-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNX Enhanced.user.js
2107 lines (1619 loc) · 114 KB
/
NX Enhanced.user.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
// ==UserScript==
// @name NX Enhanced
// @description Adds quality-of-life features to NextDNS website for a more practical experience
// @author BLBC (github.com/hjk789, greasyfork.org/users/679182-hjk789, reddit.com/u/dfhg89s7d89)
// @copyright 2020+, BLBC (github.com/hjk789)
// @version 3.7.4
// @homepage https://github.com/hjk789/NXEnhanced
// @license https://github.com/hjk789/NXEnhanced#license
// @supportURL https://github.com/hjk789/NXEnhanced/issues
// @downloadURL https://greasyfork.org/scripts/408934-nx-enhanced/code/NX%20Enhanced.user.js
// @updateURL https://greasyfork.org/scripts/408934-nx-enhanced/code/NX%20Enhanced.user.js
// @grant GM.setValue
// @grant GM.getValue
// @match https://my.nextdns.io/*
// @match https://api.nextdns.io/*
// ==/UserScript==
/* eslint-disable no-multi-spaces, curly, no-loop-func, no-multi-str, no-caller, dot-notation, no-lone-blocks, no-undef, no-implicit-globals */
if (window.top == window.self)
{
let currentPage = ""
const intervals = []
// Load all NX Enhanced's settings
getGMsettings()
// Add some internal functions to the code
extendFunctions()
// Add some simple styles for a better UX
const style = document.createElement("style")
style.innerHTML = `.list-group-item:hover .btn { visibility: visible !important; } /* Allow/Deny/Hide buttons on hover */
.tooltipParent:hover .customTooltip { opacity: 1 !important; visibility: visible !important; } /* Show the tooltip when hovering it's container */
.tooltipParent .customTooltip:hover { opacity: 0 !important; visibility: hidden !important; } /* Hide the tooltip when it's hovered, as it should stay visible only when hovering the parent */
div:hover #counters { visibility: hidden !important; } /* Hide the log entries counters on hover */
.btn-light { background-color: #eee; } /* Make the btn-light more visible without affecting the hover */
.list-group-item div div:hover input.description, input.description:focus { visibility: visible !important; } /* Show the allow/denylist domains description input box on hover, and when the input is focused */
`
document.head.appendChild(style)
window.addEventListener("message", function check(e) // In some cases, such as when using Chrome, for some reason, the API frame has some delay to finish loading, which breaks the script when a request is made before
{ // it's finished. So this makes it so that when the frame finishes loading, it sends a message to the top window to make it known and allow the script to continue.
if (e.data == "frame ready")
{
frameReady = true
this.removeEventListener("message", check)
}
})
window.addEventListener("message", function(e) { // Run the event listener callback including the response when the HTTP request is completed. Here, PostMessage
if (e.data.callback != "") // is only necessary for asynchronous requests, as it would be pretty hacky to do this in any other way, and
dispatchEvent(new CustomEvent(e.data.callback, {detail: e.data.response})) // asynchronous requests here are only necessary for slow connections and for multiple simultaneous requests.
}, true)
const ApiFrame = document.createElement("object") // Here an OBJECT element is being used instead of an IFRAME because of a bug in GreaseMonkey that makes it not run inside IFRAMEs, but it runs fine inside EMBEDs and OBJECTs.
ApiFrame.data = "https://api.nextdns.io/configurations/"
document.body.appendChild(ApiFrame)
ApiFrame.style.display = "none" // The frame needs to be hidden *after* the append, otherwise Chrome won't load it. In Firefox it works fine.
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
function main()
{
setIntervalOld(function()
{
if (currentPage == location.href)
return
currentPage = location.href
clearAllIntervals()
// ---------------------------- Logs page ---------------------------
if (/\/logs/i.test(location.href))
{
let hideDevices = false, filtering = true
let loadingChunk = false, cancelLoading = false
let logsContainer, allowDenyPopup, existingEntries, updateRelativeTimeInterval
let visibleEntriesCountEll, filteredEntriesCountEll, allHiddenEntriesCountEll, loadedEntriesCountEll
let lastBefore, lastAfter = 1, currentDeviceId, searchString, blockedQueriesOnly, simpleLogs = 1
const dateTimeFormatter = new Intl.DateTimeFormat('default', { weekday: "long", month: "long", day: "numeric", year: "numeric", hour: "numeric", minute: "numeric", second: "numeric" });
const waitForItems = setInterval(function()
{
const pageContentContainer = document.getElementById("root").secondChild()
if (!pageContentContainer)
return
logsContainer = pageContentContainer.getByClass("list-group")
if (!logsContainer)
return
const svgs = logsContainer.querySelectorAll(".settings-button svg, .stream-button svg")
if (svgs.length < 2) // Wait for the SVGs to finish loading before overriding, otherwise they fail to load and leave a blank space.
return
let searchBarForm = logsContainer.querySelector("form")
if (!searchBarForm || !logsContainer.querySelector("div.text-center")) // Wait for the search bar and the first log row to finish loading before overriding.
return
clearInterval(waitForItems)
pageContentContainer.firstChild.outerHTML += "" // Override the content container code (reparse) to remove all events attached to it, so it can be used statically (without interferences from other scripts).
logsContainer = pageContentContainer.getByClass("list-group") // Update the "pointer" to the new instance.
existingEntries = logsContainer.getElementsByClassName("list-group-item")
// Setup the devices dropdown
{
const waitForDropdown = setInterval(function()
{
let devicesDropdown = pageContentContainer.getByClass("dropdown")
if (!devicesDropdown)
return
clearInterval(waitForDropdown)
let customDevicesDropdown = devicesDropdown.parentElement
customDevicesDropdown = customDevicesDropdown.firstChild
customDevicesDropdown.id = "customDevicesDropdown"
customDevicesDropdown.firstChild.disabled = false
customDevicesDropdown.firstChild.style.pointerEvents = "initial"
customDevicesDropdown.onclick = function()
{
const classes = this.lastChild.classList
if (!classes.contains("show"))
classes.add("show")
else classes.remove("show")
}
const devicesDropdownMenu = document.createElement("div")
devicesDropdownMenu.className = "dropdown-menu"
customDevicesDropdown.appendChild(devicesDropdownMenu)
// Get the devices IDs to use for loading the log entries of specific devices. In NextDNS, each device has a randomly
// generated ID (just like the config ID), and this ID is used as parameter to request the log entries of specific devices.
// NX Enhanced loads the log entries by itself instead of letting the site load them, because this way NX Enhanced has access to the log entries' raw data instead of having to depend on what the page
// actually shows, which can change anytime and require constant adaptations for every layout or code change. Also, this makes it possible to implement other features to the logs that require such access.
const requestString = "analytics/top_devices?selector=true"
makeApiRequestAndAddEvent("GET", requestString, function(e)
{
const devicesData = JSON.parse(e.detail)
for (let i=0; i < devicesData.length + 1; i++)
{
const deviceCustom = document.createElement("button")
deviceCustom.className = i == 0 ? "dropdown-item active" : "dropdown-item"
deviceCustom.textContent = i == 0 ? "All devices" : devicesData[i-1].name
deviceCustom.onclick = function()
{
const index = Array.from(this.parentElement.children).indexOf(this) // Get the index of this dropdown item.
cancelLoading = true // Indicates that the chunk currently being loaded should be interrupted.
if (index == 0) // If it's the "All devices" item.
{
currentDeviceId = ""
reloadLogs()
}
else // If instead it's a specific device.
{
currentDeviceId = devicesData[index-1].id
loadLogChunk({device: currentDeviceId, clear: true})
}
// Update the current device selected
this.parentElement.querySelector(".active").classList.remove("active")
this.classList.add("active")
this.parentElement.previousSibling.textContent = this.textContent
hideDevices = false
allHiddenEntriesCountEll.parentElement.style.display = "none"
}
devicesDropdownMenu.appendChild(deviceCustom)
}
// Create the "Other devices" button
const otherDevicesBtn = document.createElement("button")
otherDevicesBtn.className = "dropdown-item"
otherDevicesBtn.id = "otherDevicesBtn"
otherDevicesBtn.style = "border-top: 1px solid lightgray;" // Separator
otherDevicesBtn.innerHTML = "Other devices"
otherDevicesBtn.onclick = function()
{
this.parentElement.firstChild.click() // Click the "All devices" button. Use the full log to filter the devices
customDevicesDropdown.firstChild.innerHTML = "Other devices"
this.parentElement.querySelector(".active").classList.remove("active")
this.classList.add("active")
hideDevices = true
allHiddenEntriesCountEll.parentElement.style.display = "initial"
}
devicesDropdownMenu.appendChild(otherDevicesBtn)
})
}, 100)
}
// Setup the filtering's buttons and inputs
{
// Create the "Filters" button
{
const filtersButton = document.createElement("button")
filtersButton.id = "filtersButton"
filtersButton.className = "btn btn-secondary"
filtersButton.style = "align-self: center; margin-right: 15px;"
filtersButton.innerHTML = "Filters"
filtersButton.onclick = function()
{
event.stopPropagation()
if (this.className.includes("secondary"))
{
filteringOptionsContainer.style.visibility = "visible"
this.innerHTML = "OK"
this.className = this.className.replace("secondary", "primary")
}
else // If it's clicked the second time.
{
updateFilters()
filteringOptionsContainer.style.visibility = "hidden"
this.innerHTML = "Filters"
this.className = this.className.replace("primary", "secondary")
}
}
var container = pageContentContainer.firstChild.firstChild
container.appendChild(filtersButton)
}
// Create the filtering options
{
var filteringOptionsContainer = document.createElement("div")
filteringOptionsContainer.style = "position: absolute; right: 60px; top: 145px; visibility: hidden; display: grid; grid-gap: 10px;"
filteringOptionsContainer.onclick = function() { event.stopPropagation() }
// Create the "Enable filtering" switch
{
const enableFilteringSwitch = createSwitchCheckbox("Enable filtering")
enableFilteringSwitch.style.marginLeft = "-7px"
enableFilteringSwitch.firstChild.checked = true
enableFilteringSwitch.firstChild.onchange = function()
{
filtering = this.checked
if (filtering)
refilterLogEntries()
else
reloadLogs()
}
filteringOptionsContainer.appendChild(enableFilteringSwitch)
}
// Create the filter's inputbox
{
var domainsToHideInput = document.createElement("textarea")
domainsToHideInput.id = "domainsToHideInput"
domainsToHideInput.spellcheck = false
domainsToHideInput.value = domainsToHide.join("\n")
domainsToHideInput.style = "width: 320px; height: 240px; min-width: 250px; min-height: 100px; border-radius: 15px; resize: both; padding-top: 5px;\
border: 1px groove lightgray; outline: 0px; padding-left: 10px; padding-right: 5px; overflow-wrap: normal;"
filteringOptionsContainer.appendChild(domainsToHideInput)
}
// Create the "Show number of entries" switch
{
const showNumEntriesSwitch = createSwitchCheckbox("Show number of entries")
showNumEntriesSwitch.firstChild.checked = GMsettings.LogsOptions.ShowCounters
showNumEntriesSwitch.firstChild.onchange = function()
{
visibleEntriesCountEll.parentElement.style.visibility = this.checked ? "visible" : "hidden"
GMsettings.LogsOptions.ShowCounters = this.checked
GM.setValue("LogsOptions", JSON.stringify(GMsettings.LogsOptions))
}
filteringOptionsContainer.appendChild(showNumEntriesSwitch)
}
container.appendChild(filteringOptionsContainer)
}
function updateFilters()
{
GM.setValue("domainsToHide", domainsToHideInput.value)
domainsToHide = domainsToHideInput.value.split("\n").filter(d => d.trim() != "") // Store each entry in an array, but don't include empty lines
}
}
// Create the refresh button
{
const refreshButton = document.createElement("button")
refreshButton.className = "btn btn-primary"
refreshButton.style = "font-size: x-large; padding: 0px 2px; height: 25px; margin-right: 10px; margin-top: 3px;"
refreshButton.onclick = function() { reloadLogs() }
const icon = document.createElement("div")
icon.style = "margin-top: -9px;"
icon.innerHTML = "⟲"
refreshButton.appendChild(icon)
const inputContainer = logsContainer.firstChild.firstChild
inputContainer.insertBefore(refreshButton, inputContainer.firstChild)
}
// Create the allow/deny popup
{
const elementsContainer = document.createElement("div")
elementsContainer.onclick = function() { event.stopPropagation() } // Prevent the popup from being hidden when clicking inside it
elementsContainer.style = "background: #f7f7f7; position: absolute; right: 130px; height: max-content; width: max-content; \
border: 2px solid lightgray; border-radius: 15px; z-index: 99; padding: 5px 15px 15px 15px; visibility: hidden;"
const errorMsgSpan = document.createElement("span")
errorMsgSpan.style = "display: block; min-height: 25px; line-height: 20px; margin-top: 0px;"
errorMsgSpan.className = "ml-1 my-1 invalid-feedback"
const input = document.createElement("input")
input.style = "border-radius: 5px; width: 300px; padding: 5px;"
input.className = "form-control mb-3"
input.onkeyup = function()
{
if (event.key == "Enter") allowDenyPopup.fullDomainButton.click()
else if (event.key == "Escape") allowDenyPopup.container.style.cssText += 'visibility: hidden;'
}
input.oninput = function()
{
this.classList.remove("is-invalid")
this.previousSibling.innerHTML = ""
}
const fullDomainButton = document.createElement("button")
fullDomainButton.onclick = function()
{
allowDenyPopup.errorMsg.classList.remove("invalid-feedback")
if (allowDenyPopup.listName != "Hide")
{
allowDenyPopup.errorMsg.innerHTML = "Submitting..."
// In NextDNS site, domains, TLDs, blocklists, and pretty much anything added by clicking an "Add" button, are added by sending these items' id with
// each character converted to hexadecimal, instead of plain text (ASCII). This converts the specified domain to hex then sends it to the respective list.
const requestString = allowDenyPopup.listName + "/hex:" + convertToHex(allowDenyPopup.input.value)
makeApiRequestAndAddEvent("PUT", requestString, function(e) // Make an asynchronous HTTP request and run this callback when finished
{
if (e.detail.includes(allowDenyPopup.input.value)) // After successfully adding the domain to the allow/denylist, NextDNS responds with the domain added and it's active status.
{ // This checks if it was successful.
allowDenyPopup.errorMsg.innerHTML = 'Done!'
// Auto dismiss the popup after 1 second
setTimeout(function() {
allowDenyPopup.container.style.cssText += 'visibility: hidden; top: 0px' // Top 0px, because otherwise it stays stuck with a top value greater than the body height when the log is refreshed
allowDenyPopup.errorMsg.innerHTML = ''
}, 1000)
// Update the cached list of domains from the allow/denylist
makeApiRequestAndAddEvent("GET", allowDenyPopup.listName, function(e) {
allowDenyPopup.domainsList[allowDenyPopup.listName] = e.detail
})
}
else if (e.detail.includes("error")) // If it wasn't successful, get the error from the response and show the respective message above the popup's input box
{
let error = JSON.parse(e.detail).error
if (error.includes("exist"))
error = "This domain has already been added"
else if (error.includes("invalid"))
error = "Please enter a valid domain"
allowDenyPopup.errorMsg.textContent = error
allowDenyPopup.errorMsg.classList.add("invalid-feedback")
allowDenyPopup.input.classList.add("is-invalid")
}
})
}
else
{
document.getElementById("domainsToHideInput").value += "\n" + allowDenyPopup.input.value
updateFilters()
allowDenyPopup.errorMsg.innerHTML = 'Done!'
refilterLogEntries()
setTimeout(function() {
allowDenyPopup.container.style.cssText += 'visibility: hidden;'
}, 1000)
}
}
const rootDomainButton = document.createElement("button")
rootDomainButton.style = "width: 127px; float: right;"
rootDomainButton.onclick = function()
{
let input = allowDenyPopup.input
input.value = this.title.substring(this.title.indexOf("*") + 2) // Instead of parsing the root domain again, get it from the title set by the Allow/Deny/Hide buttons
if (allowDenyPopup.listName == "Hide")
input.value = "." + input.value // Add a dot before the root domain to prevent false positives.
allowDenyPopup.fullDomainButton.click()
}
elementsContainer.appendChild(errorMsgSpan)
elementsContainer.appendChild(input)
elementsContainer.appendChild(fullDomainButton)
elementsContainer.appendChild(rootDomainButton)
logsContainer.parentElement.appendChild(elementsContainer)
// Add all these elements in an object for easy access
allowDenyPopup = {
parent: logsContainer.parentElement,
container: elementsContainer,
errorMsg: errorMsgSpan,
input: input,
fullDomainButton: fullDomainButton,
rootDomainButton: rootDomainButton,
listName: "",
domainsList: {
allowlist: "",
denylist: ""
}
}
// Cache the list of domains in the allowlist, then cache the list of domains in the denylist
makeApiRequestAndAddEvent("GET", "allowlist", function(e)
{
allowDenyPopup.domainsList.allowlist = e.detail;
makeApiRequestAndAddEvent("GET", "denylist", function(e) { allowDenyPopup.domainsList.denylist = e.detail })
})
}
// Create the entries countings
{
if (!document.getElementById("visibleEntriesCount"))
{
const countingsContainer = document.createElement("div")
countingsContainer.id = "counters"
countingsContainer.style = "text-align: right; border: solid 2px #aaa; border-radius: 10px; padding: 0px 10px 5px; width: 160px; background: white;"
countingsContainer.style.visibility = GMsettings.LogsOptions.ShowCounters ? "visible" : "hidden"
countingsContainer.innerHTML = `
<b style="line-height: 35px;">Queries count</b>
Listed: <b id="visibleEntriesCount"></b><br>
Filtered: <b id="filteredEntriesCount"></b><br>
<span style="display: none;">All Hidden: <b id="allHiddenEntriesCount"></b><br></span>
Loaded: <b id="loadedEntriesCount"></b>
`
const hoverContainer = document.createElement("div")
hoverContainer.style = "position: fixed; bottom: 20px; right: 11.5%;"
hoverContainer.appendChild(countingsContainer)
document.body.appendChild(hoverContainer)
visibleEntriesCountEll = document.getElementById("visibleEntriesCount")
filteredEntriesCountEll = document.getElementById("filteredEntriesCount") // Entries filtered by the domains filters
allHiddenEntriesCountEll = document.getElementById("allHiddenEntriesCount") // Entries from named devices
loadedEntriesCountEll = document.getElementById("loadedEntriesCount") // All the entries of the loaded chunks
}
}
// Hide popups and dropdowns when the body is clicked
document.body.onclick = function()
{
if (/\/logs/i.test(location.href))
{
// Hide the allow/deny popup
allowDenyPopup.container.style.cssText += 'visibility: hidden; top: 0px'
// Hide the devices dropdown
const customDevicesDropdown = document.getElementById("customDevicesDropdown")
if (customDevicesDropdown != null && event.target != customDevicesDropdown.firstChild)
customDevicesDropdown.lastChild.classList.remove("show")
// Collapse the filtering options
const filtersButton = document.getElementById("filtersButton")
if (filtersButton && !filtersButton.className.includes("secondary"))
filtersButton.click()
}
}
// Disable the original trigger that loads the next log chunk and add NXE's trigger
addEventListener("scroll", function(e)
{
e.stopPropagation() // Don't let the original event listener receive this event
if (!cancelLoading && document.body.getBoundingClientRect().bottom < window.innerHeight * 3) // Only load the next chunk if the user is three screens above the page bottom.
loadLogChunk({before: lastBefore}) // This big distance makes scrolling the logs much more fluid, because when you
// reach the bottom, the next chunk is already loaded and you don't need to wait.
}, true)
// Make the search bar use NXE's code
{
const searchBarForm = logsContainer.querySelector("form")
searchBarForm.outerHTML = searchBarForm.firstChild.outerHTML // Take out the input from inside the form and remove the form element, so that when hitting
// Enter, it doesn't reload the page. This also stripes all the original events of the input box.
var searchBar = logsContainer.querySelector("[type='search']")
searchBar.onkeyup = function(e)
{
if (e.key == "Enter")
{
searchString = this.value.split(" ")[0] // Take only the part before a space character to make the request. This is in preparation for the feature of excluding entries from a search
reloadLogs()
}
else clearSearchButton.style.display = this.value == "" ? "none" : "block" // Hide the clear button when the input box is empty, and display it otherwise.
}
// Recreate the clear button for the search bar, as it's created and deleted in the original code, instead of just hidden
{
var clearSearchButton = document.createElement("div")
clearSearchButton.innerHTML = "X"
clearSearchButton.style = "position: absolute; right: 10px; top: 8px; width: 15px; height: 15px; text-align: center; line-height: 13px; color: white; \
border-radius: 15px; font-size: 10px; user-select: none; cursor: pointer; background: #bbb; font-weight: bold; display: none;"
clearSearchButton.onclick = function()
{
if (searchBar.value != "")
{
searchString = searchBar.value = ""
this.style.display = "none"
reloadLogs()
}
}
searchBar.parentElement.appendChild(clearSearchButton)
}
}
// Adapt the options button
{
const settingsButton = logsContainer.getByClass("settings-button")
settingsButton.onclick = function()
{
if (optionsContainer.style.display == "none")
{
optionsContainer.style.cssText += "display: flex !important;"
settingsButton.classList.add("active")
}
else
{
optionsContainer.style.cssText += "display: none !important;"
settingsButton.classList.remove("active")
}
}
const optionsContainer = document.createElement("div")
optionsContainer.className = "d-md-flex mt-3"
optionsContainer.style = "display: none !important; color: #777;"
// Adapt the "Blocked Queries Only" switch
{
optionsContainer.appendChild(createSwitchCheckbox("Blocked Queries Only"))
optionsContainer.firstChild.classList.add("mr-5")
optionsContainer.firstChild.lastChild.style.fontSize = "80%"
optionsContainer.firstChild.firstChild.onchange = function()
{
blockedQueriesOnly = +this.checked
reloadLogs()
}
}
// Adapt the "Raw DNS logs" switch
{
optionsContainer.appendChild(createSwitchCheckbox("Raw DNS logs"))
optionsContainer.lastChild.lastChild.style.fontSize = "80%"
optionsContainer.lastChild.firstChild.onchange = function()
{
simpleLogs = +!this.checked
reloadLogs()
}
}
settingsButton.parentElement.parentElement.parentElement.appendChild(optionsContainer)
}
// Adapt the "Stream" button (real-time log)
{
const streamButton = logsContainer.getByClass("stream-button")
streamButton.onclick = function()
{
if (streamButton.classList.contains("streaming"))
{
streamButton.classList.remove("streaming")
clearInterval(realTimeLogsPolling)
}
else
{
streamButton.classList.add("streaming")
realTimeLogsPolling = setInterval(function() // Poll for new log entries each 2 seconds.
{
if (!loadingChunk)
loadLogChunk({after: lastAfter})
}, 2000)
}
}
}
// Remove leftover of the original logs container
logsContainer.querySelector("div.text-center").remove()
// And finally start loading the logs
reloadLogs()
}, 250)
function openAllowDenyPopup(button)
{
const domainContainer = button.parentElement.parentElement.firstChild
const fullDomain = domainContainer.secondChild().textContent
let upperDomain =
allowDenyPopup.input.value = fullDomain
allowDenyPopup.errorMsg.classList.remove("invalid-feedback")
allowDenyPopup.input.classList.remove("is-invalid")
allowDenyPopup.errorMsg.innerHTML = ""
if (button.innerText != "Hide")
{
allowDenyPopup.listName = button.innerText.toLowerCase() + "list"
// Check if there's already an upper domain entry that includes the chosen subdomain
while (upperDomain.indexOf(".") >= 0) // As long as there's a dot...
{
upperDomain = upperDomain.substring(upperDomain.indexOf(".") + 1) // ... get the domain after the next dot.
if (allowDenyPopup.domainsList[allowDenyPopup.listName].includes('"' + upperDomain + '"')) // If there's an entry which is included in this upper domain, set a message
{ // to warn the user. Otherwise, check the next upper domain.
allowDenyPopup.errorMsg.innerHTML = "This subdomain is already included in another entry!"
allowDenyPopup.input.classList.add("is-invalid")
allowDenyPopup.errorMsg.classList.add("invalid-feedback")
break
}
}
}
else allowDenyPopup.listName = "Hide"
const subdomains = allowDenyPopup.input.value.split(".")
let rootDomain = subdomains[subdomains.length-2]
if (SLDs.includes(rootDomain))
rootDomain = subdomains[subdomains.length-3] + "." + rootDomain
rootDomain += "." + subdomains[subdomains.length-1]
allowDenyPopup.rootDomainButton.title = button.innerText + " any subdomain under *." + rootDomain
// Set the button's label and color according to the action
allowDenyPopup.fullDomainButton.className =
allowDenyPopup.rootDomainButton.className = button.innerText == "Allow" ? "btn btn-success mt-1" : button.innerText == "Deny" ? "btn btn-danger mt-1" : "btn btn-secondary mt-1"
allowDenyPopup.fullDomainButton.textContent = button.innerText + " domain"
allowDenyPopup.rootDomainButton.textContent = button.innerText + " root"
allowDenyPopup.container.style.cssText += "visibility: visible; top: " + (button.getBoundingClientRect().y - allowDenyPopup.parent.getBoundingClientRect().y - 170) + "px;" // Show the popup right above the buttons
allowDenyPopup.input.focus()
event.stopPropagation() // Don't raise this event to the body, as the body hides the popup when clicked.
}
function loadLogChunk(params)
{
if (loadingChunk && !cancelLoading) // Load only one chunk at a time
return
else
loadingChunk = true
// Clear the logs
{
if (params.clear)
{
for (let i = existingEntries.length-1; i > 0; i--)
existingEntries[i].remove() // If clear is true, then remove all the loaded custom log entries to load again
visibleEntriesCountEll.textContent = filteredEntriesCountEll.textContent = allHiddenEntriesCountEll.textContent = loadedEntriesCountEll.textContent = 0
}
}
// Build the request string
{
logsRequestString = "logs?"
buildLogsRequestString("device", currentDeviceId) // The device id when loading the logs of specific devices.
buildLogsRequestString("before", params.before) // NextDNS' logs always responds to a GET with the 100 most recent log entries. The "before" parameter indicates to NextDNS that it should do so with the log entries that happened before the specified timestamp.
buildLogsRequestString("after", params.after) // The "after" parameter indicates to NextDNS that it should respond with the log entries that happened after the specified timestamp. Used by the stream button (real-time log).
buildLogsRequestString("search", searchString) // The search string. Used by the search bar.
buildLogsRequestString("simple", simpleLogs) // Used by the "Raw DNS logs" switch.
buildLogsRequestString("blockedQueriesOnly", blockedQueriesOnly) // Used by the "Blocked queries only" switch.
}
// Recreate the spinner when loading. It has a different color than the original to indicate that it's being loaded by NXE
{
if (!params.after) // Don't show the spinner when the real-time log is enabled.
{
let spinner = logsContainer.getByClass("spinner-border")
if (spinner) spinner.remove()
spinner = document.createElement("span")
spinner.className = "spinner-border text-primary my-4"
spinner.style = "height: 50px; width: 50px; align-self: center;"
logsContainer.appendChild(spinner)
}
}
// Load the log entries data
makeApiRequestAndAddEvent("GET", logsRequestString, function(e)
{
const response = JSON.parse(e.detail)
const entriesData = response.logs
if (entriesData.length > 0)
{
lastBefore = entriesData.lastItem().timestamp // Store the timestamp of the last entry, to load the older chunk starting from this timestamp. This timestamp is in Unix time.
lastAfter = entriesData[0].timestamp // Store the timestamp of the first entry, to load the newer chunk starting from this timestamp.
const now = Date.now() // Get the current date-time in Unix time
// Process the chunk's log entries
{
for (let i=0; i < entriesData.length; i++)
{
// Cancel old responses when reloading
{
if (cancelLoading)
{
if (!params.clear) // params.clear and cancelLoading are only true when the logs are being reloaded. So if cancelLoading is true
return // but params.clear is not, this means that this is the response of an old request and it should be canceled.
else
cancelLoading = false
}
}
loadedEntriesCountEll.textContent++ // textContent is the actual content of the element, while innerText or innerHTML is the content currently being displayed
// Check if the entry matches any filter, and if so, remove it from the list
{
var domainName = entriesData[i].name
var isNamedDevice = !!entriesData[i].deviceName
if ((filtering && !domainName.includes(".")) // Chrome's random queries never have a dot
|| (hideDevices && isNamedDevice) // If enabled, named devices
|| (filtering && domainsToHide.some(d => domainName.includes(d))) ) // If enabled, domains included in the list of domains to hide
{
entriesData.splice(i,1)
i--
if (!hideDevices || hideDevices && !isNamedDevice)
filteredEntriesCountEll.textContent++
allHiddenEntriesCountEll.textContent++
continue
}
}
// Otherwise, create all the entry's elements
{
const status = entriesData[i].status == 3 ? "whitelisted" : entriesData[i].status == 2 ? "blocked" : "default"
const entryContainer = document.createElement("div")
entryContainer.className = "log list-group-item"
entryContainer.style = "display: flex; justify-content: space-between; align-items: center; border-left: 4px solid;"
entryContainer.style.borderLeftColor = status == "whitelisted" ? "limegreen" : status == "blocked" ? "orangered" : "transparent"
// Create the elements of the left side of the log entry
{
const leftSideContainer = document.createElement("div")
// Create the domain's favicon element
{
const imgEll = document.createElement("img")
imgEll.src = "https://favicons.nextdns.io/hex:" + convertToHex(domainName) + "@1x.png" // NextDNS stores in their server every domain's favicon, and the image files are named after
imgEll.className = "mr-2" // the domain's hex and the favicon's size, being 1x the smallest size and 3x the biggest.
imgEll.style.marginTop = "-2px"
imgEll.onerror = function()
{
// Gray globe icon. This happens when either NextDNS doesn't have the domain's favicon, then responding with a 404 "Not found" error, or the domain itself doesn't have a favicon at all.
this.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAxElEQVR42n3RO0vEYBCF4Sfb2iV/QBAW1s52izWQLoKsYMBAilg\
qfLBk/j9Y5L6FM9XwHuZyhjkKpV6S9EqFXRxUBqFTe/MrDCqHFTdCKwcPbkIIzSyphIsMnHxMOIRqnD1oJ/y0gSEMCkoxNef1ThBKet2y7KOzs6+NoCep9yc5\
LvhHIi1l0nkGLz5dndQS/d3U46ZXpx+X3OZ1wfm4ZGHYCZoJZ9rxzNGoMdfIXGajZqu3gly7tXp91rd3te7+Wf+++w9XTTyOUFyhzgAAAABJRU5ErkJggg=="
}
leftSideContainer.appendChild(imgEll)
}
// Create the domain name element
{
const domainEll = document.createElement("span")
domainEll.className = "domainName"
domainEll.innerHTML = "<span style='opacity: 0.6;'>" + domainName.substring(0, entriesData[i].rootDomainStartIndex) + "</span>"
+ domainName.substring(entriesData[i].rootDomainStartIndex) // NextDNS stores at which character starts the root domain name,
// so everything before rootDomainStartIndex is a subdomain
leftSideContainer.appendChild(domainEll)
}
// Create the DNSSEC icon
{
if (entriesData[i].dnssec)
{
const DnsSecIconSrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAMCAYAAABbayygAAAAgklEQVQYlWP4jwSm7Lr736H10H+H1kP/fXqO/l998glcjgHGmLzrzn+H1kP/vXuO/s9\
ffPG/d8/R/w6th/4fvvkGVSFM0efvv////////+0XX/47tB76n7/4IkLh+QcfUASRNTu0HiJR4fxDD+AC+DBD/uKLw0fh9osv/ucvvkgQAwBXBF9KK3QiTQAAAABJRU5ErkJggg=="
const DnsSecContainer = createStylizedTooltipWithImgParent(DnsSecIconSrc, "Validated with DNSSEC")
DnsSecContainer.style.marginLeft = "10px"
leftSideContainer.appendChild(DnsSecContainer)
}
}
// Create the query type element
{
if (entriesData[i].type)
{
const queryTypeEll = document.createElement("span")
queryTypeEll.style = "font-weight: 600; font-size: 10px; opacity: 0.4; margin-left: 10px; background: #eee; padding: 1px 4px;"
queryTypeEll.innerText = entriesData[i].type
leftSideContainer.appendChild(queryTypeEll)
}
}
// Create the block/allow reason icon and tooltip
{
if (status != "default")
{
const blockReasonIcon = document.createElement("div")
blockReasonIcon.innerHTML = "i"
blockReasonIcon.style = "display: inline-block; border-radius: 12px; width: 13px; height: 13px; text-align: center; color: white; \
font-weight: bold; font-family: serif; font-size: 11px; user-select: none; line-height: 13px; margin-left: 10px;"
blockReasonIcon.style.background = entryContainer.style.borderLeftColor
// matchedName is the CNAME that got blocked. lists is an array containing the name of each list that includes this domain
const blockReasonText = (entriesData[i].matchedName ? "<b style='font-size: 13px; display: block; margin: 5px 3px 8px 3px;'>→ " + entriesData[i].matchedName + "</b>": "")
+ (status == "whitelisted" ? "Allowed" : "Blocked") + " by " + entriesData[i].lists.join(", ")
blockReasonIcon.createStylizedTooltip(blockReasonText)
leftSideContainer.appendChild(blockReasonIcon)
}
}
entryContainer.appendChild(leftSideContainer)
}
// Create the Hide/Allow/Deny buttons
{
const buttonsContainer = document.createElement("div")
buttonsContainer.style = "visibility: hidden; margin-right: 25px; margin-left: auto;"
const hideButton = document.createElement("button")
hideButton.className = "btn btn-secondary mr-4"
hideButton.innerHTML = "Hide"
hideButton.onclick = function() { openAllowDenyPopup(hideButton) }
buttonsContainer.appendChild(hideButton)
if (status == "default")
{
const denyButton = document.createElement("button")
denyButton.className = "btn btn-danger mr-4"
denyButton.innerHTML = "Deny"
denyButton.onclick = function() { openAllowDenyPopup(denyButton) }
buttonsContainer.appendChild(denyButton)
}
if (status != "whitelisted")
{
const allowButton = document.createElement("button")
allowButton.className = "btn btn-success"
allowButton.innerHTML = "Allow"
allowButton.onclick = function() { openAllowDenyPopup(allowButton) }
buttonsContainer.appendChild(allowButton)
}
entryContainer.appendChild(buttonsContainer)
}
// Create the elements of the right side of the log entry
{
const rightSideContainer = document.createElement("div")
rightSideContainer.style = "font-size: 0.9em; display: grid;"
// Create the device name element
{
const deviceEll = document.createElement("span")
deviceEll.textContent = entriesData[i].deviceName
deviceEll.style = "height: 15px; margin-bottom: 10px; margin-left: auto;"
if (!isNamedDevice) // If the query was made from an unnamed device, then show the gray empty space
{
deviceEll.innerHTML = " "
deviceEll.style.cssText += "background-color: #eee; width: 90px; margin-bottom: 5px; margin-top: 5px;"
}
if (entriesData[i].isEncryptedDNS)
{
// Create the DoH/DoT padlock icon
const encryptedQueryIconSrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAALCAYAAABGbhwYAAAAdUlEQVQYlcXPIQ7EMBADwLzWeP8QuqGm+UNC09csDQ51ybVqTjqp7CyZW\
COtNumTtZaO4xBJ9d4159Qz6UI5ZwG4a2aKiB221gRAtVZFhMYYAiCSO3R3AdhOfW/vIUmZmQColHL32kgqIpSeD/wqyXfQ3f8JT3fXMJ8Ei4pHAAAAAElFTkSuQmCC"
const encryptedQueryContainer = createStylizedTooltipWithImgParent(encryptedQueryIconSrc, entriesData[i].protocol)
encryptedQueryContainer.lastChild.style.fontSize = "0.9em"
if (isNamedDevice)
encryptedQueryContainer.style.marginRight = "5px"
else
{
encryptedQueryContainer.style.marginLeft = "-15px"
encryptedQueryContainer.firstChild.style.marginTop = "-4px"
}
deviceEll.insertBefore(encryptedQueryContainer, deviceEll.firstChild)
}
rightSideContainer.appendChild(deviceEll)
}
// Create the date-time element.