-
Notifications
You must be signed in to change notification settings - Fork 6
/
background.js
1145 lines (1033 loc) · 41.7 KB
/
background.js
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
let WJR_DEBUG = false;
//Ensure browser cache isn't going to cause us problems
browser.webRequest.handlerBehaviorChanged();
//User feedback
browser.runtime.onInstalled.addListener(async ({ reason, temporary, }) => {
if (temporary) return; // skip during development
switch (reason) {
case "update": {
const url = browser.runtime.getURL("https://docs.google.com/forms/d/e/1FAIpQLSfkmwmDvV0vK5x8s1rmgCNWRoj5d7FOxu4-4scyrzMy2nuJbQ/viewform?usp=sf_link");
await browser.tabs.create({ url, });
} break;
}
});
browser.runtime.setUninstallURL("https://docs.google.com/forms/d/e/1FAIpQLSfYLfDewK-ovU-fQXOARqvNRaaH18UGxI2S6tAQUKv5RNSGaQ/viewform?usp=sf_link");
statusInitialize();
let BK_connectedClients = {};
let BK_openFilters = {};
let BK_openB64Filters = {};
let BK_openVidFilters = {};
let BK_isInitialized = false;
function bkInitialize() {
statusOnLoaded();
bkUpdateFromSettings();
bkSetEnabled(true); //always start on
}
function bkOnClientConnected(port) {
WJR_DEBUG && console.log(`LIFECYCLE: Processor ${port.name} connected.`);
let registration = { port: port, tabId: null, processorId: port.name, backend: 'unknown' };
BK_connectedClients[registration.processorId] = registration;
WJR_DEBUG && console.log(`LIFECYCLE: There are now ${Object.keys(BK_connectedClients).length} processors`);
port.onMessage.addListener(bkOnProcessorMessage);
bkNotifyThreshold();
bkBroadcastProcessorSettings();
if (!BK_isInitialized) {
BK_isInitialized = true;
bkInitialize();
}
}
let BK_currentProcessorIndex = 0;
function bkGetNextProcessor() {
if (Object.keys(BK_connectedClients).length == 0) {
return null;
}
//TODO Right now we only use primary.
for(let key of Object.keys(BK_connectedClients)) {
if(BK_connectedClients[key].backend == BK_processorBackendPreference[0]) {
WJR_DEBUG && console.debug(`BACKEND: Selecting client ${key}`);
return BK_connectedClients[key];
}
}
return null;
}
function bkBroadcastMessageToProcessors(m) {
Object.keys(BK_connectedClients).forEach(c => {
BK_connectedClients[c].port.postMessage(m);
});
}
let BK_isSilentModeEnabled = false;
function bkBroadcastProcessorSettings() {
bkBroadcastMessageToProcessors({
type: 'settings',
isSilentModeEnabled: BK_isSilentModeEnabled
});
}
browser.runtime.onConnect.addListener(bkOnClientConnected);
let BK_processorBackendPreference = [];
function bkReloadProcessors() {
WJR_DEBUG && console.log('LIFECYCLE: Cleaning up old processors.');
let keys = Object.keys(BK_connectedClients);
for (let key of keys) {
let client = BK_connectedClients[key];
browser.tabs.remove(client.tabId);
delete BK_connectedClients[key];
}
WJR_DEBUG && console.log('LIFECYCLE: Spawning new processors.');
for(let i=0; i<BK_processorBackendPreference.length; i++) {
let backend = BK_processorBackendPreference[i];
WJR_DEBUG && console.log(`LIFECYCLE: Spawning processor with backend ${backend}`);
browser.tabs.create({url:`/processor.html?backend=${backend}&id=${backend}-1`, active: false})
.then(async tab=>await browser.tabs.hide(tab.id));
}
WJR_DEBUG && console.log('LIFECYCLE: New processors are launching!');
}
function bkOnProcessorMessage(m) {
switch (m.type) {
case 'scan': {
WJR_DEBUG && console.debug('PROC: '+m);
if(m.requestId.startsWith('crash')) {
bkHandleCrashDetectionResult(m);
} else {
let filter = BK_openFilters[m.requestId];
filter.write(m.imageBytes);
filter.close();
delete BK_openFilters[m.requestId];
WJR_DEBUG && console.debug('OPEN FILTERS: '+Object.keys(BK_openFilters).length);
}
}
break;
case 'gif_scan': {
gifOnGifFrame(m);
}
break;
case 'b64_data': {
let b64Filter = BK_openB64Filters[m.requestId];
let b64Text = b64Filter.encoder.encode(m.dataStr);
b64Filter.filter.write(b64Text);
}
break;
case 'b64_close': {
let b64Filter = BK_openB64Filters[m.requestId];
b64Filter.filter.close();
delete BK_openB64Filters[m.requestId];
}
break;
case 'vid_scan': {
vidOnVidScan(m);
}
break;
case 'stat': {
WJR_DEBUG && console.debug('STAT: '+m.requestId+' '+m.result);
statusCompleteImageCheck(m.requestId, m.result);
switch (m.result) {
case 'pass': {
bkIncrementPassCount();
}
break;
case 'block': {
bkIncrementBlockCount();
}
//could also be tiny or error
}
}
break;
case 'registration': {
WJR_DEBUG && console.dir(BK_connectedClients);
WJR_DEBUG && console.log(`LIFECYCLE: Registration of processor ${m.processorId} with tab ID ${m.tabId}`);
BK_connectedClients[m.processorId].backend = m.backend;
BK_connectedClients[m.processorId].tabId = m.tabId;
}
break;
}
}
/////////// ZONE START /////////////////////////
var BK_isZoneAutomatic = true;
var BK_predictionBufferBlockCount = 0;
var BK_predictionBuffer = [];
var BK_estimatedTruePositivePercentage = 0;
var BK_isEstimateValid = false;
function bkAddToPredictionBuffer(prediction) {
BK_predictionBuffer.push(prediction);
if (prediction > 0) {
BK_predictionBufferBlockCount++;
}
if (BK_predictionBuffer.length > 200) {
let oldPrediction = BK_predictionBuffer.shift();
if (oldPrediction > 0) {
BK_predictionBufferBlockCount--;
}
}
if (BK_predictionBuffer.length > 50) {
let estimatedTruePositiveCount = BK_zonePrecision * BK_predictionBufferBlockCount;
BK_estimatedTruePositivePercentage = estimatedTruePositiveCount / BK_predictionBuffer.length;
BK_isEstimateValid = true;
} else {
BK_estimatedTruePositivePercentage = 0;
BK_isEstimateValid = false;
}
}
function bkClearPredictionBuffer() {
BK_predictionBufferBlockCount = 0;
BK_predictionBuffer = [];
BK_estimatedTruePositivePercentage = 0;
}
function bkIncrementBlockCount() {
bkAddToPredictionBuffer(1);
bkCheckZone();
}
function bkIncrementPassCount() {
bkAddToPredictionBuffer(0);
bkCheckZone();
}
function bkSetZoneAutomatic(isAutomatic) {
BK_isZoneAutomatic = isAutomatic;
}
function bkSetDefaultZone(result) {
console.log('result');
console.log(result);
if (!result.default_zone || result.default_zone === 'automatic') {
bkSetZoneAutomatic(true);
BK_zone = 'neutral'
} else {
bkSetZoneAutomatic(false);
BK_zone = result.default_zone;
}
}
function bkCheckZone() {
if (!BK_isEstimateValid) {
return;
}
if (!BK_isZoneAutomatic) {
return;
}
let requestedZone = 'untrusted';
if (BK_estimatedTruePositivePercentage < ROC_trustedToNeutralPercentage) {
requestedZone = 'trusted';
} else if (BK_estimatedTruePositivePercentage < ROC_neutralToUntrustedPercentage) {
requestedZone = 'neutral';
}
if (requestedZone != BK_zone) {
bkSetZone(requestedZone);
}
}
var BK_zoneThreshold = ROC_neutralRoc.threshold;
var BK_zonePrecision = rocCalculatePrecision(ROC_neutralRoc);
WJR_DEBUG && console.log("Zone precision is: "+BK_zonePrecision);
var BK_zone = 'neutral';
function bkSetZone(newZone)
{
WJR_DEBUG && console.log('Zone request to: '+newZone);
let didZoneChange = false;
switch (newZone) {
case 'trusted':
BK_zoneThreshold = ROC_trustedRoc.threshold;
BK_zonePrecision = rocCalculatePrecision(ROC_trustedRoc);
statusSetImageZoneTrusted();
BK_zone = newZone;
didZoneChange = true;
WJR_DEBUG && console.log('Zone is now trusted!');
break;
case 'neutral':
BK_zoneThreshold = ROC_neutralRoc.threshold;
BK_zonePrecision = rocCalculatePrecision(ROC_neutralRoc);
statusSetImageZoneNeutral();
BK_zone = newZone;
didZoneChange = true;
WJR_DEBUG && console.log('Zone is now neutral!');
break;
case 'untrusted':
BK_zoneThreshold = ROC_untrustedRoc.threshold;
BK_zonePrecision = rocCalculatePrecision(ROC_untrustedRoc);
statusSetImageZoneUntrusted();
BK_zone = newZone;
didZoneChange = true;
WJR_DEBUG && console.log('Zone is now untrusted!')
break;
}
if(didZoneChange) {
WJR_DEBUG && console.log("Zone precision is: "+BK_zonePrecision);
bkClearPredictionBuffer();
bkNotifyThreshold();
}
}
function bkNotifyThreshold() {
bkBroadcastMessageToProcessors({
type: 'thresholdChange',
threshold: BK_zoneThreshold
});
}
////////////////////// ZONE END //////////////////////////
//////////////////// WATCHDOG START //////////////////////
/* Cleanup counts across all types */
let BK_watchdogCleanupCount = 0;
let BK_watchdogKickCount = 0;
async function bkWatchdogGeneric(watchdogName, whichFilters, cleanupAction) {
let keysSnapshot = Object.keys(whichFilters);
let nowish = performance.now();
let cleaned = [];
let watchList = [];
WJR_DEBUG && console.info(`WATCHDOG: Stuck ${watchdogName} check - Current open filters count: ${keysSnapshot.length} Watchdog kick: ${BK_watchdogKickCount} Total cleaned up: ${BK_watchdogCleanupCount}`);
for(let key of keysSnapshot) {
let ageMs = whichFilters[key] ? nowish - whichFilters[key].stopTime : 0;
if (ageMs >= 45000) {
BK_watchdogCleanupCount++;
delete whichFilters[key];
cleanupAction(key, 'error');
cleaned.push(key);
BK_watchdogCleanupCount++;
} else if (ageMs >= 30000) {
watchList.push(key);
}
}
if (cleaned.length > 0) {
console.error(`WATCHDOG: Stuck ${watchdogName} check watchdog cleaned up ${cleaned.join(',')} for a total kick count ${BK_watchdogKickCount}`);
}
if (watchList.length > 0) {
console.warn(`WATCHDOG: Stuck ${watchdogName} check old age watchlist ${watchList.join(',')}`);
}
}
async function bkWatchdog() {
await bkWatchdogGeneric('image', BK_openFilters, statusCompleteImageCheck);
await bkWatchdogGeneric('base64 image', BK_openB64Filters, statusCompleteImageCheck);
await bkWatchdogGeneric('video', BK_openVidFilters, statusCompleteVideoCheck);
}
setInterval(bkWatchdog, 2500);
let CRASH_DETECTION_IMAGE = null;
fetch('silent_data/zoe-reeve-ijRuGjKpBcg-unsplash.jpg')
.then(async r => {
CRASH_DETECTION_IMAGE = await r.arrayBuffer();
setInterval(bkCrashDetectionWatchdog, 7500);
});
let CRASH_DETECTION_EXPECTED_RESULT;
let CRASH_DETECTION_WARMUPS_LEFT = 3;
let CRASH_DETECTION_COUNT = 0;
let CRASH_NO_PROCESSOR_COUNT = 0;
let CRASH_BAD_STATE_ENCOUNTERED_COUNT = 0;
const CRASH_NO_PROCESSOR_RESTART_THRESHOLD = 3;
const CRASH_BAD_STATE_RESTART_THRESHOLD = 2;
const CRASH_IDLE_SECONDS = 3 * 60;
async function bkCrashDetectionWatchdog() {
let idleState = await browser.idle.queryState(CRASH_IDLE_SECONDS)
if(idleState != 'active') {
console.log('CRASH: User not active, ceasing crash check.');
return;
}
let pseudoRequestId = `crash-detection-${CRASH_DETECTION_COUNT}`;
CRASH_DETECTION_COUNT++;
let processorReq = bkGetNextProcessor();
if (!processorReq) {
CRASH_NO_PROCESSOR_COUNT++;
if(CRASH_NO_PROCESSOR_COUNT >= CRASH_NO_PROCESSOR_RESTART_THRESHOLD) {
console.error(`CRASH: No processors found after extended time - reloading.`);
browser.runtime.reload();
}
console.warn(`CRASH: Processors not yet ready.`);
return;
}
try {
let processor = processorReq.port;
processor.postMessage({
type: 'start',
requestId: pseudoRequestId,
mimeType: 'image/jpeg',
url: pseudoRequestId
});
processor.postMessage({
type: 'ondata',
requestId: pseudoRequestId,
data: CRASH_DETECTION_IMAGE
});
processor.postMessage({
type: 'onstop',
requestId: pseudoRequestId
});
} catch(e) {
CRASH_NO_PROCESSOR_COUNT++;
if(CRASH_NO_PROCESSOR_COUNT >= CRASH_NO_PROCESSOR_RESTART_THRESHOLD) {
console.error(`CRASH: Failure to post to processor after extended time - reloading.`);
browser.runtime.reload();
}
console.error(`CRASH: Failure to post to processor.`);
}
}
function bkApproxEq(expected, actual) {
return Math.abs(actual - expected) < 0.02;
}
function bkCompareSqrxScores(x, a) {
return bkApproxEq(x[0][0],a[0][0])
&& bkApproxEq(x[1][0],a[1][0])
&& bkApproxEq(x[1][1],a[1][1])
&& bkApproxEq(x[1][2],a[1][2])
&& bkApproxEq(x[1][3],a[1][3]);
}
function bkHandleCrashDetectionResult(m) {
if (!CRASH_DETECTION_EXPECTED_RESULT) {
if(CRASH_DETECTION_WARMUPS_LEFT > 0) {
CRASH_DETECTION_WARMUPS_LEFT -= 1;
console.log(`CRASH: Warmups left before setting crash result ${CRASH_DETECTION_WARMUPS_LEFT}`);
} else {
CRASH_DETECTION_EXPECTED_RESULT = { ... m.sqrxrScore};
console.log(`CRASH: Setting expected result to ${JSON.stringify(CRASH_DETECTION_EXPECTED_RESULT)}`);
}
} else {
let actual = m.sqrxrScore;
if (!bkCompareSqrxScores(CRASH_DETECTION_EXPECTED_RESULT,actual)) {
console.error(`CRASH: Check actual ${JSON.stringify(actual)} vs. Expected ${JSON.stringify(CRASH_DETECTION_EXPECTED_RESULT)}`);
CRASH_BAD_STATE_ENCOUNTERED_COUNT++;
if (CRASH_BAD_STATE_ENCOUNTERED_COUNT >= CRASH_BAD_STATE_RESTART_THRESHOLD) {
console.error(`CRASH: Bad state threshold exceeded, reloading plugin!!!`);
browser.runtime.reload();
}
} else {
console.log(`CRASH: Detection passed`);
}
}
}
///////////////// WATCHDOG END ////////////////////////////
async function bkImageListener(details, shouldBlockSilently = false) {
if (details.statusCode < 200 || 300 <= details.statusCode) {
return;
}
if (whtIsWhitelisted(details.url)) {
WJR_DEBUG && console.log('WEBREQ: Normal whitelist '+details.url);
return;
}
let mimeType = '';
for (let i = 0; i < details.responseHeaders.length; i++) {
let header = details.responseHeaders[i];
if (header.name.toLowerCase() == "content-type") {
mimeType = header.value;
if (!shouldBlockSilently) {
header.value = 'image/svg+xml';
}
break;
}
}
let isGif = mimeType.startsWith('image/gif');
if(isGif) {
return await gifListener(details);
}
return await bkImageListenerNormal(details, mimeType);
}
async function bkImageListenerNormal(details, mimeType) {
WJR_DEBUG && console.debug('WEBREQ: start headers '+details.requestId);
let dataStartTime = null;
let filter = browser.webRequest.filterResponseData(details.requestId);
let processor = bkGetNextProcessor().port;
processor.postMessage({
type: 'start',
requestId: details.requestId,
mimeType: mimeType,
url: details.url
});
statusStartImageCheck(details.requestId);
filter.ondata = event => {
if (dataStartTime == null) {
dataStartTime = performance.now();
}
WJR_DEBUG && console.debug('WEBREQ: data '+details.requestId);
processor.postMessage({
type: 'ondata',
requestId: details.requestId,
data: event.data
});
}
filter.onerror = e => {
try
{
WJR_DEBUG && console.debug('WEBREQ: error '+details.requestId);
processor.postMessage({
type: 'onerror',
requestId: details.requestId
});
filter.close();
}
catch (ex) {
console.error('WEBREQ: Filter error: ' + e + ', ' + ex);
}
}
filter.onstop = async event => {
WJR_DEBUG && console.debug('WEBREQ: onstop '+details.requestId);
filter.stopTime = performance.now();
BK_openFilters[details.requestId] = filter;
processor.postMessage({
type: 'onstop',
requestId: details.requestId
});
}
return details;
}
async function bkDirectTypedUrlListener(details) {
if (details.statusCode < 200 || 300 <= details.statusCode) {
return;
}
if (whtIsWhitelisted(details.url)) {
WJR_DEBUG && console.log('WEBREQ: Direct typed whitelist '+details.url);
return;
}
//Try to see if there is an image MIME type
for (let i = 0; i < details.responseHeaders.length; i++) {
let header = details.responseHeaders[i];
if (header.name.toLowerCase() == "content-type") {
let mimeType = header.value;
if(mimeType.startsWith('image/')) {
WJR_DEBUG && console.log('WEBREQ: Direct URL: Forwarding based on mime type: '+mimeType+' for '+details.url);
return bkImageListener(details,true);
}
}
}
//Otherwise do nothing...
return details;
}
///////////////////////////////////////////////// DNS Lookup Tie-in /////////////////////////////////////////////////////////////
BK_shouldUseDnsBlocking = false;
async function bkDnsBlockListener(details) {
let dnsResult = await dnsIsDomainOk(details.url);
if(!dnsResult) {
WJR_DEBUG && console.log('DNS: DNS Blocked '+details.url);
return { cancel: true };
}
return details;
}
function bkSetDnsBlocking(onOrOff) {
let effectiveOnOrOff = onOrOff && BK_isEnabled;
WJR_DEBUG && console.log('CONFIG: DNS blocking set request: '+onOrOff+', effective value '+effectiveOnOrOff);
let isCurrentlyOn = browser.webRequest.onBeforeRequest.hasListener(bkDnsBlockListener);
if (effectiveOnOrOff != isCurrentlyOn) {
BK_shouldUseDnsBlocking = onOrOff; //Store the requested, not effective value
if(effectiveOnOrOff && !isCurrentlyOn) {
WJR_DEBUG && console.log('CONFIG: DNS Adding DNS block listener')
browser.webRequest.onBeforeRequest.addListener(
bkDnsBlockListener,
{ urls: ["<all_urls>"], types: ["image", "imageset", "media"] },
["blocking"]
);
} else if (!effectiveOnOrOff && isCurrentlyOn) {
WJR_DEBUG && console.log('CONFIG: DNS Removing DNS block listener')
browser.webRequest.onBeforeRequest.removeListener(bkDnsBlockListener);
}
WJR_DEBUG && console.log('CONFIG: DNS blocking is now: '+onOrOff);
} else {
WJR_DEBUG && console.log('CONFIG: DNS blocking is already correctly set.');
}
}
//Use this if you change BK_isEnabled
function bkRefreshDnsBlocking() {
bkSetDnsBlocking(BK_shouldUseDnsBlocking);
}
////////////////////////////////base64 IMAGE SEARCH SPECIFIC STUFF BELOW, BOO HISS!!!! ///////////////////////////////////////////
// Listen for any Base 64 encoded images, particularly the first page of
// "above the fold" image search requests in Google Images
async function bkBase64ContentListener(details) {
if (details.statusCode < 200 || 300 <= details.statusCode) {
return;
}
if (whtIsWhitelisted(details.url)) {
WJR_DEBUG && console.log('WEBREQ: Base64 whitelist '+details.url);
return;
}
WJR_DEBUG && console.debug('WEBREQ: base64 headers '+details.requestId+' '+details.url);
// The received data is a stream of bytes. In order to do text-based
// modifications, it is necessary to decode the bytes into a string
// using the proper character encoding, do any modifications, then
// encode back into a stream of bytes.
// Historically, detecting character encoding has been a tricky task
// taken on by the browser. Here, a simplified approach is taken
// and the complexity is hidden in a helper method.
let decoderEncoder = bkDetectCharsetAndSetupDecoderEncoder(details);
if (!decoderEncoder) {
return;
}
let [decoder, encoder] = decoderEncoder;
if (!decoder) {
return;
}
let filter = browser.webRequest.filterResponseData(details.requestId);
let b64Filter = {
requestId: details.requestId,
encoder: encoder,
filter: filter
};
BK_openB64Filters[details.requestId] = b64Filter;
//Choose highest power here because we have many images possibly
let processor = bkGetNextProcessor().port;
processor.postMessage({
type: 'b64_start',
requestId: details.requestId
});
filter.ondata = evt => {
let str = decoder.decode(evt.data, { stream: true });
processor.postMessage({
type: 'b64_ondata',
requestId: details.requestId,
dataStr: str
});
};
filter.onstop = async evt => {
let str = decoder.decode(evt.data, { stream: true });
processor.postMessage({
type: 'b64_ondata',
requestId: details.requestId,
dataStr: str
});
processor.postMessage({
type: 'b64_onstop',
requestId: details.requestId
});
}
filter.onerror = e => {
try {
processor.postMessage({
type: 'b64_onerror',
requestId: details.requestId
})
}
catch (e) {
console.error('WEBREQ: Filter error: ' + e);
}
}
return details;
}
// This helper method does a few things regarding character encoding:
// 1) Detects the charset for the TextDecoder so that bytes are properly turned into strings
// 2) Ensures the output Content-Type is UTF-8 because that is what TextEncoder supports
// 3) Returns the decoder/encoder pair
function bkDetectCharsetAndSetupDecoderEncoder(details) {
let contentType = '';
let headerIndex = -1;
for (let i = 0; i < details.responseHeaders.length; i++) {
let header = details.responseHeaders[i];
if (header.name.toLowerCase() == "content-type") {
contentType = header.value.toLowerCase();
headerIndex = i;
break;
}
}
for (let i = 0; i < details.responseHeaders.length; i++) {
let header = details.responseHeaders[i];
WJR_DEBUG && console.debug('CHARSET: '+header.name+': '+header.value);
}
if (headerIndex == -1) {
WJR_DEBUG && console.debug('CHARSET: No Content-Type header detected for '+details.url+', adding one by guessing.');
contentType = bkGuessContentType(details);
headerIndex = details.responseHeaders.length;
details.responseHeaders.push(
{
"name": "Content-Type",
"value": contentType
}
);
}
let baseType;
let trimmedContentType = contentType.trim();
if(trimmedContentType.startsWith('text/html')) {
baseType = 'text/html';
WJR_DEBUG && console.debug('CHARSET: Detected base type was '+baseType);
} else if(trimmedContentType.startsWith('application/xhtml+xml')) {
baseType = 'application/xhtml+xml';
WJR_DEBUG && console.debug('CHARSET: Detected base type was '+baseType);
} else if(trimmedContentType.startsWith('image/')) {
WJR_DEBUG && console.debug('CHARSET: Base64 listener is ignoring '+details.requestId+' because it is an image/ MIME type');
return;
} else if(trimmedContentType == 'application/pdf') {
WJR_DEBUG && console.debug('CHARSET: Base64 listener is ignoring '+details.requestId+' because it is a PDF MIME type');
return;
} else {
baseType = 'text/html';
WJR_DEBUG && console.debug('CHARSET: The Content-Type was '+contentType+', not text/html or application/xhtml+xml.');
return;
}
// Character set detection is quite a difficult problem.
// If modifying this block of code, ensure that the tests at
// https://www.w3.org/2006/11/mwbp-tests/index.xhtml
// all pass - current implementation passes on all
let decodingCharset = 'utf-8';
let detectedCharset = bkDetectCharset(contentType);
if (detectedCharset !== undefined) {
decodingCharset = detectedCharset;
WJR_DEBUG && console.debug('CHARSET: Detected charset was ' + decodingCharset + ' for ' + details.url);
} else if(trimmedContentType.startsWith('application/xhtml+xml')) {
decodingCharset = 'utf-8';
WJR_DEBUG && console.debug('CHARSET: No detected charset, but content type was application/xhtml+xml so using UTF-8');
} else {
decodingCharset = undefined;
WJR_DEBUG && console.debug('CHARSET: No detected charset, moving ahead with Windows-1252 until sniff finds an encoding or decoding error encountered!');
}
let decoder = new TextDecoderWithSniffing(decodingCharset);
let encoder = new TextEncoderWithSniffing(decoder);
return [decoder, encoder];
}
function bkConcatBuffersToUint8Array(buffers) {
let fullLength = buffers.reduce((acc,buf)=>acc+buf.byteLength, 0);
let result = new Uint8Array(fullLength);
let offset = 0;
for(let buffer of buffers) {
result.set(new Uint8Array(buffer), offset);
offset += buffer.byteLength;
}
return result;
}
function bkIsUtf8Alias(declType) {
//Passes all 6 aliases found at https://encoding.spec.whatwg.org/#names-and-labels
return (/.*utf.?8/gmi.test(declType));
}
function bkSniffExtractEncoding(sniffString) {
try {
const xmlParts = /<\?xml\sversion="1\.0"\s+encoding="([^"]+)"\?>/gm.exec(sniffString);
if(xmlParts) {
return xmlParts[1];
}
const metaParts = /<meta[^>]+charset="?([^"]+)"/igm.exec(sniffString);
if(metaParts) {
return metaParts[1];
}
} catch (ex) {
console.error('CHARSET: Sniff extraction exception: '+ex);
}
return null;
}
function TextDecoderWithSniffing(declType)
{
let self = this;
self.currentType = declType;
self.decoder = (self.currentType === undefined) ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : new TextDecoder(self.currentType);
self.sniffBufferList = [];
self.sniffCount = 0;
self.decode = function(buffer, options) {
if(self.currentType === undefined) {
try {
if(self.sniffCount < 512) {
//Start by checking for BOM
//Buffer should always be >= 3 but just in case...
if(self.sniffCount == 0 && buffer.byteLength >= 3) {
let bom = new Uint8Array(buffer, 0, 3);
if(bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) {
WJR_DEBUG && console.log('CHARSET: Sniff found utf-8 BOM');
self.currentType = 'utf-8';
}
}
//Continue with normal header sniffing
if(self.currentType === undefined) {
self.sniffBufferList.push(buffer);
self.sniffCount += buffer.byteLength;
WJR_DEBUG && console.debug('CHARSET: Sniff count '+self.sniffCount);
if(self.sniffCount >= 512) {
let fullSniffBuffer = bkConcatBuffersToUint8Array(self.sniffBufferList);
self.sniffBufferList = null;
let tmpDecoder = new TextDecoder('iso-8859-1');
let sniffString = tmpDecoder.decode(fullSniffBuffer);
if(sniffString.length > 512) {
sniffString = sniffString.substring(0, 512);
}
WJR_DEBUG && console.debug('CHARSET: Sniff string constructed: '+sniffString);
let extractedEncoding = bkSniffExtractEncoding(sniffString);
if(extractedEncoding) {
WJR_DEBUG && console.log('CHARSET: Sniff found decoding of '+extractedEncoding+' by examining header, changing decoder');
self.currentType = extractedEncoding.toLowerCase();
self.decoder = new TextDecoder(self.currentType);
} else {
WJR_DEBUG && console.log('CHARSET: Sniff string did not indicate encoding');
}
}
}
}
WJR_DEBUG && console.debug('CHARSET: Sniff received a chunk, current decoding type '+self.currentType);
return self.decoder.decode(buffer, options);
} catch (ex) {
WJR_DEBUG && console.warn('CHARSET: Falling back from '+self.currentType+' to iso-8859-1 (Exception: '+ex+')');
self.decoder = new TextDecoder('iso-8859-1');
self.currentType = 'iso-8859-1';
return self.decoder.decode(buffer, options);
}
} else {
WJR_DEBUG && console.debug('CHARSET: Effective decoding ' + self.currentType);
return self.decoder.decode(buffer, options);
}
}
}
function TextEncoderWithSniffing(decoder) {
let self = this;
self.utf8Encoder = new TextEncoder();
self.linkedDecoder = decoder;
self.encode = function(str) {
WJR_DEBUG && console.debug('CHARSET: Encoding with decoder current type '+self.linkedDecoder.currentType);
if(bkIsUtf8Alias(self.linkedDecoder.currentType)) {
WJR_DEBUG && console.debug('CHARSET: Encoding utf-8');
return self.utf8Encoder.encode(str);
}
console.log('CHARSET: Test '+TEXT_ENCODINGS[self.linkedDecoder.currentType]);
let effectiveEncoding = TEXT_ENCODINGS[self.linkedDecoder.currentType] ?? TEXT_ENCODINGS['iso-8859-1'];
WJR_DEBUG && console.debug('CHARSET: Effective encoding ' + effectiveEncoding.name);
let outputRaw = [];
let untranslatableCount = 0;
for(const codePoint of str) {
let initialCodePoint = codePoint.codePointAt(0);
let bytes = effectiveEncoding.codePointsToBytes[initialCodePoint];
if(bytes !== undefined) {
for(let i=0; i<bytes.length; i++) {
outputRaw.push(bytes[i]);
}
} else {
//If no character encoding was specified, the default is a bit sketchy but locale-defined
//However, I've seen pages where it wasn't specified, the default should be iso-8859-1/Windows-1252
//and yet the content was actually utf-8. Since this is a passthrough, retry encoding as utf-8
//in that specific circumstance
if(self.linkedDecoder.currentType === undefined) {
console.warn('CHARSET: Encoding was unspecified, but iso-8859-1 encoding failed, so falling back to utf-8');
return self.utf8Encoder.encode(str);
}
if(untranslatableCount == 0) {
console.warn('CHARSET: untranslatable code point '+initialCodePoint+' found while charset='+self.linkedDecoder.currentType);
}
untranslatableCount++;
}
}
let result = new Uint8Array(outputRaw);
WJR_DEBUG && console.log('CHARSET: re-encoded '+result.length+' bytes ('+untranslatableCount+' untranslated code points) with effective encoding '+ effectiveEncoding.name);
return result;
}
}
// Guess the content type when none is supplied
// Ideally this would actually look at the bytes supplied but we
// don't have those available yet, so do some hacky guessing
function bkGuessContentType(details) {
try {
for (let i = 0; i < details.responseHeaders.length; i++) {
let header = details.responseHeaders[i];
// If no content-type was specified BUT a default filename was
// provided, fallback to a MIME type derived from the extension - YUCK
// e.g. content-disposition: inline; filename="user-guide-nokia-5310-user-guide.pdf" -> application/pdf
// Note: we will not try to handle filename* as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
// and https://datatracker.ietf.org/doc/html/rfc5987#page-7
if (header.name.toLowerCase() == "content-disposition") {
let filenameMatches = [...header.value.matchAll(/filename[ ]*=[ ]*\"([^\"]*)\"/g)];
if(filenameMatches.length > 0) {
let filename = filenameMatches[0][1]; //First capture group of first match
let extensionMatch = filename.match(/\.[^\.]+$/);
if(extensionMatch != null && extensionMatch.length > 0) {
let extension = extensionMatch[0];
switch(extension) {
case ".pdf":
WJR_DEBUG && console.debug('CHARSET: Guessed content type application/pdf using extension ' + extension + ' for ' + details.url);
return 'application/pdf';
default:
WJR_DEBUG && console.debug('CHARSET: Unhandled file extension "' + extension + '" for ' + details.url);
break;
}
}
}
break;
}
}
} catch(e) {
console.error('CHARSET: Exception guessing content type when none supplied for '+details.url+' '+e);
}
return 'text/html';
}
// Detect the charset from Content-Type
function bkDetectCharset(contentType) {
/*
From https://tools.ietf.org/html/rfc7231#section-3.1.1.5:
A parameter value that matches the token production can be
transmitted either as a token or within a quoted-string. The quoted
and unquoted values are equivalent. For example, the following
examples are all equivalent, but the first is preferred for
consistency:
text/html;charset=utf-8
text/html;charset=UTF-8
Text/HTML;Charset="utf-8"
text/html; charset="utf-8"
Internet media types ought to be registered with IANA according to
the procedures defined in [BCP13].
Note: Unlike some similar constructs in other header fields, media
type parameters do not allow whitespace (even "bad" whitespace)
around the "=" character.
...
And regarding application/xhtml+xml, from https://tools.ietf.org/html/rfc3236#section-2
and the referenced links, it can be seen that charset is handled the same way with
respect to Content-Type.
*/
let charsetMarker = "charset="; // Spaces *shouldn't* matter
let foundIndex = contentType.indexOf(charsetMarker);
if (foundIndex == -1) {
return undefined;
}
let charsetMaybeQuoted = contentType.substr(foundIndex + charsetMarker.length).trim();
let charset = charsetMaybeQuoted.replace(/\"/g, '');
return charset;
}
////////////////////////////Context Menu////////////////////////////
if (browser.menus) {
browser.menus.create({
title: "Hide Image",
documentUrlPatterns: ["*://*/*"],
contexts: ["image"],
onclick(info, tab) {
browser.tabs.executeScript(tab.id, {
frameId: info.frameId,
code: `browser.menus.getTargetElement(${info.targetElementId}).style.visibility="hidden";`,
});
},
});
}
////////////////////////Actual Startup//////////////////////////////
function bkRegisterAllCallbacks() {
browser.webRequest.onHeadersReceived.addListener(
bkImageListener,
{ urls: ["<all_urls>"], types: ["image", "imageset"] },
["blocking", "responseHeaders"]
);
browser.webRequest.onHeadersReceived.addListener(
bkDirectTypedUrlListener,
{ urls: ["<all_urls>"], types: ["main_frame"] },
["blocking", "responseHeaders"]
);
browser.webRequest.onHeadersReceived.addListener(
bkBase64ContentListener,
{
urls: [
"<all_urls>"
],
types: ["main_frame"]
},
["blocking", "responseHeaders"]
);
if (BK_isVideoEnabled) {
browser.webRequest.onBeforeRequest.addListener(
vidPrerequestListener,
{ urls: ["<all_urls>"], types: ["media", "xmlhttprequest"] },
["blocking"]