-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbackground.js
1380 lines (1212 loc) · 37.2 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
"use strict";
import { POPUP, CONTENT, BACKGROUND, NOTIFICATION, LOCATION, WORKER, emojis, certificateEmojis, statusEmojis, digitEmojis, dateTimeFormat4, numberFormat, rtf, regionNames, IPv4RE, IPv6RE, outputbase85, expand, IPv6toInt, outputseconds, outputlocation, earth, getissuer, getHSTS, getmessage, countryCode, delay } from "/common.js";
import * as AddonSettings from "/common/modules/AddonSettings/AddonSettings.js";
// import * as common from "common.js";
const TITLE = "Server Status";
const label = "PSL";
const { TAB_ID_NONE } = browser.tabs;
const ALARM1 = "updatePSL";
const ALARM2 = "updateGeoIP";
// Chrome
// Adapted from: https://github.com/mozilla/webextension-polyfill/blob/master/src/browser-polyfill.js
const IS_CHROME = Object.getPrototypeOf(browser) !== Object.prototype;
// Seconds to wait
const wait = 60;
const settings = {
icon: null,
badge: null,
color: null,
warndays: null, // Days
open: null,
dns: null,
fullipv6: null,
compactipv6: null,
blocked: null,
GeoDB: null,
update: null,
updateidle: null,
idle: null, // Seconds
map: null,
lookupip: null,
lookuphost: null,
suffix: null,
https: null,
blacklist: null,
domainblacklists: null,
ipv4blacklists: null,
ipv6blacklists: null,
send: null
};
const columns = {
download: null,
upload: null,
classification: null,
security: null,
expiration: null,
tlsversion: null,
hsts: null,
httpversion: null,
httpstatus: null
};
const tabs = new Map();
const notifications = new Map();
let IS_ANDROID = null;
let IS_LINUX = null;
let icons = null;
let certificateIcons = null;
let statusIcons = null;
let digitIcons = null;
const flagIcons = {};
let httpsOnlyMode = null;
let intervalId = null;
let args = null;
let popup = null;
let worker = null;
let date = null;
let suffixes = null;
let exceptions = null;
/**
* Create notification.
*
* @param {string} title
* @param {string} message
* @param {number} [date]
* @returns {void}
*/
function notification(title, message, date) {
console.log(title, message, date && new Date(date));
if (settings.send) {
browser.notifications.create({
type: "basic",
iconUrl: browser.runtime.getURL("icons/icon_128.png"),
title,
message,
eventTime: date
});
}
}
browser.notifications.onClicked.addListener((notificationId) => {
const url = notifications.get(notificationId);
if (url) {
browser.tabs.create({ url });
}
});
browser.notifications.onClosed.addListener((notificationId) => {
notifications.delete(notificationId);
});
/**
* Creates icon using native emoji.
* Adapted from: https://stackoverflow.com/a/56313229 and https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/setIcon#Examples
*
* @param {string} emoji
* @param {number} size
* @returns {ImageData}
*/
function getImageData(emoji, size) {
// OffscreenCanvas is not yet enabled for Firefox: https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas#browser_compatibility
const canvas = globalThis.OffscreenCanvas ? new OffscreenCanvas(size, size) : document.createElement("canvas");
const ctx = canvas.getContext("2d");
// https://bugzilla.mozilla.org/show_bug.cgi?id=1692791
if (IS_LINUX) {
ctx.font = `${size * (IS_LINUX && !IS_CHROME ? 63 / 64 : IS_ANDROID ? 57 / 64 : 7 / 8)}px sans-serif`;
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
if (IS_LINUX) {
// draw the emoji
ctx.fillText(emoji, size / 2, size * (IS_CHROME && !IS_ANDROID ? 37 / 64 : IS_LINUX ? 59 / 96 : 13 / 24));
} else {
let font_size = size / 2;
let width;
let height;
do {
++font_size;
ctx.font = `${font_size}px sans-serif`; // "Twemoji Mozilla"
const textMetrics = ctx.measureText(emoji);
width = Math.abs(textMetrics.actualBoundingBoxLeft) + Math.abs(textMetrics.actualBoundingBoxRight);
height = Math.abs(textMetrics.actualBoundingBoxAscent) + Math.abs(textMetrics.actualBoundingBoxDescent);
} while (width < size && height < size);
--font_size;
ctx.font = `${font_size}px sans-serif`; // "Twemoji Mozilla"
const textMetrics = ctx.measureText(emoji);
width = Math.abs(textMetrics.actualBoundingBoxLeft) - Math.abs(textMetrics.actualBoundingBoxRight);
height = Math.abs(textMetrics.actualBoundingBoxAscent) - Math.abs(textMetrics.actualBoundingBoxDescent);
// draw the emoji
ctx.fillText(emoji, (size + width) / 2, (size + height) / 2);
}
return ctx.getImageData(0, 0, size, size);
}
/**
* Create icons.
*
* @param {string} emoji
* @returns {Object.<number, ImageData>}
*/
function getIcons(emoji) {
const icons = {};
for (const size of [16, 32, 64, 128]) {
icons[size] = getImageData(emoji, size);
}
return icons;
}
/**
* Set the browserAction icon.
*
* @param {number|null} tabId
* @param {ImageData|null} icon
* @param {string|null} title
* @param {string|null} text
* @param {string|null} backgroundColor
* @returns {void}
*/
function setIcon(tabId, icon, title, text, backgroundColor) {
// console.log(tabId, icon, title, text, backgroundColor);
browser.browserAction.setIcon({
imageData: icon,
tabId
});
browser.browserAction.setTitle({
title,
tabId
});
if (settings.badge) {
browser.browserAction.setBadgeText({
text,
tabId
});
browser.browserAction.setBadgeBackgroundColor({
color: backgroundColor,
tabId
});
}
}
/**
* Update the browserAction icon.
*
* @param {number} tabId
* @param {Object} tab
* @param {Object} tab.details
* @param {Object} tab.securityInfo
* @param {Object} [tab.performance]
* @returns {Promise<void>}
*/
async function updateIcon(tabId, tab) {
const { details, securityInfo } = tab;
// console.log(tabId, details, securityInfo);
let icon = null;
const title = [`𝗦𝘁𝗮𝘁𝘂𝘀: ${details.statusLine}`]; // Status
let text = null;
let backgroundColor = null;
if (details.ip) {
const ipv4 = IPv4RE.test(details.ip);
const ipv6 = IPv6RE.test(details.ip);
console.assert(ipv4 || ipv6, "Error: Unknown IP address", details.ip);
if (ipv4) {
// IPv4 address
title.push(`𝗜𝗣𝘃𝟰 𝗮𝗱𝗱𝗿𝗲𝘀𝘀: ${details.ip}`);
} else if (ipv6) {
// IPv6 address
title.push(`𝗜𝗣𝘃𝟲 𝗮𝗱𝗱𝗿𝗲𝘀𝘀: ${settings.fullipv6 ? expand(details.ip).join(":") : settings.compactipv6 ? outputbase85(IPv6toInt(expand(details.ip).join(""))) : details.ip}`);
}
if (settings.icon === 6) {
if (ipv4) {
icon = digitIcons[4];
text = "v4";
backgroundColor = "red";
} else if (ipv6) {
icon = digitIcons[6];
text = "v6";
backgroundColor = "green";
}
}
} else if (settings.icon === 6) {
icon = details.fromCache ? icons.globe_with_meridians : icons.black_question_mark_ornament;
}
if (settings.GeoDB) {
if (details.ip) {
const info = await getGeoIP(details.ip);
console.log(details.ip, info);
const country = info?.country;
// Server location
title.push(`𝗦𝗲𝗿𝘃𝗲𝗿 𝗹𝗼𝗰𝗮𝘁𝗶𝗼𝗻: ${country ? `${outputlocation(info)} (${country}) ${countryCode(country)}${info.lon == null ? "" : ` ${earth(info.lon)}`}` : "Unknown"}`);
if (settings.icon === 1) {
if (country) {
if (!(country in flagIcons)) {
const flag = countryCode(country);
flagIcons[country] = getIcons(flag);
}
icon = flagIcons[country];
text = country;
backgroundColor = settings.color;
} else {
icon = icons.black_question_mark_ornament;
}
}
} else if (settings.icon === 1) {
icon = details.fromCache ? icons.globe_with_meridians : icons.black_question_mark_ornament;
}
} else if (settings.icon === 1) {
title.unshift("Error: Geolocation database disabled");
icon = certificateIcons.cross_mark;
}
let state = "";
if (securityInfo.state === "insecure") {
state = "Insecure";
if (settings.icon === 2 || settings.icon === 3) {
icon = certificateIcons.open_lock;
}
} else if (securityInfo.state === "broken" || securityInfo.isUntrusted || securityInfo.isNotValidAtThisTime || securityInfo.isDomainMismatch) {
state = getmessage(securityInfo);
} else if (securityInfo.state === "weak") {
state = `Weak${securityInfo.weaknessReasons ? ` (${securityInfo.weaknessReasons})` : ""}`;
}
if (state) {
// Connection
title.push(`𝗖𝗼𝗻𝗻𝗲𝗰𝘁𝗶𝗼𝗻: ${state}`);
}
if (securityInfo.state !== "insecure") {
if (securityInfo.certificates.length) {
const [certificate] = securityInfo.certificates;
const { /* start, */ end } = certificate.validity;
const sec = Math.floor((end - details.timeStamp) / 1000);
const days = Math.floor(sec / 86400);
const { issuer } = certificate;
const aissuer = getissuer(issuer);
// console.log(end, days, new Date(end));
// Certificate expiration
// sec > 0 ? outputdateRange(start, end) : outputdate(end)
title.push(`𝗖𝗲𝗿𝘁𝗶𝗳𝗶𝗰𝗮𝘁𝗲: ${sec > 0 ? "Expires" : "Expired"} ${rtf.format(days, "day")} (${dateTimeFormat4.format(new Date(end))})`);
// Certificate issuer
title.push(`𝗜𝘀𝘀𝘂𝗲𝗿: ${aissuer.O || aissuer.CN || issuer}${aissuer.L ? `, ${aissuer.L}` : ""}${aissuer.S ? `, ${aissuer.S}` : ""}${aissuer.C ? `, ${regionNames.of(aissuer.C)} (${aissuer.C}) ${countryCode(aissuer.C)}` : ""}`);
// SSL/TLS protocol
title.push(`𝗦𝗦𝗟/𝗧𝗟𝗦 𝗽𝗿𝗼𝘁𝗼𝗰𝗼𝗹: ${securityInfo.protocolVersion}${securityInfo.secretKeyLength ? `, ${securityInfo.secretKeyLength} bit keys` : ""}`);
if (settings.icon === 2) {
if (sec > 0) {
if (days > settings.warndays) {
icon = certificateIcons.lock;
backgroundColor = "green";
} else {
icon = certificateIcons.warning_sign;
backgroundColor = "yellow";
}
} else {
icon = certificateIcons.cross_mark;
backgroundColor = "red";
}
text = sec > 0 && days === 0 ? `< ${numberFormat.format(1)}` : numberFormat.format(days);
} else if (settings.icon === 3) {
const version = securityInfo.protocolVersion;
if (version.startsWith("TLSv")) {
const [major, minor] = version.slice("TLSv".length).split(".").map((x) => Number.parseInt(x, 10));
if (major === 1) {
icon = minor < digitIcons.length ? digitIcons[minor] : icons.black_question_mark_ornament;
if (minor === 0 || minor === 1) {
backgroundColor = "red";
} else if (minor === 2) {
backgroundColor = "blue";
} else if (minor >= 3) {
backgroundColor = "green";
}
} else if (major > 1) {
icon = icons.black_question_mark_ornament;
backgroundColor = settings.color;
}
text = version.slice("TLSv".length);
} else {
icon = icons.black_question_mark_ornament;
text = version;
backgroundColor = settings.color;
}
}
}
if (securityInfo.state === "broken" || securityInfo.isUntrusted || securityInfo.isNotValidAtThisTime || securityInfo.isDomainMismatch) {
if (settings.icon === 2 || settings.icon === 3) {
icon = certificateIcons.cross_mark;
backgroundColor = "red";
}
}
let atitle = "";
if (details.responseHeaders) {
// console.log(details.responseHeaders);
const header = details.responseHeaders.find((e) => e.name.toLowerCase() === "strict-transport-security");
if (header) {
const aheader = getHSTS(header.value);
// console.log(header, aheader);
atitle += `✔ Yes (${outputseconds(Number.parseInt(aheader["max-age"], 10))})`;
} else {
atitle += securityInfo.hsts ? "✔ Yes" : "✖ No";
}
// console.assert(!!header === securityInfo.hsts, "Error: HSTS", header, securityInfo.hsts);
} else {
atitle += securityInfo.hsts ? "✔ Yes" : "✖ No";
}
// HSTS
title.push(`𝗛𝗦𝗧𝗦: ${atitle}`);
}
switch (settings.icon) {
case 4: {
const { statusCode } = details;
if (statusCode >= 100 && statusCode < 200) {
icon = statusIcons.large_blue_square;
backgroundColor = "blue";
} else if (statusCode >= 200 && statusCode < 300) {
icon = statusIcons.large_green_square;
backgroundColor = "green";
} else if (statusCode >= 300 && statusCode < 400) {
icon = statusIcons.large_yellow_square;
backgroundColor = "yellow";
} else {
// I'm a teapot, RFC 2324: https://datatracker.ietf.org/doc/html/rfc2324
icon = statusCode === 418 ? statusIcons.teapot : statusIcons.large_red_square;
backgroundColor = "red";
}
text = statusCode.toString();
break;
}
case 5: {
// Get HTTP version
const re = /^HTTP\/(\d+(?:\.\d+)?) (\d{3})(?: .*)?$/u;
const regexResult = re.exec(details.statusLine);
console.assert(regexResult, "Error: Unknown HTTP Status", details.statusLine);
if (regexResult) {
const [, version] = regexResult;
const [major, minor] = version.split(".").map((x) => Number.parseInt(x, 10));
icon = major < digitIcons.length ? digitIcons[major] : icons.black_question_mark_ornament;
switch (major) {
case 0:
backgroundColor = "red";
break;
case 1:
backgroundColor = minor === 0 ? "red" : "blue";
break;
case 2:
backgroundColor = "teal";
break;
default: if (major >= 3) {
backgroundColor = "green";
}
}
text = version;
} else {
icon = icons.black_question_mark_ornament;
text = details.statusLine;
backgroundColor = settings.color;
}
break;
}
case 7:
if (tab.performance) {
const [navigation] = tab.performance.navigation;
const start = navigation.redirectCount ? navigation.redirectStart : navigation.fetchStart;
const load = navigation.loadEventStart - start;
if (load <= 2500) {
icon = statusIcons.large_green_square;
backgroundColor = "green";
} else if (load <= 4000) {
icon = statusIcons.large_yellow_square;
backgroundColor = "yellow";
} else {
icon = statusIcons.large_red_square;
backgroundColor = "red";
}
text = numberFormat.format(load);
}
break;
case 8:
if (tab.performance?.lcp) {
const lcp = tab.performance.lcp.at(-1);
if (lcp.startTime <= 2500) {
icon = statusIcons.large_green_square;
backgroundColor = "green";
} else if (lcp.startTime <= 4000) {
icon = statusIcons.large_yellow_square;
backgroundColor = "yellow";
} else {
icon = statusIcons.large_red_square;
backgroundColor = "red";
}
text = numberFormat.format(lcp.startTime);
}
break;
}
setIcon(tabId, icon, title.join(" \n"), text, backgroundColor);
}
/**
* Update active tab.
*
* @param {Object} details
* @returns {Promise<void>}
*/
async function updateActiveTab(details) {
if (details.frameId === 0) {
// console.log(details.url);
// console.log("webNavigation.onCommitted:", details.url, new URL(details.url).origin);
if (details.tabId && details.tabId !== TAB_ID_NONE) {
const aurl = new URL(details.url);
const title = ["http:", "https:"].includes(aurl.protocol) ? ", try ⟳ refreshing the page" : "";
if (tabs.has(details.tabId)) {
const tab = tabs.get(details.tabId);
if (tab.details?.statusLine) {
const url = new URL(tab.details.url);
if (url.origin === aurl.origin) {
updateIcon(details.tabId, tab);
// console.log(`Success: ${details.tabId}`, changeInfo.url);
} else {
const tabInfo = await browser.tabs.get(details.tabId);
// https://bugzilla.mozilla.org/show_bug.cgi?id=1455060
if (tabInfo.isInReaderMode) {
updateIcon(details.tabId, tab);
} else {
const tab = {
details: null,
securityInfo: null,
requests: new Map(),
requestSize: 0,
responseSize: 0
};
tabs.set(details.tabId, tab);
// certificateIcons.shield
setIcon(details.tabId, icons.information_source, `${TITLE} \nAccess denied for this “${aurl.protocol}” page${title}`, null, null);
console.debug("Access denied", aurl.protocol, aurl.origin, url.origin);
}
}
} else if (tab.error) {
setIcon(details.tabId, icons.information_source, `${TITLE} \nError occurred for this page: ${tab.error}`, null, null);
console.debug("Error occurred", aurl.protocol, aurl.origin, tab.error);
} else if (tab.blocked) {
setIcon(details.tabId, certificateIcons.shield, `${TITLE} \nThe browser or another add-on has blocked this page`, null, null);
console.debug("Blocked", aurl.protocol, aurl.origin);
} else {
setIcon(details.tabId, tab.details ? icons.jigsaw_puzzle_piece : icons.information_source, `${TITLE} \n${tab.details ? "Waiting for connection to complete" : "Unavailable or Access denied for this page"}${title}`, null, null);
console.debug(tab.details ? "Waiting" : "Unavailable or Access denied", aurl.protocol, aurl.origin);
}
} else {
setIcon(details.tabId, icons.jigsaw_puzzle_piece, `${TITLE} \nUnavailable for this “${aurl.protocol}” page${title}`, null, null);
// console.log(`Error: ${details.tabId}`, changeInfo.url);
console.debug("Unavailable", aurl.protocol, aurl.origin);
}
} else {
setIcon(details.tabId, icons.jigsaw_puzzle_piece, `${TITLE} \nUnavailable for this page`, null, null);
}
}
}
browser.webNavigation.onCommitted.addListener(updateActiveTab);
browser.tabs.onRemoved.addListener((tabId) => {
tabs.delete(tabId);
});
/**
* Save request details.
*
* @param {Object} details
* @returns {void}
*/
function beforeRequest(details) {
// console.log(details);
if (details.tabId && details.tabId !== TAB_ID_NONE) {
const aurl = new URL(details.url);
if (details.type === "main_frame") {
tabs.set(details.tabId, {
details,
requests: new Map(),
requestSize: 0,
responseSize: 0
});
// console.log("beforeRequest", details);
} else if (!tabs.has(details.tabId)) {
tabs.set(details.tabId, {
details: null,
requests: new Map(),
requestSize: 0,
responseSize: 0
});
// certificateIcons.shield
setIcon(details.tabId, icons.information_source, `${TITLE} \nAccess denied for this “${aurl.protocol}” page`, null, null);
console.debug("Access denied", details.tabId, aurl.origin);
}
const tab = tabs.get(details.tabId);
if (!tab.requests.has(aurl.hostname)) {
tab.requests.set(aurl.hostname, {
connections: new Map(),
requestSize: 0,
responseSize: 0
});
}
const requests = tab.requests.get(aurl.hostname);
requests.connections.set(details.requestId, { details });
}
}
browser.webRequest.onBeforeRequest.addListener(beforeRequest,
{ urls: ["<all_urls>"] },
// Blocking needed to show requests at browser startup: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest#requests_at_browser_startup
// https://bugzilla.mozilla.org/show_bug.cgi?id=1749871
["blocking"]
);
/**
* Save request details and security info.
*
* @param {Object} details
* @returns {Promise<void>}
*/
async function headersReceived(details) {
// console.log(details);
if (details.tabId && details.tabId !== TAB_ID_NONE) {
try {
const main_frame = details.type === "main_frame";
const securityInfo = await browser.webRequest.getSecurityInfo(
details.requestId,
{ certificateChain: main_frame, rawDER: main_frame }
);
// console.log(securityInfo);
const aurl = new URL(details.url);
const tab = tabs.get(details.tabId);
if (!tab) {
console.error(details.tabId, aurl.origin);
return;
}
if (main_frame) {
tab.details = details;
tab.securityInfo = securityInfo;
// console.log("headersReceived", details);
}
const requests = tab.requests.get(aurl.hostname);
if (!requests || !requests.connections.has(details.requestId)) {
console.error(details.tabId, aurl.hostname, details.requestId, aurl.origin);
return;
}
requests.connections.set(details.requestId, { details, securityInfo });
sendSettings(details, tab);
} catch (error) {
console.error(error);
}
}
}
browser.webRequest.onHeadersReceived.addListener(headersReceived,
{ urls: ["<all_urls>"] },
["blocking", "responseHeaders"]
);
/**
* Save redirect.
*
* @param {Object} details
* @returns {void}
*/
function beforeRedirect(details) {
if (details.tabId && details.tabId !== TAB_ID_NONE) {
const aurl = new URL(details.url);
const aredirectUrl = new URL(details.redirectUrl);
const blocked = !["http:", "https:"].includes(aredirectUrl.protocol);
if (!blocked && aurl.hostname === aredirectUrl.hostname) {
return;
}
const tab = tabs.get(details.tabId);
if (!tab) {
console.error(details.tabId, aurl.origin);
return;
}
if (details.type === "main_frame") {
if (!tab.details) {
console.error("No Details!", tab);
}
if (blocked) {
tab.blocked = blocked;
}
// console.log("beforeRedirect", details);
}
const requests = tab.requests.get(aurl.hostname);
if (!requests || !requests.connections.has(details.requestId)) {
console.error(details.tabId, aurl.hostname, details.requestId, aurl.origin);
return;
}
const request = requests.connections.get(details.requestId);
if (!request.details) {
console.error("No Details!", request);
}
if (blocked) {
request.blocked = blocked;
} else {
request.redirected = aredirectUrl.hostname;
}
sendSettings(details, tab);
}
}
browser.webRequest.onBeforeRedirect.addListener(beforeRedirect,
{ urls: ["<all_urls>"] }
);
/**
* Save completed.
*
* @param {Object} details
* @returns {void}
*/
function completed(details) {
if (details.tabId && details.tabId !== TAB_ID_NONE) {
const aurl = new URL(details.url);
const tab = tabs.get(details.tabId);
if (!tab) {
console.error(details.tabId, aurl.origin);
return;
}
if (details.type === "main_frame") {
tab.completed = true;
// console.log("completed", details);
}
tab.requestSize += details.requestSize;
tab.responseSize += details.responseSize;
const requests = tab.requests.get(aurl.hostname);
if (!requests || !requests.connections.has(details.requestId)) {
console.error(details.tabId, aurl.hostname, details.requestId, aurl.origin);
return;
}
requests.requestSize += details.requestSize;
requests.responseSize += details.responseSize;
const request = requests.connections.get(details.requestId);
request.completed = true;
sendSettings(details, tab);
}
}
browser.webRequest.onCompleted.addListener(completed,
{ urls: ["<all_urls>"] }
);
/**
* Save error.
* Firefox error codes: https://searchfox.org/mozilla-central/rev/f6a2ef2f028b8f1eb82fa5dc5cb1e39a3baa8feb/js/xpconnect/src/xpc.msg
*
* @param {Object} details
* @returns {void}
*/
function errorOccurred(details) {
if (details.tabId && details.tabId !== TAB_ID_NONE) {
const aurl = new URL(details.url);
const tab = tabs.get(details.tabId);
if (!tab) {
console.error(details.tabId, aurl.origin);
return;
}
if (details.type === "main_frame") {
tab.error = details.error;
// console.log("errorOccurred", details);
}
const requests = tab.requests.get(aurl.hostname);
if (!requests || !requests.connections.has(details.requestId)) {
console.error(details.tabId, aurl.hostname, details.requestId, aurl.origin);
return;
}
const request = requests.connections.get(details.requestId);
request.error = details.error;
sendSettings(details, tab);
}
}
browser.webRequest.onErrorOccurred.addListener(errorOccurred,
{ urls: ["<all_urls>"] }
);
/**
* Convert hostname to lowercase and Punycode: https://en.wikipedia.org/wiki/Punycode.
*
* @param {string} hostname
* @returns {string}
*/
function punycode(hostname) {
return new URL(`https://${hostname}`).hostname;
}
/**
* Get the public suffix list.
*
* @param {number} date
* @param {number} [retry]
* @returns {Promise<void>}
*/
function getPSL(date, retry = 0) {
console.time(label);
const url = "https://publicsuffix.org/list/public_suffix_list.dat";
console.log(url);
return fetch(url).then(async (response) => {
if (response.ok) {
const text = await response.text();
// console.log(text);
console.timeLog(label);
const PSL = Object.freeze(text.split("\n").map((r) => r.trim()).filter((r) => r.length && !r.startsWith("//")));
console.log(PSL.length, new Date(date));
browser.storage.local.set({ PSL: { PSL, date } });
console.timeLog(label);
parsePSL(PSL);
} else {
console.error(response);
}
console.timeEnd(label);
}).catch(async (error) => {
if (retry >= 2) {
throw error;
}
console.error(error);
await delay((1 << retry) * 1000);
return getPSL(date, retry + 1);
});
}
/**
* Traverse Trie tree of objects to create RegEx.
*
* @param {Object.<string, Object|boolean>} tree
* @returns {string}
*/
function createRegEx(tree) {
const alternatives = [];
const characterClass = [];
for (const char in tree) {
if (char) {
const atree = tree[char];
if ("" in atree && Object.keys(atree).length === 1) {
characterClass.push(char);
} else {
const recurse = createRegEx(atree);
alternatives.push(recurse + char);
}
}
}
if (characterClass.length) {
alternatives.push(characterClass.length === 1 ? characterClass[0] : `[${characterClass.join("")}]`);
}
let result = alternatives.length === 1 ? alternatives[0] : `(?:${alternatives.join("|")})`;
if ("" in tree) {
if (characterClass.length || alternatives.length > 1) {
result += "?";
} else {
result = `(?:${result})?`;
}
}
return result;
}
/**
* Convert public suffix list into Trie tree of objects.
*
* @param {string[]} arr
* @returns {string}
*/
function createTree(arr) {
const tree = {};
arr.sort((a, b) => b.length - a.length);
for (const str of arr) {
let temp = tree;
for (const char of Array.from(punycode(str.replaceAll("*", "---")).replaceAll("---", "*")).reverse()) {
if (!(char in temp)) {
temp[char] = {};
}
temp = temp[char];
}
// Leaf node
temp[""] = true;
}
Object.freeze(tree);
return createRegEx(tree).replaceAll(".", String.raw`\.`).replaceAll("*", "[^.]+");
}
/**
* Parse public suffix list and create regular expressions.
*
* @param {readonly string[]} PSL
* @returns {void}
*/
function parsePSL(PSL) {
const start = performance.now();
suffixes = [];
exceptions = [];
for (const r of PSL) {
if (r.startsWith("!")) {
exceptions.push(r.slice(1));
} else {
suffixes.push(r);
}
}
// console.log(suffixes, exceptions);
suffixes = createTree(suffixes);
exceptions = createTree(exceptions);
console.log(suffixes, exceptions);
suffixes = new RegExp(String.raw`(?:^|\.)(${suffixes})$`, "u");
exceptions = new RegExp(String.raw`(?:^|\.)(${exceptions})$`, "u");
// console.log(suffixes, exceptions);
const end = performance.now();
console.log(`The PSL was parsed in ${end - start} ms.`);
}
/**
* Get the geolocation databases.
*
* @param {number} date
* @returns {Promise<void>}
*/
async function getGeoLoc(date) {
setIcon(null, icons.downwards_black_arrow, `${TITLE} \nUpdating geolocation databases`, null, null);
const message = {
type: WORKER,
date,
languages: await browser.i18n.getAcceptLanguages()
};
// console.log(message);
worker.postMessage(message);
}
/**
* Get the geolocation.
*
* @param {string} address
* @returns {Promise<Object|null>}
*/
function getGeoIP(address) {
const message = {
type: LOCATION,
addresses: [address]
};
// console.log(message);
return new Promise((resolve) => {
const channel = new MessageChannel();
channel.port1.onmessage = (event) => {
channel.port1.close();
resolve(event.data.locations[0]);
};
worker.postMessage(message, [channel.port2]);
});
}
browser.privacy.network.httpsOnlyMode.onChange.addListener((details) => {
console.log(details);
httpsOnlyMode = details.value;
});
/**
* Handle idle state change.
*
* @param {string} state
* @returns {void}
*/
function newState(state) {
// console.log(`New state: ${state}`);
if (settings.updateidle) {
// console.log(new Date(), state);
if (state === "locked" || state === "idle") {
if (date) {