-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
popup.js
1338 lines (1226 loc) · 40.6 KB
/
popup.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, LOCATION, emojis, certificateEmojis, statusEmojis, dateTimeFormat1, dateTimeFormat3, dateTimeFormat4, numberFormat1, numberFormat2, numberFormat3, numberFormat4, numberFormat5, numberFormat6, numberFormat, rtf, regionNames, IPv4RE, IPv6, IPv6RE, outputunit, outputbase85, expand, IPv6toInt, outputseconds, outputdate, outputdateRange, outputlocation, earth, getissuer, getHSTS, getmessage, countryCode } from "/common.js";
const { TAB_ID_NONE } = browser.tabs;
const formatter2 = new Intl.ListFormat([], { style: "short" });
const aIPv6RE = new RegExp(String.raw`^\[${IPv6}\]$`, "u");
let WARNDAYS = 3;
let OPEN = true;
let BLOCKED = true;
let FULLIPv6 = false;
let COMPACTIPv6 = false;
let HTTPS = false;
let SUFFIX = true;
let GeoDB = 1;
let MAP = 0;
let LOOKUP = 0;
let DNS = true;
let BLACKLIST = false;
let SEND = true;
let COLUMNS = {
download: true,
upload: true,
classification: true,
security: true,
expiration: true,
tlsversion: true,
hsts: true,
httpversion: true,
httpstatus: true
};
let DOMAINBLACKLISTS = [];
let IPv4BLACKLISTS = [];
let IPv6BLACKLISTS = [];
let pasteSymbol = null;
let suffixes = null;
let exceptions = null;
let timeoutID = null;
let tabId = null;
let running = false;
const timer = document.getElementById("timer");
/**
* Create notification.
*
* @param {string} title
* @param {string} message
* @returns {void}
*/
function notification(title, message) {
console.log(title, message);
if (SEND) {
browser.notifications.create({
type: "basic",
iconUrl: browser.runtime.getURL("icons/icon_128.png"),
title,
message
});
}
}
/**
* Get seconds as digital clock.
*
* @param {number} sec_num
* @returns {string}
*/
function getSecondsAsDigitalClock(sec_num) {
// console.log(now);
const d = Math.floor(sec_num / 86400);
const h = Math.floor(sec_num % 86400 / 3600);
const m = Math.floor(sec_num % 3600 / 60);
const s = sec_num % 60;
let text = "";
if (d > 0) {
// text += d.toLocaleString() + '\xa0days ';
text += `${numberFormat1.format(d)} `;
}
if (d > 0 || h > 0) {
// text += ((h < 10) ? '0' + h : h) + '\xa0hours ';
text += `${numberFormat2.format(h)} `;
}
if (d > 0 || h > 0 || m > 0) {
// text += ((m < 10) ? '0' + m : m) + '\xa0minutes ';
text += `${numberFormat3.format(m)} `;
}
if (d > 0 || h > 0 || m > 0 || s > 0) {
// text += ((s < 10) ? '0' + s : s) + '\xa0seconds';
text += numberFormat4.format(s);
}
return text;
}
/**
* Output timer.
*
* @param {number} time
* @param {number} now
* @returns {void}
*/
function outputtimer(time, now) {
const sec_num = Math.floor(time / 1000) - Math.floor(now / 1000);
const days = Math.floor(sec_num / 86400);
let text;
let color;
if (sec_num > 0) {
text = getSecondsAsDigitalClock(sec_num);
color = days > WARNDAYS ? "green" : "yellow";
} else {
text = "Expired";
color = "red";
}
timer.classList.add(color);
timer.textContent = text;
}
/**
* Timer tick.
*
* @param {number} time
* @returns {void}
*/
function timerTick(time) {
const now = Date.now();
const delay = 1000 - now % 1000;
timeoutID = setTimeout(() => {
outputtimer(time, now + delay);
if (time > now) {
timerTick(time);
}
}, delay);
}
/**
* Output time in seconds.
*
* @param {number} time
* @returns {string}
*/
function outputtime(time) {
const s = Math.floor(time / 1000);
const ms = time % 1000;
let text = "";
if (s > 0) {
text += `${numberFormat4.format(s)} `;
}
if (s > 0 || ms > 0) {
text += numberFormat5.format(ms);
}
return text;
}
/**
* Create link.
*
* @param {string} link
* @returns {HTMLAnchorElement}
*/
function createlink(link) {
const a = document.createElement("a");
a.href = link;
a.target = "_blank";
return a;
}
/**
* Output map link.
*
* @param {number} latitude
* @param {number} longitude
* @returns {Array.<HTMLElement|string>}
*/
function map(latitude, longitude) {
let url = "";
switch (MAP) {
case 1:
url = `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}`;
break;
case 2:
url = `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;
break;
case 3:
url = `https://bing.com/maps/?cp=${latitude}~${longitude}`;
break;
case 4:
url = `https://www.mapquest.com/latlng/${latitude},${longitude}`;
break;
case 5:
url = `https://maps.apple.com/?q=${latitude},${longitude}`;
break;
// No default
}
const a = createlink(url);
a.title = "Click to View Map";
a.textContent = "🗺️";
a.classList.add("button");
return ["(", a, ")"];
}
/**
* Output lookup link.
*
* @param {string} hostname
* @param {string} address
* @returns {Array.<HTMLElement|string>}
*/
function lookup(hostname, address) {
let url = "";
switch (LOOKUP) {
case 1:
// https://iplookup.flagfox.net/?ip={IPaddress}&host={domainName}
url = `https://iplookup.flagfox.net/?ip=${address}&host=${hostname}`;
break;
case 2:
url = `https://www.ip2location.com/${address}`;
break;
case 3:
url = `https://browserleaks.com/ip/${address}`;
break;
// No default
}
const a = createlink(url);
a.title = "Click to Lookup IP address";
a.textContent = "🔍";
a.classList.add("button");
return ["(", a, ")"];
}
/**
* Output IP address.
*
* @param {string} address
* @param {string} hostname
* @param {string|null} [current]
* @param {boolean} [ipv4]
* @param {boolean} [ipv6]
* @returns {Array.<HTMLElement|string>}
*/
function outputaddress(address, hostname, current, ipv4, ipv6) {
ipv4 ??= IPv4RE.test(address);
ipv6 ??= IPv6RE.test(address);
console.assert(ipv4 || ipv6, "Error: Unknown IP address", address);
const aaddress = ipv6 ? FULLIPv6 ? expand(address).join(":") : COMPACTIPv6 ? outputbase85(IPv6toInt(expand(address).join(""))) : address : address;
const a = createlink(`http${HTTPS ? "s" : ""}://${ipv6 ? `[${address}]` : address}`);
if (address === current) {
const strong = document.createElement("strong");
strong.textContent = aaddress;
a.append(strong);
} else {
a.textContent = aaddress;
}
a.classList.add(ipv6 ? "ipv6" : "ipv4");
const text = [a];
if (LOOKUP) {
text.push("\u00A0", ...lookup(hostname, address));
}
return text;
}
/**
* Output list of IP addresses.
*
* @param {string[]} addresses
* @param {string} hostname
* @param {string} current
* @param {boolean} ipv4
* @param {boolean} ipv6
* @returns {string}
*/
function outputaddresses(addresses, hostname, current, ipv4, ipv6) {
return formatter2.format(addresses.map((x) => {
const span = document.createElement("span");
span.append(...outputaddress(x, hostname, current, ipv4, ipv6));
return span.innerHTML;
}));
// .join(', ')
}
/**
* Output hostname.
*
* @param {string} hostname
* @param {string} protocol
* @param {boolean} [ipv4]
* @param {boolean} [ipv6]
* @returns {HTMLAnchorElement}
*/
function outputhost(hostname, protocol, ipv4, ipv6) {
ipv4 ??= IPv4RE.test(hostname);
ipv6 ??= aIPv6RE.test(hostname);
if (SUFFIX && suffixes && !ipv4 && !ipv6) {
const regexResult = suffixes.exec(hostname);
const aregexResult = exceptions.exec(hostname);
const labels = hostname.split(".");
const alabels = aregexResult ? aregexResult[1].split(".").slice(1) : regexResult ? regexResult[1].split(".") : labels.slice(-1);
if (labels.length > alabels.length) {
const domain = labels.slice(-(alabels.length + 1)).join("\u200B.");
const subdomain = labels.slice(0, -(alabels.length + 1)).join("\u200B.");
const a = createlink(`${protocol}//${hostname}`);
const strong = document.createElement("strong");
strong.textContent = domain;
if (subdomain) {
a.textContent = `${subdomain}\u200B.`;
}
a.append(strong);
return a;
}
console.error("Error: Hostname has invalid suffix", hostname);
}
const a = createlink(`${protocol}//${hostname}`);
a.textContent = hostname;
return a;
}
/**
* Handle error.
*
* @param {string} error
* @returns {void}
*/
function handleError(error) {
console.error(`Error: ${error}`);
}
/**
* Convert HTTP statue code to emoji.
*
* @param {number} statusCode
* @returns {string}
*/
function status(statusCode) {
let emoji;
if (statusCode >= 100 && statusCode < 200) {
emoji = statusEmojis[0];
} else if (statusCode >= 200 && statusCode < 300) {
emoji = statusEmojis[1];
} else if (statusCode >= 300 && statusCode < 400) {
emoji = statusEmojis[2];
} else {
// I'm a teapot, RFC 2324: https://datatracker.ietf.org/doc/html/rfc2324
emoji = statusCode === 418 ? statusEmojis[4] : statusEmojis[3];
}
return emoji;
}
/**
* Get emoji and URL classification.
*
* @param {Object} details
* @returns {{emojis: string[], classifications: string[]}}
*/
function getClassification(details) {
const emojis = [];
// let classifications = urlClassification.firstParty.concat(urlClassification.thirdParty);
let classifications = details.thirdParty ? details.urlClassification.thirdParty : details.urlClassification.firstParty;
if (classifications.length) {
if (classifications.some((c) => c.startsWith("fingerprinting"))) {
emojis.push("👣");
}
if (classifications.some((c) => c.startsWith("cryptomining"))) {
emojis.push("⚒️");
}
if (classifications.some((c) => c.startsWith("tracking") && c !== "tracking_social")) {
/* if (classifications.includes("tracking_ad")) {
emojis.push("🖼️");
} else if (classifications.includes("tracking_analytics")) {
emojis.push("📈");
} */
emojis.push("👁️");
}
if (classifications.includes("any_social_tracking")) {
emojis.push("👥");
}
classifications = classifications.filter((c) => !c.startsWith("any_"));
}
return { emojis, classifications };
}
/**
* Get emoji and security state.
*
* @param {Object} tab
* @param {Object} tab.securityInfo
* @param {string} [tab.error]
* @returns {{emoji: string[], state: string}}
*/
function getstate({ securityInfo, error }) {
const emoji = [];
let state = "";
if (securityInfo) {
if (securityInfo.state === "insecure") {
emoji.push(certificateEmojis[0]);
state = "Insecure";
} else if (securityInfo.state === "broken" || securityInfo.isUntrusted || securityInfo.isNotValidAtThisTime || securityInfo.isDomainMismatch) {
emoji.push(certificateEmojis[3]);
state = getmessage(securityInfo);
} else if (securityInfo.state === "weak") {
emoji.push(certificateEmojis[1], certificateEmojis[2]);
state = `Weak${securityInfo.weaknessReasons ? ` (${securityInfo.weaknessReasons})` : ""}`;
} else if (securityInfo.state === "secure") {
emoji.push(certificateEmojis[1]);
state = "Secure";
}
}
if (error) {
emoji.push(certificateEmojis[4]);
if (state) {
state += `, error: ${error}`;
} else {
state = `Error: ${error}`;
}
}
return { emoji, state };
}
/**
* Count instances of values in array.
*
* @param {string[]} array
* @returns {Object.<string, number>}
*/
function count(array) {
return array.reduce((aarray, item) => {
if (item) {
if (item in aarray) {
++aarray[item];
} else {
aarray[item] = 1;
}
}
return aarray;
}, {});
}
/**
* Output tooltip/title.
*
* @param {string[]} array
* @param {string} [str]
* @returns {string}
*/
function outputtitle(array, str) {
const obj = count(array);
return Object.keys(obj).length > 1 ? Object.entries(obj).map(([key, value]) => `${numberFormat.format(value)}: ${key}`).join("\n") : str || Object.keys(obj)[0];
}
/**
* Check Blacklist.
*
* @param {string} domain
* @param {string} blacklist
* @param {string} [address]
* @returns {Promise<void>}
*/
function checkblacklist(domain, blacklist, address) {
return browser.dns.resolve(domain, ["disable_trr"]).then((record) => {
// console.log(record);
if (record.addresses.length) {
document.getElementById("blacklist").innerText += `🚫\u00A0${address ? `IP address (${address})` : "domain"} is listed in the "${blacklist}" blacklist (${record.addresses.join(" ")})\n`;
document.querySelector(".blacklist").classList.remove("hidden");
}
}).catch(() => {});
}
/**
* Check Blacklists.
*
* @param {string} hostname
* @param {string[]} [ipv4s]
* @param {string[]} [ipv6s]
* @returns {Promise<void>}
*/
async function checkblacklists(hostname, ipv4s, ipv6s) {
const ipv4 = IPv4RE.test(hostname);
const ipv6 = aIPv6RE.test(hostname);
// Check Domain Blacklists
if (!ipv4 && !ipv6) {
for (const bl of DOMAINBLACKLISTS) {
await checkblacklist(`${hostname}.${bl}`, bl);
}
}
// Check IPv4 Blacklists
if (!ipv6) {
let addresses = [];
if (ipv4) {
addresses = [hostname];
} else if (ipv4s) {
addresses = ipv4s;
}
for (const address of addresses) {
// Reverse IPv4 address
const reverse = address.split(".").reverse().join(".");
for (const bl of IPv4BLACKLISTS) {
await checkblacklist(`${reverse}.${bl}`, bl, address);
}
}
}
// Check IPv6 Blacklists
if (!ipv4) {
let addresses = [];
if (ipv6) {
addresses = [hostname.slice(1, -1)];
} else if (ipv6s) {
addresses = ipv6s;
}
for (const address of addresses) {
// Expand and reverse IPv6 address
const reverse = expand(address).join("").split("").reverse().join(".");
for (const bl of IPv6BLACKLISTS) {
await checkblacklist(`${reverse}.${bl}`, bl, address);
}
}
}
}
/**
* Get the geolocation.
*
* @param {string[]} addresses
* @returns {Promise<Array<{start: number|bigint, end: number|bigint, country: string, state2?: string, state1?: string, city?: string, lat?: number, lon?: number}|null>>}
*/
function getGeoIP(addresses) {
return browser.runtime.sendMessage({ type: LOCATION, addresses }).then((message) => {
if (message.type === LOCATION) {
// console.log(message);
return message.locations;
}
});
}
/**
* Copy link to clipboard.
*
* @param {string} text
* @param {string} link
* @returns {void}
*/
function copyToClipboard(text, _link) {
// https://github.com/mdn/webextensions-examples/blob/master/context-menu-copy-link-with-types/clipboard-helper.js
/* const atext = encodeXML(text);
const alink = encodeXML(link);
const html = `<a href="${alink}">${atext}</a>`; */
navigator.clipboard.writeText(text);
}
/**
* Copy URI/IRI to clipboard and show notification when unable to open tab/window directly.
*
* @param {string} uri
* @returns {void}
*/
function copy(uri) {
copyToClipboard(uri, uri);
const url = new URL(uri);
notification(`📋 Press ${pasteSymbol}-V and Enter ↵`, `Add-ons are currently unable to open “${url.protocol}” links directly, so it has been copied to your clipboard.\nPlease press ${pasteSymbol}-V and Enter ↵ to go.`);
}
/**
* Attempt to open link in a new tab.
*
* @param {MouseEvent} event
* @returns {void}
*/
function click(event) {
const url = event.target.href;
// console.log(url);
browser.tabs.create({ url, openerTabId: tabId }).catch((error) => {
console.error(error);
browser.tabs.create({ openerTabId: tabId });
copy(url);
}).finally(() => {
setTimeout(() => {
close();
}, 1000);
});
}
/**
* Update transfer size.
*
* @param {Object} tab
* @param {number} tab.requestSize
* @param {number} tab.responseSize
* @returns {void}
*/
function updateTransfer({ requestSize, responseSize }) {
document.getElementById("download").textContent = `${outputunit(responseSize, false)}B${responseSize >= 1000 ? ` (${outputunit(responseSize, true)}B)` : ""}`;
document.getElementById("upload").textContent = `${outputunit(requestSize, false)}B${requestSize >= 1000 ? ` (${outputunit(requestSize, true)}B)` : ""}`;
document.querySelector(".size").classList.remove("hidden");
}
/**
* Update performance data.
*
* @param {Object} performance
* @returns {void}
*/
function updatePerformance(performance) {
const [navigation] = performance.navigation;
const start = navigation.redirectCount ? navigation.redirectStart : navigation.fetchStart;
const load = navigation.loadEventStart - start;
const aload = document.getElementById("load");
aload.title = outputtime(load);
aload.textContent = numberFormat6.format(load);
const ttfb = navigation.responseStart - start;
const attfb = document.getElementById("ttfb");
attfb.title = outputtime(ttfb);
attfb.textContent = numberFormat6.format(ttfb);
const fcp = performance.paint?.find((x) => x.name === "first-contentful-paint");
const apaint = document.getElementById("paint");
apaint.title = fcp ? outputtime(fcp.startTime) : "";
apaint.textContent = fcp ? numberFormat6.format(fcp.startTime) : "None";
if (PerformanceObserver.supportedEntryTypes.includes("largest-contentful-paint")) {
const lcp = performance.lcp?.at(-1);
const alcp = document.getElementById("lcp");
alcp.title = lcp ? outputtime(lcp.startTime) : "";
alcp.textContent = lcp ? numberFormat6.format(lcp.startTime) : "None";
document.querySelector(".lcp").classList.remove("hidden");
}
/* const size = navigation.transferSize;
document.getElementById("size").textContent = size === 0 && navigation.decodedBodySize > 0 ? "Cached" : `${outputunit(size, false)}B${size >= 1000 ? ` (${outputunit(size, true)}B)` : ""}`;
for (const element of document.querySelectorAll(".content")) {
element.classList.remove("hidden");
} */
document.querySelector(".content").classList.remove("hidden");
}
/**
* Update requests table.
*
* @param {Map} requests
* @returns {void}
*/
function updateTable(requests) {
if (requests.size) {
const promises = [];
const table = document.createElement("table");
for (const [hostname, request] of requests) {
const arequests = Array.from(request.connections.values());
let connections = 0;
let completed = 0;
let redirected = 0;
let blocked = 0;
let errored = 0;
for (const arequest of arequests) {
if (arequest.error) {
++errored;
} else if (arequest.blocked) {
++blocked;
} else if (arequest.redirected) {
++redirected;
} else if (arequest.completed) {
++completed;
} else {
++connections;
}
}
if (connections || completed || redirected || BLOCKED) {
const row = table.insertRow();
const cell = row.insertCell();
cell.title = `${numberFormat.format(completed)} connection${completed === 1 ? "" : "s"} completed${redirected ? `\n${numberFormat.format(redirected)} connection${redirected === 1 ? "" : "s"} redirected to a different domain` : ""}${BLOCKED ? `${blocked ? `\n${numberFormat.format(blocked)} connection${blocked === 1 ? "" : "s"} blocked by browser/another add-on` : ""}${!blocked || errored ? `\n${numberFormat.format(errored)} connection${errored === 1 ? "" : "s"} blocked/errored` : ""}` : ""}\n${numberFormat.format(connections)} active connection${connections === 1 ? "" : "s"}`;
cell.textContent = `${numberFormat.format(completed + redirected)}${BLOCKED ? `/${numberFormat.format(blocked + errored)}` : ""}/${numberFormat.format(connections)}`;
if (connections) {
cell.classList.add("highlight");
}
if (COLUMNS.download) {
const cell = row.insertCell();
const { responseSize } = request;
cell.title = `Download/Response: ${outputunit(responseSize, false)}B${responseSize >= 1000 ? ` (${outputunit(responseSize, true)}B)` : ""}`;
cell.textContent = `${outputunit(responseSize, false)}B`;
let aclass;
if (responseSize < 1024) {
aclass = "b";
} else if (responseSize < 1024 ** 2) {
aclass = "kib";
} else if (responseSize < 1024 ** 3) {
aclass = "mib";
} else {
aclass = "gib";
}
cell.classList.add(aclass, "right");
}
if (COLUMNS.upload) {
const cell = row.insertCell();
const { requestSize } = request;
cell.title = `Upload/Request: ${outputunit(requestSize, false)}B${requestSize >= 1000 ? ` (${outputunit(requestSize, true)}B)` : ""}`;
cell.textContent = `${outputunit(requestSize, false)}B`
let aclass;
if (requestSize < 1024) {
aclass = "b";
} else if (requestSize < 1024 ** 2) {
aclass = "kib";
} else if (requestSize < 1024 ** 3) {
aclass = "mib";
} else {
aclass = "gib";
}
cell.classList.add(aclass, "right");
}
if (COLUMNS.classification) {
const cell = row.insertCell();
const classification = arequests.map((obj) => getClassification(obj.details));
const classifications = classification.flatMap((obj) => obj.classifications).map((c) => c.split("_").map(([h, ...t]) => h.toUpperCase() + t.join("")).join(" "));
const aemojis = classification.flatMap((obj) => obj.emojis);
cell.title = classifications.length ? outputtitle(classifications) : "No known trackers";
cell.textContent = aemojis.length ? Array.from(new Set(aemojis)).join("") : "–";
}
if (COLUMNS.security) {
// const { emoji, state } = getstate(securityInfo);
const states = arequests.filter((x) => x.details.statusLine || x.error).map((obj) => getstate(obj));
const cell = row.insertCell();
cell.title = states.length ? outputtitle(states.map((obj) => obj.state)/* , state */) : blocked ? "Blocked by the browser or another add-on" : "Waiting for connection…";
cell.textContent = states.length ? Array.from(new Set(states.flatMap((obj) => obj.emoji))).join("") : blocked ? certificateEmojis[5] : emojis[6];
}
const arequest = arequests.filter((x) => x.details.statusLine);
if (arequest.length) {
const { details, securityInfo } = arequest.at(-1);
if (securityInfo.state !== "insecure" && securityInfo.certificates.length) {
const [{ details }] = arequest;
if (COLUMNS.expiration) {
const [certificate] = securityInfo.certificates;
const { start, end } = certificate.validity;
const sec = Math.floor(end / 1000) - Math.floor(details.timeStamp / 1000);
const days = Math.floor(sec / 86400);
let title;
let color;
if (sec > 0) {
// title += 'expires in ' + days.toLocaleString() + ' days';
title = `Expires ${rtf.format(days, "day")} (${outputdateRange(start, end)})`;
color = days > WARNDAYS ? "green" : "yellow";
} else {
title = `Expired ${rtf.format(days, "day")} (${outputdate(end)})`;
color = "red";
}
const cell = row.insertCell();
cell.title = title;
const span = document.createElement("span");
span.classList.add(color);
span.textContent = sec > 0 && days === 0 ? `<${numberFormat.format(1)}` : numberFormat.format(days);
cell.append(span);
}
if (COLUMNS.tlsversion) {
const cell = row.insertCell();
cell.title = outputtitle(arequest.map((obj) => obj.securityInfo).map((obj) => `${obj.protocolVersion}${obj.secretKeyLength ? `, ${obj.secretKeyLength} bits` : ""}, ${obj.cipherSuite}`));
cell.append(...Array.from(new Set(arequest.map((obj) => obj.securityInfo.protocolVersion)), (version, index) => {
const span = document.createElement("span");
if (version?.startsWith("TLSv")) {
const [major, minor] = version.slice("TLSv".length).split(".").map((x) => Number.parseInt(x, 10));
let color;
if (major === 1) {
if (minor === 0 || minor === 1) {
color = "red";
} else if (minor === 2) {
color = "blue";
} else if (minor >= 3) {
color = "green";
}
} else if (major > 1) {
color = "green";
}
span.classList.add(color);
span.textContent = version.slice("TLS".length);
} else {
span.textContent = version;
}
return index ? ["\n", span] : [span];
}).flat());
}
if (COLUMNS.hsts) {
const cell = row.insertCell();
if (details.responseHeaders) {
const header = details.responseHeaders.find((e) => e.name.toLowerCase() === "strict-transport-security");
// const header = arequest.find((obj) => obj.details.responseHeaders.find((e) => e.name.toLowerCase() === "strict-transport-security"))?.details.responseHeaders.find((e) => e.name.toLowerCase() === "strict-transport-security");
if (header) {
const aheader = getHSTS(header.value);
const sec = Number.parseInt(aheader["max-age"], 10);
const days = Math.floor(sec / 86400);
cell.title = `HSTS: Yes (${outputseconds(sec)})`;
cell.textContent = sec > 0 && days === 0 ? `<${numberFormat.format(1)}` : numberFormat.format(days);
} else {
cell.title = `HSTS: ${securityInfo.hsts ? "Yes (Unable to find header)" : "No"}`;
cell.textContent = securityInfo.hsts ? emojis[4] : emojis[5];
}
} else {
cell.title = `HSTS: ${securityInfo.hsts ? "Yes" : "No"}`;
cell.textContent = securityInfo.hsts ? emojis[4] : emojis[5];
}
}
} else {
if (COLUMNS.expiration) {
const cell = row.insertCell();
cell.textContent = "–";
}
if (COLUMNS.tlsversion) {
const cell = row.insertCell();
cell.textContent = "–";
}
if (COLUMNS.hsts) {
const cell = row.insertCell();
cell.textContent = "–";
}
}
const title = (COLUMNS.httpversion || COLUMNS.httpstatus) && outputtitle(arequest.map((obj) => obj.details.statusLine), details.statusLine);
if (COLUMNS.httpversion) {
const cell = row.insertCell();
cell.title = title;
// Get HTTP version
const re = /^HTTP\/(\d+(?:\.\d+)?) (\d{3})(?: .*)?$/u;
cell.append(...Array.from(new Set(arequest.map((obj) => {
const regexResult = re.exec(obj.details.statusLine);
console.assert(regexResult, "Error: Unknown HTTP Status", obj.details.statusLine);
return regexResult && regexResult[1];
})), (version, index) => {
const span = document.createElement("span");
if (version) {
const [major, minor] = version.split(".").map((x) => Number.parseInt(x, 10));
let color;
switch (major) {
case 0:
color = "red";
break;
case 1:
color = minor === 0 ? "red" : "blue";
break;
case 2:
color = "teal";
break;
default: if (major >= 3) {
color = "green";
}
}
span.classList.add(color);
span.textContent = version;
} else {
span.textContent = emojis[2];
}
return index ? ["\n", span] : [span];
}).flat());
}
if (COLUMNS.httpstatus) {
const cell = row.insertCell();
cell.title = title;
cell.textContent = Array.from(new Set(arequest.map((obj) => obj.details.statusCode)), (key) => status(key)).join("");
}
let cell = row.insertCell();
cell.append(outputhost(hostname, `http${HTTPS ? "s" : ""}:`));
cell.classList.add("host");
const addresses = Array.from(new Set(arequest.map((obj) => obj.details.ip).filter(Boolean)));
cell = row.insertCell();
if (addresses.length) {
cell.append(...addresses.flatMap((x, i) => [...i ? ["\n"] : [], ...outputaddress(x, hostname, details.ip)]));
} else if (details.fromCache) {
const [{ details }] = arequest;
if (details.responseHeaders) {
const header = details.responseHeaders.find((e) => e.name.toLowerCase() === "date");
if (header) {
cell.title = outputdate(header.value);
}
}
cell.textContent = "(Cached)";
}
if (GeoDB) {
cell = row.insertCell();
if (addresses.length) {
cell.title = "Loading…";
cell.textContent = "…";
promises.push(getGeoIP(addresses).then((infos) => {
// console.log(details.ip, addresses, infos);
cell.title = outputtitle(infos.map((x) => x?.country ? outputlocation(x) : "Unknown Location"));
if (MAP) {
cell.replaceChildren(...Array.from(new Set(infos), (x, i) => x?.country ? [...i ? [" "] : [], countryCode(x.country), ...x.lat != null && x.lon != null ? map(x.lat, x.lon) : []] : [emojis[2]]).flat());
} else {
cell.textContent = Array.from(new Set(infos.map((x) => x?.country)), (x) => x ? countryCode(x) : emojis[2]).join("");
}
}));
} else if (details.fromCache) {
cell.textContent = "–";
} else {
cell.title = "Unknown Location";
cell.textContent = emojis[2];
}
}
} else if (BLOCKED) {
if (COLUMNS.expiration) {
const cell = row.insertCell();
cell.textContent = "–";
}
if (COLUMNS.tlsversion) {
const cell = row.insertCell();
cell.textContent = "–";
}
if (COLUMNS.hsts) {
const cell = row.insertCell();
cell.textContent = "–";
}
if (COLUMNS.httpversion) {
const cell = row.insertCell();
cell.textContent = "–";
}
if (COLUMNS.httpstatus) {
const cell = row.insertCell();
cell.textContent = "–";
}
let cell = row.insertCell();
cell.append(outputhost(hostname, `http${HTTPS ? "s" : ""}:`));
cell.classList.add("host");
cell = row.insertCell();
cell.textContent = "–";
if (GeoDB && requests.size > 1) {
/* cell = */row.insertCell();
}
row.classList.add("blocked");
}
}
}
document.getElementById("number").textContent = numberFormat.format(table.rows.length);
Promise.all(promises).then(() => {
document.getElementById("requests").replaceChildren(table);
});
}
}
/**
* Update popup.
*
* @param {number} tabId
* @param {Object} tab
* @param {Object} tab.details
* @param {Object} tab.securityInfo
* @param {Map} tab.requests
* @param {string} [tab.error]
* @param {boolean} [tab.blocked]
* @param {Object} [tab.performance]
* @returns {void}
*/
function updatePopup(tabId, tab) {
const { details, securityInfo, requests, error, blocked } = tab;
// console.log(tabId, details, securityInfo);
document.getElementById("content").textContent = "Loading…";
browser.tabs.sendMessage(tabId, { type: CONTENT }).then((message) => {
if (message.type === CONTENT) {
// console.log(message);
}
}).catch(handleError).finally(() => {
document.querySelector(".no-content").classList.add("hidden");
});
if (tab.performance) {
updatePerformance(tab.performance);
}