-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
1325 lines (1315 loc) · 61 KB
/
renderer.js
File metadata and controls
1325 lines (1315 loc) · 61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
async function backup() {
disableHomeButtons();
await handleScanButtonClick();
if (!window.scanCancelled) {
//get the current registry configuration in the registry.json file
const date = new Date(Date.now());
const full_date = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}_${String(date.getHours()).padStart(2, '0')}_${String(date.getMinutes()).padStart(2, '0')}_${String(date.getSeconds()).padStart(2, '0')}`;
//get the current timestamp
try {
await window.api.copyRegistry('registry.json', './backups', 'backup_' + full_date + '.json');
}
catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Copy Backup: ${err}`);
}
catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
}
enableHomeButtons();
//copy the registry.json file with all the scanned data to the backup folder named as the current timestamp
}
async function changeRegistry(no_user_selection, registry_dict){
showTab("home");
//send users back to the home page while the registry is being updated
window.dualProgressMode = true;
//enable both progress bars because everything needs to be rescanned after the registry is updated
window.InProgress = true;
disableHomeButtons();
var applyButton;
var floatingApplyButton;
if (!no_user_selection) {
applyButton = document.getElementById('apply-button');
floatingApplyButton = document.getElementById('floating-apply-button');
if (applyButton) {
applyButton.classList.add('disabled');
}
if (floatingApplyButton) {
floatingApplyButton.classList.add('disabled');
}
//disable buttons on other tab pages besides home
for (const dropdown of dropdowns) {
if (dropdown.value !== "Corrupted" && dropdown.value !== "") {
registry_dict[dropdown.getAttribute('attached-data')] = parseInt(dropdown.value, 10);
}
else {
registry_dict[dropdown.getAttribute('attached-data')] = dropdown.value;
}
};
}
//get all the required data in the right format if the endpoints were individually configured through user interaction (dropdowns) otherwise just use the passed in registry_dict
for (const [key, obj] of Object.entries(registry_dict)) {
if (JSON.parse(key).state !== "" && JSON.parse(key).state !== "Corrupted") {
if (parseInt(JSON.parse(key).state, 10) === obj) {
delete registry_dict[key];
}
}
else {
if (JSON.parse(key).state === obj.toString()) {
delete registry_dict[key];
}
}
}
//remove all registry data that doesn't change from its previous state
updateRegistryProgress(0, "Preparing to modify registry...");
updateProgressUI();
//show both the registry and scan progress bars
const totalEndpoints = Object.keys(registry_dict).length;
let processedEndpoints = 0;
for (const [key, obj] of Object.entries(registry_dict)) {
await (async (endpoint, newValue) => {
//for every endpoint get the key (representing the full endpoint json structure) and the value representing the updated registry state
if (newValue != "Corrupted") {
processedEndpoints++;
const progress = Math.round((processedEndpoints / totalEndpoints) * 100);
updateRegistryProgress(progress, `Modifying registry: ${processedEndpoints}/${totalEndpoints} endpoints`);
//update the registry progress bar depending on the amount of changed endpoints
try {
var command;
if (endpoint.action === "add") {
command = `
$registryPath = '${endpoint.registrypath}'
$valueName = '${endpoint.registryvalue}'
$newValue = ${newValue}
try {
if (-not (Test-Path -Path $registryPath)) {
New-Item -Path $registryPath -Force | Out-Null
Write-Output "Registry path '$registryPath' created."
}
Set-ItemProperty -Path $registryPath -Name $valueName -Value $newValue -ErrorAction Stop
Write-Output "Registry value '$valueName' set to '$newValue'."
} catch {
Write-Output "$_"
}
`;
//update the registry powershell command for endpoints that require a change in registry DWORD value to achieve the desired effect (add)
}
else {
if (newValue === "") {
command = `
$registryPath = '${endpoint.registrypath}'
$valueName = '${endpoint.registryvalue}'
try {
if (-not (Test-Path -Path $registryPath)) {
New-Item -Path $registryPath -Force | Out-Null
Write-Output "Registry path '$registryPath' created."
}
Remove-ItemProperty -Path $registryPath -Name $valueName -ErrorAction Stop
Write-Output "Registry value '$valueName' has been deleted."
} catch {
Write-Output "$_"
}
`;
}
//update the registry powershell command for endpoints that require the deletion of a registry value to achieve the desired effect (delete)
else if (newValue === 0 && !endpoint.del_DWORD) {
command = `
$registryPath = '${endpoint.registrypath}'
$valueName = '${endpoint.registryvalue}'
try {
if (-not (Test-Path -Path $registryPath)) {
New-Item -Path $registryPath -Force | Out-Null
Write-Output "Registry path '$registryPath' created."
}
New-ItemProperty -Path $registryPath -Name $valueName -PropertyType String -ErrorAction Stop
Write-Output "New string registry value '$valueName' created."
} catch {
Write-Output "$_"
}
`;
}
//update the registry powershell command for endpoints that require the creation of a registry string value to achieve the desired effect (delete)
else if (endpoint.del_DWORD) {
command = `
$registryPath = '${endpoint.registrypath}'
$valueName = '${endpoint.registryvalue}'
$newValue = ${newValue}
try {
if (-not (Test-Path -Path $registryPath)) {
New-Item -Path $registryPath -Force | Out-Null
Write-Output "Registry path '$registryPath' created."
}
Set-ItemProperty -Path $registryPath -Name $valueName -Value $newValue -ErrorAction Stop
Write-Output "Registry value '$valueName' set to '$newValue'."
} catch {
Write-Output "$_"
}
`;
}
//update the registry powershell command for endpoints that require a change in registry DWORD value to achieve the desired effect (delete)
}
await window.api.powerShell(command, false);
//execute the configured powershell command to make registry changes
} catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Run PowerShell Command: ${err}`);
}
catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
}
})(JSON.parse(key), obj);
}
updateRegistryProgress(100, "Registry changes complete");
window.InProgress = false;
//signal the changing of progress bars to scanning
await handleScanButtonClick()
//only show the scanning progress bar and scan all the endpoints
window.dualProgressMode = false;
updateProgressUI();
//end scan
enableHomeButtons();
//enable buttons on home page
if (!no_user_selection) {
const applyButton = document.getElementById('apply-button');
const floatingApplyButton = document.getElementById('floating-apply-button');
if (applyButton) {
applyButton.classList.remove('disabled');
}
if (floatingApplyButton) {
floatingApplyButton.classList.remove('disabled');
floatingApplyButton.classList.remove('visible');
}
};
//enable buttons on other tab pages besides home
}
function createEndpointElement(endpoint, isCategoryDisplay) {
const endpointContainer = document.createElement('div');
for (const key of Object.keys(endpoint.dependencies)) {
if (!endpoint.dependencies[key].includes(regbyname[key].state)) {
endpointContainer.className = 'endpoint-container disabled';
}
}
if (endpointContainer.className === "") {
endpointContainer.className = 'endpoint-container';
}
//check if the endpoint's required dependencies are in the correct state for endpoint use otherwise disable the endpoint
const titleBox = document.createElement('div');
titleBox.className = 'title';
const titleContent = document.createElement('div');
titleContent.className = 'title-content';
const titleText = document.createElement('span');
titleText.className = 'title-text';
titleText.textContent = endpoint.name;
const securityState = getEndpointSecurityState(endpoint);
const statusDot = document.createElement('span');
statusDot.className = `endpoint-status ${securityState}`;
titleText.insertBefore(statusDot, titleText.firstChild);
const statusIndicator = document.createElement('span');
statusIndicator.className = `status-indicator status-${securityState}`;
statusIndicator.textContent = securityState.toUpperCase();
titleContent.appendChild(titleText);
titleContent.appendChild(statusIndicator);
titleBox.appendChild(titleContent);
//assemble each endpoint's header along with a colored dot indicating its status
const dropdown = document.createElement('select');
dropdown.className = "dropdown";
dropdown.setAttribute('attached-data', JSON.stringify(endpoint, null, 2));
//attach each endpoints data to its associated dropdown
const options = endpoint.states;
Object.entries(options).forEach(([key, value]) => {
if (key !== "Corrupted") {
const opt = document.createElement('option');
opt.value = key;
opt.textContent = value;
dropdown.appendChild(opt);
}
});
//create options for each possible endpoint state
dropdown.addEventListener('focus', function() {
this.size = Object.keys(endpoint.states).length-1;
});
dropdown.addEventListener('blur', function() {
this.size = 0;
});
dropdown.addEventListener('change', function() {
this.size = 1;
this.blur();
});
dropdown.addEventListener('change', function() {
const container = this.closest('.endpoint-container');
const endpoint = JSON.parse(this.getAttribute('attached-data') || '{}');
endpoint.state = this.value;
updateEndpointVisualState(container, endpoint);
if (isCategoryDisplay === true) {
let floatingApplyButton = document.getElementById('floating-apply-button');
if (!floatingApplyButton) {
floatingApplyButton = document.createElement('button');
floatingApplyButton.textContent = 'Apply Changes';
floatingApplyButton.className = 'floating-apply-button';
floatingApplyButton.id = 'floating-apply-button';
floatingApplyButton.onclick = async () => {
await changeRegistry(false, {});
};
document.body.appendChild(floatingApplyButton);
}
if (window.floatingButtonVisibility) {
window.removeEventListener('scroll', window.floatingButtonVisibility);
document.querySelector('.main-content')?.removeEventListener('scroll', window.floatingButtonVisibility);
}
setTimeout(() => {
floatingApplyButton.classList.add('visible');
}, 10);
//for categories always show the apply changes button once an endpoint is changed
}
//setup the floating apply button for the categories page
});
//update colored status dot and endpoint theming depending on what state the user selects
if (endpoint.state !== "corrupted") {
dropdown.value = endpoint.state;
}
else {
dropdown.value = endpoint.defaultkey;
}
dropdowns.push(dropdown);
titleBox.appendChild(dropdown);
//add a dropdown menu to the title box
endpointContainer.appendChild(titleBox);
//add the title box to the main endpoints container
endpointContainer.classList.add(securityState);
//add the initial endpoint box theming
const descriptionBox = document.createElement('div');
descriptionBox.className = 'description';
const descriptionText = document.createElement('span');
descriptionText.className = 'description-text';
descriptionText.textContent = endpoint.description;
descriptionBox.appendChild(descriptionText);
//add the description to the description box
const indicatorsContainer = document.createElement('div');
indicatorsContainer.className = 'description-indicators';
const scopeIndicator = document.createElement('div');
scopeIndicator.className = 'registry-scope-indicator';
var scope;
if (endpoint.registrypath.startsWith('HKCU')) {
scope = 'HKCU';
}
else {
scope = 'HKLM';
}
const scopeIcon = document.createElement('div');
scopeIcon.className = `registry-scope-icon ${scope.toLowerCase()}`;
if (scope === 'HKCU') {
scopeIcon.innerHTML = `
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</svg>
`;
//svg icon for current user (single person)
} else {
scopeIcon.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5z"/>
</svg>
`;
//svg icon for local machine (computer)
}
const scopeTooltip = document.createElement('div');
scopeTooltip.className = 'registry-scope-tooltip';
const tooltipContent = scope === 'HKCU' ?
`<span style="color: var(--accent-secondary); font-weight: 600;">Current User - </span>
<span>This endpoint applies only to the currently logged-in user. The system as a whole is unaffected.</span>` :
`<span style="color: var(--accent-secondary); font-weight: 600;">System - </span>
<span>This endpoint applies to the whole system independent of the current user. Settings for the current user will not affect this endpoint.</span>`;
scopeTooltip.innerHTML = tooltipContent;
scopeIndicator.appendChild(scopeIcon);
scopeIndicator.appendChild(scopeTooltip);
let tooltipTimeout;
scopeIcon.addEventListener('mouseenter', () => {
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
const iconRect = scopeIcon.getBoundingClientRect();
const tooltipWidth = 280;
const tooltipHeight = 70;
const verticalOffset = 0;
let tooltipTop = iconRect.top - tooltipHeight + verticalOffset;
const tabsHeight = 80;
let isRepositioned = false;
if (tooltipTop < tabsHeight) {
tooltipTop = tabsHeight + 10;
isRepositioned = true;
}
document.body.appendChild(scopeTooltip);
if (isRepositioned) {
scopeTooltip.classList.add('repositioned');
} else {
scopeTooltip.classList.remove('repositioned');
}
scopeTooltip.style.cssText = `
position: fixed;
left: ${iconRect.right - tooltipWidth + 6}px;
top: ${tooltipTop}px;
width: ${tooltipWidth}px;
opacity: 0;
visibility: visible;
transform: translateY(-5px);
`;
requestAnimationFrame(() => {
scopeTooltip.style.opacity = '1';
scopeTooltip.style.transform = 'translateY(0)';
});
});
scopeIcon.addEventListener('mouseleave', () => {
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
}
scopeTooltip.style.opacity = '0';
scopeTooltip.style.transform = 'translateY(-5px)';
tooltipTimeout = setTimeout(() => {
scopeTooltip.style.visibility = 'hidden';
if (scopeTooltip.parentNode) {
scopeTooltip.parentNode.removeChild(scopeTooltip);
}
tooltipTimeout = null;
}, 200);
});
indicatorsContainer.appendChild(scopeIndicator);
//add a registry scope indicator for an endpoint along with tooltip functionality (HKCU/HKLM)
if (endpoint.dependencies && Object.keys(endpoint.dependencies).length > 0) {
const dependencyIndicator = document.createElement('div');
dependencyIndicator.className = 'dependency-indicator';
const dependencyIcon = document.createElement('div');
dependencyIcon.className = 'dependency-icon';
dependencyIcon.textContent = 'i';
const dependencyTooltip = document.createElement('div');
dependencyTooltip.className = 'dependency-tooltip';
dependencyTooltip.innerHTML = `
<span style="color: var(--accent-secondary); font-weight: 600;">Required Conditions - </span>
<span>
${Object.keys(endpoint.dependencies).map(key => {const values = endpoint.dependencies[key].map(depKey => regbyname[key].states[depKey]); return `${key}: ${values.join(', ')}`;}).join('; ')}
</span>
`;
//display the state(s) of each required endpoint dependency that will allow the current endpoint to work
dependencyIndicator.appendChild(dependencyIcon);
dependencyIndicator.appendChild(dependencyTooltip);
let tooltipTimeout;
dependencyIcon.addEventListener('mouseenter', () => {
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
const iconRect = dependencyIcon.getBoundingClientRect();
const tooltipWidth = 250;
const dependencyCount = Object.keys(endpoint.dependencies).length;
const tooltipHeight = dependencyCount > 3 ? 120 : 60;
const verticalOffset = dependencyCount > 3 ? -14 : -24;
let tooltipTop = iconRect.top - tooltipHeight + verticalOffset;
const tabsHeight = 80;
let isRepositioned = false;
if (tooltipTop < tabsHeight) {
tooltipTop = tabsHeight + 10;
isRepositioned = true;
}
document.body.appendChild(dependencyTooltip);
if (isRepositioned) {
dependencyTooltip.classList.add('repositioned');
} else {
dependencyTooltip.classList.remove('repositioned');
}
dependencyTooltip.style.cssText = `
position: fixed;
left: ${iconRect.right - tooltipWidth + 6}px;
top: ${tooltipTop}px;
width: ${tooltipWidth}px;
opacity: 0;
visibility: visible;
transform: translateY(-5px);
`;
requestAnimationFrame(() => {
dependencyTooltip.style.opacity = '1';
dependencyTooltip.style.transform = 'translateY(0)';
});
});
dependencyIcon.addEventListener('mouseleave', () => {
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
}
dependencyTooltip.style.opacity = '0';
dependencyTooltip.style.transform = 'translateY(-5px)';
tooltipTimeout = setTimeout(() => {
dependencyTooltip.style.visibility = 'hidden';
tooltipTimeout = null;
}, 200);
});
indicatorsContainer.appendChild(dependencyIndicator);
//add a dependency indicator for an endpoint along with tooltip functionality if an endpoint has dependencies
}
descriptionBox.appendChild(indicatorsContainer);
//add indicators to the description box
endpointContainer.appendChild(descriptionBox);
//add the endpoint description box to the endpoint box
return endpointContainer;
}
//add full endpoint configuration functionality with a modern and easy to use interface
function createProgressModal() {
if (window.progressModal) return window.progressModal;
const modal = document.createElement('div');
modal.className = 'progress-modal';
modal.id = 'progress-modal';
modal.innerHTML = `
<div class="progress-card">
<div class="progress-header">
<div class="progress-title" id="progress-main-title">System Scan</div>
<div class="progress-subtitle" id="progress-subtitle">Analyzing endpoints</div>
</div>
<!-- Registry Progress Section -->
<div class="progress-section registry-section" id="registry-progress-section" style="display: none;">
<div class="progress-label">
<div class="progress-label-text">
<span class="progress-status-icon pending" id="registry-status-icon"></span>
Registry Changes
</div>
<div class="progress-percentage registry" id="registry-progress-percentage">0%</div>
</div>
<div class="progress-bar-container">
<div class="progress-bar-fill registry" id="registry-progress-fill" style="width: 0%"></div>
</div>
<div class="progress-text" id="registry-progress-text">Preparing registry modifications...</div>
</div>
<!-- Scan Progress Section -->
<div class="progress-section scan-section" id="scan-progress-section">
<div class="progress-label">
<div class="progress-label-text">
<span class="progress-status-icon pending" id="scan-status-icon"></span>
Endpoint Scan
</div>
<div class="progress-percentage scan" id="scan-progress-percentage">0%</div>
</div>
<div class="progress-bar-container">
<div class="progress-bar-fill scan" id="scan-progress-fill" style="width: 0%"></div>
</div>
<div class="progress-text" id="scan-progress-text">Initializing scan...</div>
</div>
<div class="progress-controls">
<button class="cancel-button" id="cancel-scan-btn">
<span>Cancel Scan</span>
</button>
</div>
</div>
`;
document.body.appendChild(modal);
const cancelButton = modal.querySelector('#cancel-scan-btn');
cancelButton.addEventListener('click', handleCancelScan);
window.progressModal = modal;
return modal;
}
//create a progress modal to display progress bars
async function disableHomeButtons() {
homeButton.classList.add('disabled');
searchButton.classList.add('disabled');
insecureButton.classList.add('disabled');
secureButton.classList.add('disabled');
optionalButton.classList.add('disabled');
scanButton.classList.add('disabled');
backupButton.classList.add('disabled');
documentationButton.classList.add('disabled');
backupImport.classList.add('disabled');
}
//disable buttons on home page
async function enableHomeButtons() {
homeButton.classList.remove('disabled');
searchButton.classList.remove('disabled');
insecureButton.classList.remove('disabled');
secureButton.classList.remove('disabled');
optionalButton.classList.remove('disabled');
scanButton.classList.remove('disabled');
documentationButton.classList.remove('disabled');
backupButton.classList.remove('disabled');
backupImport.classList.remove('disabled');
}
//enable buttons on home page
function getEndpointSecurityState(endpoint) {
if (endpoint.state === 'corrupted') return 'corrupted';
const currentState = endpoint.state;
const secureKey = endpoint.securekey;
if (currentState === secureKey) return 'secure';
return endpoint.section === 'optional' ? 'optional' : 'insecure';
}
//quick function to return the string state of an endpoint based on its numerical state
async function handleCancelScan() {
if (!window.InProgress) {
return;
}
//prevent spam
const cancelButton = document.getElementById('cancel-scan-btn');
if (cancelButton && cancelButton.disabled) {
return;
}
window.scanCancelled = true;
const progressBar = document.getElementById('progress-bar');
const progressPercentage = document.getElementById('progress-percentage');
if (progressBar) progressBar.style.display = 'none';
if (progressPercentage) progressPercentage.style.display = 'none';
updateScanProgress(window.scanProgressData.percentage, 'Scan cancelled');
//indicate that a scan was cancelled
if (cancelButton) {
cancelButton.textContent = 'Cancelling...';
cancelButton.disabled = true;
}
await resetReg();
setTimeout(() => {
hideProgressModal();
}, 1000);
}
//handle the cancellation of scans and reset everything
async function handleScanButtonClick() {
if (window.InProgress) {
return;
}
//prevent multiple scans from being opened
window.InProgress = true;
window.scanCancelled = false;
//update global scan variables
updateProgressUI();
//show single progress bar
await resetReg();
//reset the registry.json file
try {
var all_endpoints = [];
for (const category of window.categories) {
all_endpoints = all_endpoints.concat(category.endpoints);
}
//get all endpoints from endpoints.js by concatenating each category
const validEndpoints = [];
for (const endpoint of all_endpoints) {
if (window.scanCancelled) break;
if (endpoint.version_added <= version && (endpoint.version_removed == false || (typeof endpoint.version_removed != "boolean" && (endpoint.version_removed > version)))) {
validEndpoints.push(endpoint);
}
}
//filter out endpoints that don't exist in the user's current windows version
await processBatchedEndpoints(validEndpoints);
//process endpoints in optimized batches
} catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Process Endpoints: ${err}`);
} catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
} finally {
window.InProgress = false;
updateProgressUI();
//end scan
}
}
async function handleSearchInput(event) {
const SEARCH_DEBOUNCE_DELAY = 200;
const query = event.target.value.toLowerCase().trim();
if (window.searchTimeout) {
clearTimeout(window.searchTimeout);
}
if (query === window.lastSearchQuery) {
return;
}
//don't search a query if it has already been searched
window.searchTimeout = setTimeout(async () => {
const searchTab = document.getElementById('search');
if (searchTab.classList.contains('active')) {
const searchBar = document.getElementById('search-bar');
searchBar.classList.add("disabled");
await populateEndpointsList("search", query);
window.lastSearchQuery = query;
searchBar.classList.remove("disabled");
}
}, SEARCH_DEBOUNCE_DELAY);
//submit a search query every SEARCH_DEBOUNCE_DELAY milliseconds
}
//searches for endpoints in real time
function hideProgressModal() {
if (window.progressModal) {
window.progressModal.classList.remove('show');
setTimeout(() => {
const cancelBtn = window.progressModal.querySelector('#cancel-scan-btn');
const scanSection = window.progressModal.querySelector('#scan-progress-section');
const registrySection = window.progressModal.querySelector('#registry-progress-section');
if (cancelBtn) {
cancelBtn.textContent = 'Cancel Scan';
cancelBtn.disabled = false;
cancelBtn.style.display = 'flex';
}
if (scanSection) scanSection.classList.remove('active', 'completed');
if (registrySection) registrySection.classList.remove('active', 'completed');
window.dualProgressMode = false;
}, 300);
}
}
//hide the progress modal after a scan is finished or cancelled
async function importBackup() {
disableHomeButtons();
var file;
try {
file = await window.api.openFolder("./backups");
}
catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Open Folder: ${err}`);
}
catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
//prompt to select a backup file
if (!file.endsWith('.json')) {
enableHomeButtons();
return;
}
//filter out invalid backups
var regBackup;
try {
regBackup = await window.api.readRegistry(file);
}
catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Read Backup: ${err}`);
}
catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
//read the backup
var registry_dict = {};
//dictionary that will contain current endpoint data as the key with the backed up endpoint state as the value
try {
regBackup.forEach(endpoint => {
if (endpoint.version_added <= version && (endpoint.version_removed === false || (typeof endpoint.version_removed != "boolean" && (endpoint.version_removed < version)))) {
if (endpoint.state != "" && endpoint.state != "Corrupted") {
registry_dict[JSON.stringify(regbyname[endpoint.name], null, 2)] = parseInt(endpoint.state, 10);
}
else {
registry_dict[JSON.stringify(regbyname[endpoint.name], null, 2)] = endpoint.state;
}
}
//only import the endpoints that exist in a user's current version of windows
});
await changeRegistry(true, registry_dict);
//send the formatted registry data to the changeRegistry function for processing
} catch (err) {
try {
await window.api.logError('./log.txt', `Invalid Endpoint In Backup: ${err}`);
}
catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
enableHomeButtons();
//enable buttons on home page
}
//imports endpoint data from a backup .json file
function openDocumentation() {
window.api.openExternal('https://github.com/milrn/SH13LDME/blob/main/README.md');
}
//open documentation github page
async function populateCategories() {
const searchTab = document.getElementById('search');
const searchResultsInfo = document.getElementById('search-results-info');
if (searchResultsInfo) {
searchResultsInfo.style.display = 'none';
}
//remove the search info display when displaying categories
window.categories.forEach((category, index) => {
const categoryContainer = document.createElement('div');
categoryContainer.className = 'category-container';
const status = category.getSecurityStatus(regbyname);
//get the amount of endpoints secured out of the total number of endpoints in a category (this is a method defined in endpoints.js)
const statusText = `${status.securedCount}/${status.totalCount} secured`;
categoryContainer.innerHTML = `
<div class="category-header">
<div class="category-title">
<div class="category-name-section">
<span class="category-name">${category.name}</span>
<span class="category-status">${statusText}</span>
</div>
<button class="category-secure-button" onclick="secureCategory(${index})">
Secure All
</button>
</div>
</div>
<div class="category-description">${category.description}</div>
<div class="category-endpoints" id="category-endpoints-${index}">
</div>
`;
if (status.isFullySecured) {
categoryContainer.classList.add('fully-secured');
} else {
categoryContainer.classList.add('partially-secured');
}
//change styles depending on whether a category is fully secured or not
const header = categoryContainer.querySelector('.category-header');
header.addEventListener('click', (e) => {
if (!e.target.classList.contains('category-secure-button')) {
toggleCategoryDropdown(index);
}
});
//if the category display header is clicked display all its child endpoints or retract all its child endpoints
searchTab.appendChild(categoryContainer);
//add each category box to the page container
});
}
async function populateEndpointsList(tabId, query) {
const endpointsContainer = document.getElementById(tabId);
if (tabId != "search") {
endpointsContainer.innerHTML = '';
}
else {
const searchBar = document.getElementById('search-bar');
for (let i = endpointsContainer.childNodes.length - 1; i >= 0; i--) {
const child = endpointsContainer.childNodes[i];
if (child !== searchBar && child.id !== 'search-results-info') {
endpointsContainer.removeChild(child);
}
}
}
//makes sure that if the search page is open the search bar and info display don't get removed
const heading = document.createElement('h3');
heading.textContent = `${tabId.charAt(0).toUpperCase() + tabId.slice(1)} Endpoints`;
//set each tabs' title
const applyChanges = document.createElement('button');
applyChanges.textContent = 'Apply Changes';
applyChanges.className = 'apply-button';
applyChanges.id = 'apply-button';
applyChanges.onclick = async () => {
await changeRegistry(false, {});
};
let floatingApplyButton = document.getElementById('floating-apply-button');
if (!floatingApplyButton) {
floatingApplyButton = document.createElement('button');
floatingApplyButton.textContent = 'Apply Changes';
floatingApplyButton.className = 'floating-apply-button';
floatingApplyButton.id = 'floating-apply-button';
floatingApplyButton.onclick = applyChanges.onclick;
document.body.appendChild(floatingApplyButton);
}
setupFloatingApplyButton(applyChanges, floatingApplyButton);
heading.appendChild(applyChanges);
//add an apply changes button next to the title in the heading that follows the user if they scroll past it
endpointsContainer.appendChild(heading);
//add the heading to the page container
const endpoints = [];
const reg = Object.values(regbyname);
for (let i = 0; i < reg.length; i++) {
if (reg[i].state === reg[i].securekey && tabId === "secure") {
endpoints.push(reg[i]);
} else if (reg[i].state !== reg[i].securekey && reg[i].section === "optional" && tabId === "optional") {
endpoints.push(reg[i]);
} else if (reg[i].state !== reg[i].securekey && reg[i].section === "insecure" && tabId === "insecure") {
endpoints.push(reg[i]);
} else if ((reg[i].name.toLowerCase().includes(query.toLowerCase()) || reg[i].description.toLowerCase().includes(query.toLowerCase())) && tabId === "search") {
endpoints.push(reg[i]);
}
}
//sort through the registry data for the endpoints that should be shown on a certain page
endpoints.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
//sort the endpoints alphabetically
if (tabId === "search") {
let searchResultsInfo = document.getElementById('search-results-info');
if (!searchResultsInfo) {
searchResultsInfo = document.createElement('div');
searchResultsInfo.id = 'search-results-info';
searchResultsInfo.className = 'search-results-info';
const searchBar = document.getElementById('search-bar');
searchBar.parentNode.insertBefore(searchResultsInfo, searchBar.nextSibling);
}
//add search results information display
if (query.trim() === '') {
await populateCategories();
return;
//show categories instead of endpoints if there is no query in the search tab
} else {
if (searchResultsInfo) {
searchResultsInfo.style.display = 'block';
}
const resultText = endpoints.length === 1
? `Found ${endpoints.length} endpoint matching '${query}'`
: `Found ${endpoints.length} endpoints matching '${query}'`;
searchResultsInfo.textContent = resultText;
searchResultsInfo.style.color = endpoints.length > 0 ? '#0c8b61' : '#ff6b6b';
//show search results instead of categories if there is a query
}
}
dropdowns = [];
endpoints.forEach(endpoint => {
endpointContainer = createEndpointElement(endpoint, false);
endpointsContainer.appendChild(endpointContainer);
//add the endpoint box to the page container
});
//create a new display with configurable options for each valid endpoint
}
//create all the category displays
async function processBatchedEndpoints(endpoints) {
const totalEndpoints = endpoints.length;
let completedEndpoints = 0;
updateScanProgress(0, `Initializing scan of ${totalEndpoints} endpoints...`);
const BULK_BATCH_SIZE = 15
for (let i = 0; i < endpoints.length; i += BULK_BATCH_SIZE) {
if (window.scanCancelled) {
break;
}
const batch = endpoints.slice(i, i + BULK_BATCH_SIZE);
try {
const commandParameters = batch.map(endpoint => ({
registrypath: endpoint.registrypath,
registryvalue: endpoint.registryvalue
}));
//list of all the required command parameters
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('PowerShell Bulk Process is Hanging')), 10000)
);
const bulkCommand = `
$results = @()
${commandParameters.map((cmd, index) => `
try {
$registryPath = "${cmd.registrypath}"
$valueName = "${cmd.registryvalue}"
if (-not (Test-Path -Path $registryPath)) {
New-Item -Path $registryPath -Force | Out-Null
}
$registryValue = Get-ItemProperty -Path $registryPath -Name $valueName -ErrorAction Stop
$results += @{
Index = ${index}
Value = "$($registryValue.$valueName)"
Error = $null
}
} catch {
$results += @{
Index = ${index}
Value = $null
Error = "$_"
}
}
`).join('')}
$results | ConvertTo-Json -Depth 3
`;
//make a bulk command based on all the mapped command parameters
const bulkPromise = window.api.powerShell(bulkCommand, true);
const results = await Promise.race([bulkPromise, timeoutPromise]);
//process the bulk command and report hanging
for (const result of results) {
const endpoint = batch[result.Index];
if (result.Error) {
if (result.Error.toLowerCase().includes(`not exist`)) {
if (endpoint.action === "add") {
endpoint.state = endpoint.defaultkey;
} else {
endpoint.state = "";
}
} else {
endpoint.state = "corrupted";
}
} else if (Object.keys(endpoint.states).includes(result.Value) && (endpoint.action === "add" || (endpoint.action === "delete" && endpoint.del_DWORD))) {
endpoint.state = result.Value;
} else if (result.Value === "" && endpoint.action === "delete" && !endpoint.del_DWORD) {
endpoint.state = "0";
} else {
endpoint.state = "corrupted";
}
if (!window.scanCancelled && i + BULK_BATCH_SIZE >= endpoints.length) {
const endpointsData = [];
for (let j = 0; j < endpoints.length; j++) {
endpointsData.push({
name: endpoints[j].name,
registrypath: endpoints[j].registrypath,
registryvalue: endpoints[j].registryvalue,
description: endpoints[j].description,
state: endpoints[j].state,
section: endpoints[j].section,
states: endpoints[j].states,
action: endpoints[j].action,
del_DWORD: endpoints[j].del_DWORD,
securekey: endpoints[j].securekey,
defaultkey: endpoints[j].defaultkey,
version_added: endpoints[j].version_added,
version_removed: endpoints[j].version_removed,
dependencies: endpoints[j].dependencies
});
}
await window.api.writeRegistry("registry.json", endpointsData);
//write all endpoint data to the registry.json file
}
}
//update endpoint's properties based on its state in the registry
completedEndpoints += batch.length;
const progress = Math.round((completedEndpoints / totalEndpoints) * 100);
updateScanProgress(progress, `${completedEndpoints}/${totalEndpoints} endpoints scanned`);
await new Promise(resolve => setTimeout(resolve, 100));
//update progress bar based on the current amount of processed endpoints
} catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Process Bulk Endpoints: ${err}`);
} catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
}
if (!window.scanCancelled) {
updateScanProgress(window.scanProgressData.percentage, `Scan completed! ${completedEndpoints}/${totalEndpoints} endpoints scanned.`);
const cancelButton = document.getElementById('cancel-scan-btn');
if (cancelButton) {
cancelButton.style.display = 'none';
}
regbyname = {};
var reg;
try {
reg = await window.api.readRegistry('registry.json');
} catch (err) {
try {
await window.api.logError('./log.txt', `Failed to Read registry.json: ${err}`);
} catch (logerr) {
await window.api.displayDialog('SH13LDME©', `Failed to Write This Error To Log File: ${err}`);
}
window.close();
}
for (let i = 0; i < reg.length; i++) {