Repository navigation
Expand file tree
/
Copy pathSentinelGuard.py
More file actions
1386 lines (1150 loc) · 51.8 KB
/
Copy pathSentinelGuard.py
File metadata and controls
1386 lines (1150 loc) · 51.8 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
"""
SentinelGuard - idle-activated authentication guard for Windows.
Run with ``python SentinelGuard.py``. See README.md for setup and options.
"""
from Guard.Head import *
# How often the idle poll runs. Cheap (one Win32 call), so a short interval is
# fine and keeps the guard responsive.
IDLE_POLL_MS = 2000
PASSWORD_SYMBOLS = "!@#$%^&*()-_=+[]{};:'\",.<>/?\\|`~"
# Written as escapes rather than literal glyphs: the previous version of this
# file was saved in a mismatched encoding and shipped mojibake in the UI.
CHECK_MARK = "\u2713" # check mark
CROSS_MARK = "\u2717" # ballot X
class SentinelOverlay(QWidget):
"""Full-window dimming layer painted behind the floating islands."""
def __init__(self, parent=None):
super().__init__(parent)
self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
self.setAttribute(Qt.WA_TranslucentBackground, True)
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(0, 0, 0, 240))
class SentinelWall(QMainWindow):
def __init__(self):
super().__init__()
self.vault = SentinelVault()
profile = self.vault.profile
self.first_name = profile.first_name
self.last_name = profile.last_name
self.email = profile.email
self.dob = profile.dob
self.inactivity_timeout = self.vault.inactivity_timeout_ms
self.is_setup = self.vault.is_configured
self.facial_enabled = self.vault.facial_enabled
self.is_visible = True
self.idle_started = False # only starts after the first successful login
# Panel widgets; recreated on every panel switch, so always re-check
# for None before touching them from a timer or slot.
self.code_input = None
self.qr_label = None
self.qr_pixmap = None
self.recovery_input = None
self.mp_login_input = None
self.settings_mp_input = None
self.status_label = None
self.lockout_label = None
self.first_name_input = None
self.last_name_input = None
self.email_input = None
self.dob_input = None
self.master_password_input = None
self.inactivity_input = None
self.settings_inactivity_input = None
self.settings_new_master_input = None
self.settings_confirm_master_input = None
self.mp_len_label = None
self.mp_upper_label = None
self.mp_digit_label = None
self.mp_symbol_label = None
self.pending_totp_secret = ""
self.pending_recovery_code = ""
self.fade_anim = None
self._shake_anims = []
self.face_thread = None
self.face_worker = None
self.idle_timer = QTimer(self)
self.idle_timer.timeout.connect(self.check_idle)
self.lockout_timer = QTimer(self)
self.lockout_timer.setInterval(1000)
self.lockout_timer.timeout.connect(self.refresh_lockout_state)
self.setup_ui()
self.init_window_flags()
# ------------------------------------------------------------------
# Window chrome
# ------------------------------------------------------------------
def resizeEvent(self, event):
super().resizeEvent(event)
if getattr(self, "overlay", None) is not None:
self.overlay.setGeometry(self.rect())
def setup_ui(self):
self.setWindowTitle("SentinelGuard")
if app_ico:
self.setWindowIcon(QIcon(app_ico))
central = QWidget(self)
self.setCentralWidget(central)
self.setStyleSheet("""
QMainWindow { background: transparent; }
QWidget {
background: transparent;
color: #f5f5f5;
font-family: 'Segoe UI', system-ui, sans-serif;
}
QLabel { color: #f5f5f5; font-weight: 500; }
""")
self.overlay = SentinelOverlay(self)
self.overlay.setGeometry(self.rect())
self.overlay.lower()
root_layout = QHBoxLayout(central)
root_layout.setSpacing(24)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setAlignment(Qt.AlignCenter)
self.weather_island = self._make_island("weatherIsland", 400, 620)
weather_layout = QVBoxLayout(self.weather_island)
weather_layout.setContentsMargins(0, 0, 0, 0)
weather_layout.setSpacing(0)
self.view = QWebEngineView(self.weather_island)
self.view.setAttribute(Qt.WA_TranslucentBackground, True)
self.view.setStyleSheet("background: transparent;")
self.view.page().setBackgroundColor(QColor(0, 0, 0, 0))
weather_layout.addWidget(self.view)
self.auth_island = self._make_island("authIsland", 620, 760)
self.island_layout = QVBoxLayout(self.auth_island)
self.island_layout.setSpacing(16)
self.island_layout.setContentsMargins(32, 32, 32, 32)
self.storage_island = self._make_island("storageIsland", 400, 620)
storage_layout = QVBoxLayout(self.storage_island)
storage_layout.setContentsMargins(0, 0, 0, 0)
storage_layout.setSpacing(0)
self.storage_view = StoragePage(drive_root=self.vault.storage_drive)
storage_layout.addWidget(self.storage_view)
root_layout.addWidget(self.weather_island, 0, Qt.AlignmentFlag.AlignRight)
root_layout.addWidget(self.auth_island, 0, Qt.AlignmentFlag.AlignCenter)
root_layout.addWidget(self.storage_island, 0, Qt.AlignmentFlag.AlignLeft)
if self.is_setup:
self.show_auth_panel()
else:
self.show_details_panel()
self.view.loadFinished.connect(self.on_load_finished)
self.view.load(QUrl(f"http://127.0.0.1:{PORT}/weather"))
def _make_island(self, object_name: str, width: int, height: int) -> QWidget:
island = QWidget()
island.setObjectName(object_name)
island.setFixedSize(width, height)
island.setStyleSheet(f"""
#{object_name} {{
background-color: #000000;
border-radius: 20px;
border: 1px solid transparent;
}}
""")
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(40)
shadow.setColor(QColor(0, 0, 0, 180))
shadow.setOffset(0, 18)
island.setGraphicsEffect(shadow)
return island
def on_load_finished(self, ok: bool):
if not ok:
log.warning("Weather widget failed to load from 127.0.0.1:%s", PORT)
return
self.view.page().runJavaScript(
"document.documentElement.style.background = 'transparent';"
"document.documentElement.style.backgroundColor = 'transparent';"
"document.body.style.background = 'transparent';"
"document.body.style.backgroundColor = 'transparent';"
)
# ------------------------------------------------------------------
# Panel plumbing
# ------------------------------------------------------------------
def clear_island(self):
self.lockout_timer.stop()
self.status_label = None
self.lockout_label = None
self.code_input = None
self._clear_layout_recursive(self.island_layout)
def _clear_layout_recursive(self, layout):
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
child = item.layout()
if widget is not None:
widget.setParent(None)
widget.deleteLater()
elif child is not None:
self._clear_layout_recursive(child)
child.deleteLater()
def _add_title(self, subtitle: str | None = None):
header_row = QHBoxLayout()
header_row.setSpacing(10)
header_row.setAlignment(Qt.AlignCenter)
icon_label = QLabel()
if system_ico:
icon_label.setPixmap(
QPixmap(system_ico).scaled(48, 48, Qt.KeepAspectRatio, Qt.SmoothTransformation)
)
icon_label.setFixedSize(48, 48)
icon_label.setAlignment(Qt.AlignCenter)
title = QLabel("SentinelGuard")
title.setAlignment(Qt.AlignCenter)
title.setStyleSheet(
"QLabel { font-size: 22px; font-weight: 700; padding: 8px 0; color: #ffffff; }"
)
header_row.addWidget(icon_label)
header_row.addWidget(title)
self.island_layout.addLayout(header_row)
if subtitle:
info = QLabel(subtitle)
info.setAlignment(Qt.AlignCenter)
info.setWordWrap(True)
info.setStyleSheet("color: #b0b0b0; font-size: 13px;")
self.island_layout.addWidget(info)
def _add_status_label(self):
"""Inline feedback area. Preferred over modal dialogs on a lock screen."""
self.status_label = QLabel("")
self.status_label.setAlignment(Qt.AlignCenter)
self.status_label.setWordWrap(True)
self.status_label.setStyleSheet("color: #ff8888; font-size: 12px;")
self.status_label.hide()
self.island_layout.addWidget(self.status_label)
def set_status(self, message: str, *, error: bool = True):
if self.status_label is None:
# No inline area on this panel; fall back to a modal.
(QMessageBox.warning if error else QMessageBox.information)(
self, "SentinelGuard", message
)
return
colour = "#ff8888" if error else "#88ff88"
self.status_label.setStyleSheet(f"color: {colour}; font-size: 12px;")
self.status_label.setText(message)
self.status_label.setVisible(bool(message))
def _password_field(self, placeholder: str) -> QWidget:
"""A password QLineEdit with a reveal toggle, wrapped in a row widget."""
container = QWidget()
row = QHBoxLayout(container)
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(6)
field = QLineEdit()
field.setPlaceholderText(placeholder)
field.setEchoMode(QLineEdit.Password)
field.setStyleSheet(self._input_style())
row.addWidget(field, stretch=1)
toggle = QToolButton()
toggle.setText("Show")
toggle.setCheckable(True)
toggle.setCursor(Qt.PointingHandCursor)
toggle.setFixedHeight(36)
toggle.setStyleSheet("""
QToolButton {
background-color: #101010; color: #b0b0b0;
border: 1px solid #333333; border-radius: 10px; padding: 0 10px;
}
QToolButton:checked { color: #ffffff; border-color: #888888; }
""")
def on_toggled(checked: bool):
field.setEchoMode(QLineEdit.Normal if checked else QLineEdit.Password)
toggle.setText("Hide" if checked else "Show")
toggle.toggled.connect(on_toggled)
row.addWidget(toggle)
container.field = field # convenience handle for callers
return container
# ------------------------------------------------------------------
# Registration
# ------------------------------------------------------------------
def show_details_panel(self):
self.clear_island()
self._add_title("Create your profile")
name_row = QHBoxLayout()
name_row.setSpacing(12)
self.first_name_input = QLineEdit()
self.first_name_input.setPlaceholderText("First name")
self.first_name_input.setMaxLength(64)
self.first_name_input.setStyleSheet(self._input_style())
name_row.addWidget(self.first_name_input)
self.last_name_input = QLineEdit()
self.last_name_input.setPlaceholderText("Surname")
self.last_name_input.setMaxLength(64)
self.last_name_input.setStyleSheet(self._input_style())
name_row.addWidget(self.last_name_input)
self.island_layout.addLayout(name_row)
self.email_input = QLineEdit()
self.email_input.setPlaceholderText("Email (name@provider.domain)")
self.email_input.setStyleSheet(self._input_style())
email_regex = QRegularExpression(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$")
self.email_input.setValidator(QRegularExpressionValidator(email_regex, self.email_input))
self.island_layout.addWidget(self.email_input)
self.dob_input = QLineEdit()
self.dob_input.setPlaceholderText("MM/DD/YYYY")
self.dob_input.setInputMask("99/99/9999")
self.dob_input.setStyleSheet(self._input_style())
self.island_layout.addWidget(self.dob_input)
self.inactivity_input = QLineEdit()
self.inactivity_input.setPlaceholderText(
f"Inactivity timeout in minutes ({MIN_INACTIVITY_MINUTES}-{MAX_INACTIVITY_MINUTES})"
)
self.inactivity_input.setStyleSheet(self._input_style())
self.inactivity_input.setValidator(
QIntValidator(MIN_INACTIVITY_MINUTES, MAX_INACTIVITY_MINUTES, self.inactivity_input)
)
self.inactivity_input.setText(str(self.inactivity_timeout // 60000))
self.island_layout.addWidget(self.inactivity_input)
password_row = self._password_field("Set Master Password")
self.master_password_input = password_row.field
self.master_password_input.textChanged.connect(self.update_password_checklist)
self.island_layout.addWidget(password_row)
checklist = QVBoxLayout()
checklist.setSpacing(2)
self.mp_len_label = QLabel(f"{CROSS_MARK} At least 8 characters")
self.mp_upper_label = QLabel(f"{CROSS_MARK} At least 1 uppercase letter")
self.mp_digit_label = QLabel(f"{CROSS_MARK} At least 1 number")
self.mp_symbol_label = QLabel(f"{CROSS_MARK} At least 1 symbol or special character")
for label in (self.mp_len_label, self.mp_upper_label,
self.mp_digit_label, self.mp_symbol_label):
label.setStyleSheet("color: #b0b0b0; font-size: 11px;")
checklist.addWidget(label)
self.island_layout.addLayout(checklist)
self._add_status_label()
save_btn = QPushButton("Save")
save_btn.setFixedHeight(40)
save_btn.setCursor(Qt.PointingHandCursor)
save_btn.setStyleSheet(self._primary_button_style())
save_btn.clicked.connect(self.save_profile_and_show_link_panel)
self.island_layout.addWidget(save_btn, alignment=Qt.AlignRight)
@Slot()
def save_profile_and_show_link_panel(self):
first_name = (self.first_name_input.text() or "").strip()
last_name = (self.last_name_input.text() or "").strip()
email = (self.email_input.text() or "").strip()
dob = self.dob_input.text()
password = self.master_password_input.text() or ""
timeout_text = (self.inactivity_input.text() or "").strip()
missing = []
if not first_name:
missing.append("First name")
if not last_name:
missing.append("Surname")
if not email:
missing.append("Email")
if not dob or "_" in dob:
missing.append("Date of birth")
if not password:
missing.append("Master Password")
if not timeout_text:
missing.append("Inactivity timeout")
if missing:
self.set_status("Required: " + ", ".join(missing))
return
validator = self.email_input.validator()
if validator is not None:
state = validator.validate(email, 0)[0]
if state != QRegularExpressionValidator.Acceptable:
self.set_status("Email must be in the format name@provider.domain.")
return
if not self.is_master_password_strong(password):
self.set_status(
"Master Password needs 8+ characters with an uppercase letter, "
"a number and a symbol."
)
return
try:
timeout_minutes = int(timeout_text)
except ValueError:
timeout_minutes = 0
if not MIN_INACTIVITY_MINUTES <= timeout_minutes <= MAX_INACTIVITY_MINUTES:
self.set_status(
f"Inactivity timeout must be between {MIN_INACTIVITY_MINUTES} "
f"and {MAX_INACTIVITY_MINUTES} minutes."
)
return
self.first_name, self.last_name = first_name, last_name
self.email, self.dob = email, dob
self.inactivity_timeout = timeout_minutes * 60_000
self.vault.save_profile(Profile(first_name, last_name, email, dob))
self.vault.inactivity_timeout_ms = self.inactivity_timeout
self.vault.set_master_password(password)
self.show_link_panel()
def show_link_panel(self):
self.clear_island()
self._add_title("Link your authenticator app")
try:
self.generate_totp_and_recovery()
except CryptoUnavailable as exc:
log.error("Cannot seal the TOTP secret: %s", exc)
self._add_status_label()
self.set_status(
"Secure storage is unavailable on this machine, so setup cannot "
"continue safely. See the log for details."
)
return
self.qr_label = QLabel()
self.qr_label.setPixmap(self.qr_pixmap)
self.qr_label.setAlignment(Qt.AlignCenter)
self.qr_label.setStyleSheet("""
QLabel {
padding: 12px; background-color: #000000;
border-radius: 14px; border: 1px solid #333333;
}
""")
self.island_layout.addWidget(self.qr_label, alignment=Qt.AlignCenter)
self.island_layout.addLayout(
self._copyable_row(
f"Authenticator secret: {self.pending_totp_secret}",
self.pending_totp_secret,
"#b0b0b0", "#333333",
)
)
self.island_layout.addLayout(
self._copyable_row(
f"Recovery code: {self.pending_recovery_code}",
self.pending_recovery_code,
"#ffdd88", "#555533",
)
)
warning = QLabel(
"Store the recovery code somewhere safe. It is the only way back in "
"if you lose both your authenticator and your master password, and "
"it is not shown again."
)
warning.setWordWrap(True)
warning.setAlignment(Qt.AlignCenter)
warning.setStyleSheet("color: #ffdd88; font-size: 11px;")
self.island_layout.addWidget(warning)
finish_btn = QPushButton("Finish Setup")
finish_btn.setFixedHeight(40)
finish_btn.setCursor(Qt.PointingHandCursor)
finish_btn.setStyleSheet(self._primary_button_style())
finish_btn.clicked.connect(self.complete_setup)
self.island_layout.addWidget(finish_btn, alignment=Qt.AlignRight)
def _copyable_row(self, text: str, value: str, fg: str, border: str) -> QHBoxLayout:
row = QHBoxLayout()
row.setSpacing(8)
label = QLabel(text)
label.setAlignment(Qt.AlignLeft)
label.setTextInteractionFlags(Qt.TextSelectableByMouse)
label.setWordWrap(True)
label.setStyleSheet(f"""
QLabel {{
color: {fg}; font-family: 'Consolas', monospace; font-size: 13px;
padding: 10px 14px; background-color: #101010;
border-radius: 10px; border: 1px solid {border};
}}
""")
row.addWidget(label, stretch=1)
copy_btn = QPushButton("Copy")
copy_btn.setFixedHeight(32)
copy_btn.setCursor(Qt.PointingHandCursor)
copy_btn.setStyleSheet(self._primary_button_style())
copy_btn.clicked.connect(lambda: QApplication.clipboard().setText(value))
row.addWidget(copy_btn)
return row
def generate_totp_and_recovery(self):
"""Create and persist a fresh TOTP secret and recovery code."""
secret = pyotp.random_base32()
recovery = generate_recovery_code()
display_name = (self.first_name or "User").strip()
label = f"{display_name} <{self.email}>" if self.email else display_name
totp_uri = pyotp.TOTP(secret).provisioning_uri(
name=label or "SentinelGuardUser", issuer_name="SentinelGuard"
)
# Seal first: if this raises, nothing has been written.
self.vault.totp_secret = secret
self.vault.set_recovery_code(recovery)
self.vault.clear_failures()
self.pending_totp_secret = secret
self.pending_recovery_code = recovery
qr = QRCode(version=1, box_size=8, border=2)
qr.add_data(totp_uri)
qr.make(fit=True)
image = qr.make_image(fill_color="black", back_color="white").resize((220, 220))
buffer = io.BytesIO()
image.save(buffer, format="PNG")
self.qr_pixmap = QPixmap.fromImage(QImage.fromData(buffer.getvalue()))
@Slot()
def complete_setup(self):
self.is_setup = True
# The secret and recovery code are persisted; drop the display copies.
self.pending_totp_secret = ""
self.pending_recovery_code = ""
self.show_auth_panel()
# ------------------------------------------------------------------
# Sign-in panels
# ------------------------------------------------------------------
def show_auth_panel(self):
self.clear_island()
self._add_title()
greeting = QLabel(
f"<h1 style='margin:0'>Hi {self.vault.profile.display_name}</h1>"
"<p style='margin:4px 0 0 0'>Enter your 6-digit 2FA code</p>"
)
greeting.setAlignment(Qt.AlignCenter)
greeting.setStyleSheet("color: #b0b0b0; font-size: 13px;")
self.island_layout.addWidget(greeting)
self.code_input = QLineEdit()
self.code_input.setPlaceholderText("000000")
self.code_input.setMaxLength(6)
self.code_input.setFixedHeight(56)
self.code_input.setEchoMode(QLineEdit.Password)
self.code_input.setAlignment(Qt.AlignCenter)
self.code_input.setValidator(QRegularExpressionValidator(
QRegularExpression(r"^\d{0,6}$"), self.code_input
))
self.code_input.textChanged.connect(self.on_code_changed)
self.code_input.setStyleSheet("""
QLineEdit {
background-color: #000000; border-radius: 14px;
border: 1px solid #333333; padding: 0 24px;
color: #f5f5f5; font-size: 22px; font-family: 'Consolas', monospace;
}
QLineEdit:focus { border: 1px solid #888888; background-color: #050505; }
QLineEdit:disabled { color: #555555; border-color: #222222; }
""")
self.island_layout.addWidget(self.code_input, alignment=Qt.AlignCenter)
self.lockout_label = QLabel("")
self.lockout_label.setAlignment(Qt.AlignCenter)
self.lockout_label.setStyleSheet("color: #ffaa66; font-size: 12px;")
self.lockout_label.hide()
self.island_layout.addWidget(self.lockout_label)
self._add_status_label()
more_options = QLabel("<a href='#' style='color: white;'>More options</a>")
more_options.setAlignment(Qt.AlignCenter)
more_options.setTextFormat(Qt.RichText)
more_options.setTextInteractionFlags(Qt.TextBrowserInteraction)
more_options.setOpenExternalLinks(False)
more_options.linkActivated.connect(self.show_options_panel)
more_options.setStyleSheet("font-size: 12px;")
self.island_layout.addWidget(more_options)
self.refresh_lockout_state()
self.lockout_timer.start()
QTimer.singleShot(50, self._focus_code_input)
def _focus_code_input(self):
if self.code_input is not None:
try:
self.code_input.setFocus()
except RuntimeError:
pass # widget was replaced by a panel switch
def show_options_panel(self):
self.clear_island()
self._add_title("Choose an option")
self.island_layout.addWidget(self._option_card(
"Sign in with Master Password",
"Use the master password set at registration.",
self.show_master_password_panel,
))
face_available, face_reason = facial_recognition_status()
if face_available:
self.island_layout.addWidget(self._option_card(
"Sign in with Face",
"Use facial recognition when enabled in settings.",
self.show_face_login_panel,
))
else:
log.debug("Face sign-in unavailable: %s", face_reason)
self.island_layout.addWidget(self._option_card(
"Recovery",
"Use your recovery code to reset setup.",
self.show_recovery_panel,
))
self.island_layout.addWidget(self._option_card(
"Settings",
"Change inactivity timeout and master password.",
self.show_settings_unlock_panel,
))
back_btn = QPushButton("Back")
back_btn.setFixedHeight(32)
back_btn.setCursor(Qt.PointingHandCursor)
back_btn.setStyleSheet(self._primary_button_style())
back_btn.clicked.connect(self.show_auth_panel)
self.island_layout.addWidget(back_btn, alignment=Qt.AlignRight)
def _option_card(self, title: str, description: str, callback) -> QFrame:
card = QFrame()
card.setFrameShape(QFrame.StyledPanel)
card.setStyleSheet("""
QFrame { background-color: #000000; border-radius: 12px; border: 1px solid #222222; }
QFrame:hover { background-color: #151515; border-color: #666666; }
""")
card.setCursor(QCursor(Qt.PointingHandCursor))
layout = QVBoxLayout(card)
layout.setContentsMargins(14, 12, 14, 12)
layout.setSpacing(4)
title_label = QLabel(title)
title_label.setStyleSheet("font-size: 14px; font-weight: 600; border: none;")
description_label = QLabel(description)
description_label.setWordWrap(True)
description_label.setStyleSheet("font-size: 12px; color: #b0b0b0; border: none;")
layout.addWidget(title_label)
layout.addWidget(description_label)
card.mousePressEvent = lambda event: callback()
return card
def _panel_buttons(self, back_callback, action_text: str, action_callback) -> QHBoxLayout:
row = QHBoxLayout()
row.setSpacing(8)
back_btn = QPushButton("Back")
back_btn.setFixedHeight(34)
back_btn.setCursor(Qt.PointingHandCursor)
back_btn.setStyleSheet(self._primary_button_style())
back_btn.clicked.connect(back_callback)
row.addWidget(back_btn)
action_btn = QPushButton(action_text)
action_btn.setFixedHeight(34)
action_btn.setCursor(Qt.PointingHandCursor)
action_btn.setStyleSheet(self._primary_button_style())
action_btn.clicked.connect(action_callback)
row.addWidget(action_btn)
return row
def show_master_password_panel(self):
self.clear_island()
self._add_title("Sign in with Master Password")
hint = QLabel("Enter the master password you set during registration.")
hint.setWordWrap(True)
hint.setAlignment(Qt.AlignCenter)
hint.setStyleSheet("color: #b0b0b0; font-size: 12px;")
self.island_layout.addWidget(hint)
row = self._password_field("Master Password")
self.mp_login_input = row.field
self.mp_login_input.returnPressed.connect(self.handle_master_password_login)
self.island_layout.addWidget(row)
self.lockout_label = QLabel("")
self.lockout_label.setAlignment(Qt.AlignCenter)
self.lockout_label.setStyleSheet("color: #ffaa66; font-size: 12px;")
self.lockout_label.hide()
self.island_layout.addWidget(self.lockout_label)
self._add_status_label()
self.island_layout.addLayout(self._panel_buttons(
self.show_options_panel, "Sign in", self.handle_master_password_login
))
self.refresh_lockout_state()
self.lockout_timer.start()
def show_recovery_panel(self):
self.clear_island()
self._add_title("Passwordless recovery")
hint = QLabel(
"Enter your recovery code to reset SentinelGuard setup. "
"This erases your profile, master password and authenticator link."
)
hint.setWordWrap(True)
hint.setAlignment(Qt.AlignCenter)
hint.setStyleSheet("color: #b0b0b0; font-size: 12px;")
self.island_layout.addWidget(hint)
self.recovery_input = QLineEdit()
self.recovery_input.setPlaceholderText("XXXXX-XXXXX-XXXXX-XXXXX-XXXXX")
self.recovery_input.setStyleSheet(self._input_style())
self.island_layout.addWidget(self.recovery_input)
self._add_status_label()
self.island_layout.addLayout(self._panel_buttons(
self.show_options_panel, "Reset with Recovery", self.handle_recovery_reset
))
def show_face_login_panel(self):
self.clear_island()
self._add_title("Sign in with Face")
hint = QLabel("Look at the camera to sign in with your face.")
hint.setWordWrap(True)
hint.setAlignment(Qt.AlignCenter)
hint.setStyleSheet("color: #b0b0b0; font-size: 12px;")
self.island_layout.addWidget(hint)
self._add_status_label()
available, reason = facial_recognition_status()
enrolled = self._face_embedding_exists()
if not available:
self.set_status(f"Face sign-in is unavailable. {reason}")
elif not self.facial_enabled:
self.set_status("Face sign-in is disabled. Enable it in Settings first.")
elif not enrolled:
self.set_status("No face is enrolled yet. Capture one in Settings first.")
else:
start_btn = QPushButton("Start Face Login")
start_btn.setFixedHeight(34)
start_btn.setCursor(Qt.PointingHandCursor)
start_btn.setStyleSheet(self._primary_button_style())
start_btn.clicked.connect(self.start_facial_auth)
self.island_layout.addWidget(start_btn, alignment=Qt.AlignCenter)
back_btn = QPushButton("Back")
back_btn.setFixedHeight(34)
back_btn.setCursor(Qt.PointingHandCursor)
back_btn.setStyleSheet(self._primary_button_style())
back_btn.clicked.connect(self.show_options_panel)
self.island_layout.addWidget(back_btn, alignment=Qt.AlignRight)
@staticmethod
def _face_embedding_exists() -> bool:
try:
from Guard.SentinelFacialRec import EMBED_PATH
return Path(EMBED_PATH).exists()
except Exception:
return False
# ------------------------------------------------------------------
# Settings
# ------------------------------------------------------------------
def show_settings_unlock_panel(self):
self.clear_island()
self._add_title("Settings")
hint = QLabel("Enter your master password to access settings.")
hint.setWordWrap(True)
hint.setAlignment(Qt.AlignCenter)
hint.setStyleSheet("color: #b0b0b0; font-size: 12px;")
self.island_layout.addWidget(hint)
row = self._password_field("Master Password")
self.settings_mp_input = row.field
self.settings_mp_input.returnPressed.connect(self.handle_settings_unlock)
self.island_layout.addWidget(row)
self._add_status_label()
self.island_layout.addLayout(self._panel_buttons(
self.show_options_panel, "Continue", self.handle_settings_unlock
))
def handle_settings_unlock(self):
remaining = self.vault.lockout_remaining()
if remaining:
self.set_status(f"Too many failed attempts. Try again in {remaining}s.")
return
entered = self.settings_mp_input.text() or ""
if not entered:
self.set_status("Please enter your master password.")
return
if not self.vault.verify_master_password(entered):
penalty = self.vault.register_failure()
self.set_status(
f"The master password is incorrect. Locked for {penalty}s."
if penalty else "The master password is incorrect."
)
return
self.vault.clear_failures()
self.show_settings_panel()
def show_settings_panel(self):
self.clear_island()
self._add_title("Security settings")
timeout_label = QLabel(
f"Inactivity timeout ({MIN_INACTIVITY_MINUTES}-{MAX_INACTIVITY_MINUTES} minutes)"
)
timeout_label.setStyleSheet("color: #b0b0b0; font-size: 12px;")
self.island_layout.addWidget(timeout_label)
self.settings_inactivity_input = QLineEdit()
self.settings_inactivity_input.setPlaceholderText("Inactivity timeout in minutes")
self.settings_inactivity_input.setStyleSheet(self._input_style())
self.settings_inactivity_input.setValidator(
QIntValidator(MIN_INACTIVITY_MINUTES, MAX_INACTIVITY_MINUTES,
self.settings_inactivity_input)
)
self.settings_inactivity_input.setText(str(self.inactivity_timeout // 60000))
self.island_layout.addWidget(self.settings_inactivity_input)
face_available, face_reason = facial_recognition_status()
if face_available:
face_label = QLabel("Facial recognition sign-in (optional)")
face_label.setStyleSheet("color: #b0b0b0; font-size: 12px; margin-top: 8px;")
self.island_layout.addWidget(face_label)
face_row = QHBoxLayout()
face_row.setSpacing(8)
self.face_toggle_btn = QPushButton("Disable" if self.facial_enabled else "Enable")
self.face_toggle_btn.setFixedHeight(34)
self.face_toggle_btn.setCursor(Qt.PointingHandCursor)
self.face_toggle_btn.setStyleSheet(self._primary_button_style())
self.face_toggle_btn.clicked.connect(self.toggle_facial_enabled)
face_row.addWidget(self.face_toggle_btn)
self.face_enroll_btn = QPushButton("Capture / Re-enroll Face")
self.face_enroll_btn.setFixedHeight(34)
self.face_enroll_btn.setCursor(Qt.PointingHandCursor)
self.face_enroll_btn.setStyleSheet(self._primary_button_style())
self.face_enroll_btn.clicked.connect(self.start_facial_enrollment)
self.face_enroll_btn.setEnabled(self.facial_enabled)
face_row.addWidget(self.face_enroll_btn)
self.island_layout.addLayout(face_row)
password_label = QLabel("Change master password (optional)")
password_label.setStyleSheet("color: #b0b0b0; font-size: 12px; margin-top: 8px;")
self.island_layout.addWidget(password_label)
new_row = self._password_field("New Master Password")
self.settings_new_master_input = new_row.field
self.island_layout.addWidget(new_row)
confirm_row = self._password_field("Confirm New Master Password")
self.settings_confirm_master_input = confirm_row.field
self.island_layout.addWidget(confirm_row)
self._add_status_label()
self.island_layout.addLayout(self._panel_buttons(
self.show_options_panel, "Save settings", self.handle_save_settings
))
def handle_save_settings(self):
timeout_text = (self.settings_inactivity_input.text() or "").strip()
try:
minutes = int(timeout_text)
except ValueError:
minutes = 0
if not MIN_INACTIVITY_MINUTES <= minutes <= MAX_INACTIVITY_MINUTES:
self.set_status(
f"Inactivity timeout must be between {MIN_INACTIVITY_MINUTES} "
f"and {MAX_INACTIVITY_MINUTES} minutes."
)
return
new_password = self.settings_new_master_input.text() or ""
confirm_password = self.settings_confirm_master_input.text() or ""
if new_password or confirm_password:
if new_password != confirm_password:
self.set_status("New master password and confirmation do not match.")
return
if not self.is_master_password_strong(new_password):
self.set_status(
"Master Password needs 8+ characters with an uppercase letter, "
"a number and a symbol."
)
return
self.vault.set_master_password(new_password)
self.inactivity_timeout = minutes * 60_000
self.vault.inactivity_timeout_ms = self.inactivity_timeout
self.set_status("Your settings have been updated.", error=False)
QTimer.singleShot(1200, self.show_options_panel)
def toggle_facial_enabled(self):
self.facial_enabled = not self.facial_enabled
self.vault.facial_enabled = self.facial_enabled
if getattr(self, "face_toggle_btn", None):
self.face_toggle_btn.setText("Disable" if self.facial_enabled else "Enable")
if getattr(self, "face_enroll_btn", None):
self.face_enroll_btn.setEnabled(self.facial_enabled)
# ------------------------------------------------------------------
# Facial recognition
# ------------------------------------------------------------------
def _run_face_worker(self, worker: QObject, on_finished):
"""Move ``worker`` onto a QThread and wire up its teardown."""
if self.face_thread is not None and self.face_thread.isRunning():
self.set_status("A face operation is already running.")
return
self.face_thread = QThread(self)
self.face_worker = worker
worker.moveToThread(self.face_thread)
self.face_thread.started.connect(worker.run)
worker.finished.connect(on_finished)
worker.finished.connect(self.face_thread.quit)
worker.finished.connect(worker.deleteLater)
self.face_thread.finished.connect(self._on_face_thread_finished)
self.face_thread.start()
def _on_face_thread_finished(self):
if self.face_thread is not None:
self.face_thread.deleteLater()
self.face_thread = None
self.face_worker = None
def start_facial_enrollment(self):
if not self.facial_enabled:
self.set_status("Enable facial recognition first, then capture your face.")
return
self.set_status("Capturing face, look at the camera...", error=False)
self._run_face_worker(FaceEnrollWorker(), self.on_facial_enroll_finished)
@Slot(bool, str)
def on_facial_enroll_finished(self, ok: bool, message: str):
if ok:
self.set_status("Face enrollment completed.", error=False)
else:
self.set_status(f"Face enrollment failed. {message}".strip())