-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
4292 lines (3610 loc) · 168 KB
/
Copy pathmain.py
File metadata and controls
4292 lines (3610 loc) · 168 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
# main.py
from __future__ import annotations
import datetime
import json
import platform
import pprint
import sys
import os
import subprocess
import tempfile
import textwrap
import time
def _ensure_tools_on_path():
"""Augment PATH so external tools (Java, GPG) are discoverable.
GUI apps on macOS (launched from Finder/Dock) and packaged Windows
executables often inherit a minimal PATH that excludes directories
where Homebrew, Gpg4win, or JDK installers place their binaries.
"""
system = platform.system()
path = os.environ.get("PATH", "")
path_entries = path.split(os.pathsep)
dirs_to_add = []
def _add(d):
if d not in path_entries and os.path.isdir(d):
dirs_to_add.append(d)
if system == "Darwin":
# Homebrew (Apple Silicon + Intel)
_add("/opt/homebrew/bin")
_add("/usr/local/bin")
# Homebrew-installed OpenJDK (may not be symlinked to bin/)
_add("/opt/homebrew/opt/openjdk/bin")
_add("/usr/local/opt/openjdk/bin")
# JDK installed via .pkg (Oracle, Adoptium, etc.)
try:
java_home = subprocess.run(
["/usr/libexec/java_home"],
capture_output=True, text=True, timeout=5,
)
if java_home.returncode == 0:
_add(os.path.join(java_home.stdout.strip(), "bin"))
except Exception:
pass
elif system == "Windows":
# Gpg4win default install locations
for prog in (
os.environ.get("ProgramFiles", r"C:\Program Files"),
os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
):
_add(os.path.join(prog, "GnuPG", "bin"))
if dirs_to_add:
os.environ["PATH"] = os.pathsep.join(dirs_to_add) + os.pathsep + path
_ensure_tools_on_path()
import gnupg
import markdown
from PyQt5.QtGui import QIcon, QFont, QFontMetrics, QPalette, QColor
from src.utils.colors import Colors
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QLabel,
QPushButton,
QListWidget,
QListWidgetItem,
QComboBox,
QHBoxLayout,
QGridLayout,
QProgressBar,
QMessageBox,
QFrame,
QDialog,
QLineEdit,
QFormLayout,
QTextBrowser,
QInputDialog,
QAction,
QActionGroup,
QMainWindow,
QDialogButtonBox,
QSizePolicy,
QProgressDialog,
)
from PyQt5.QtCore import QTimer, Qt, QSize, QEvent, pyqtSignal
import sip
from cryptography.exceptions import InvalidTag
from dialogs.hex_input_dialog import HexInputDialog
from src.threads import FileHandlerThread, NFCHandlerThread, resource_path, DEFAULT_KEY
from src.threads.plugin_fetch_thread import PluginFetchThread
from secure_storage import (
SecureStorage,
get_app_data_dir,
get_default_storage_path,
get_default_config_path,
migrate_legacy_files,
CACHE_TIMEOUT_OPTIONS,
)
# MVC imports
from src.controllers import CardController
from src.services.storage_service import StorageService
from src.models.card import CardIdentifier, CardType, FIDESMO_KEY_SENTINEL
from src.events.event_bus import (
EventBus,
KeyPromptEvent,
KeyValidatedEvent,
CardStateChangedEvent,
StatusMessageEvent,
ErrorEvent,
)
from src.views.widgets.status_bar import MessageQueue
from src.views.widgets.loading_indicator import LoadingIndicator
from src.views.dialogs import KeyPromptDialog, ComboDialog, ChangeKeyDialog, ManageTagsDialog, LoadingDialog
from src.views.dialogs.plugin_designer import PluginDesignerWizard
class ElidingLabel(QLabel):
"""A QLabel that elides text when it doesn't fit the available width."""
# Vertical padding for cross-platform font rendering compatibility
VERTICAL_PADDING = 4
def __init__(self, text="", parent=None):
super().__init__(text, parent)
self._full_text = text
self.setToolTip(text)
self._update_minimum_height()
def setText(self, text):
self._full_text = text
self.setToolTip(text)
self._update_elided_text()
def resizeEvent(self, event):
super().resizeEvent(event)
self._update_elided_text()
def changeEvent(self, event):
"""Handle font changes to update minimum height and re-elide text."""
super().changeEvent(event)
if event.type() == QEvent.FontChange:
self._update_minimum_height()
self._update_elided_text()
def _update_minimum_height(self):
"""Update minimum height based on current font metrics."""
self.ensurePolished() # Ensure stylesheet font is applied
fm = QFontMetrics(self.font())
min_height = fm.height() + self.VERTICAL_PADDING
self.setMinimumHeight(min_height)
def sizeHint(self):
"""Return preferred size based on font metrics."""
self.ensurePolished() # Ensure stylesheet font is applied
fm = QFontMetrics(self.font())
width = fm.horizontalAdvance(self._full_text) if self._full_text else 100
height = fm.height() + self.VERTICAL_PADDING
return QSize(min(width, 400), height)
def _update_elided_text(self):
fm = QFontMetrics(self.font())
elided = fm.elidedText(self._full_text, Qt.ElideRight, self.width())
super().setText(elided)
class _StorageServiceAdapter:
"""
Adapter to bridge existing SecureStorage to ISecureStorageService interface.
This allows the CardController to work with the existing secure storage
implementation until we fully migrate to StorageService.
"""
def __init__(self, storage_instance, data):
self._instance = storage_instance
self._data = data or {"tags": {}}
def is_initialized(self) -> bool:
return self._data is not None
def load(self):
return self._data
def save(self, data=None):
if data:
self._data = data
if self._instance:
self._instance.save(self._data)
def get_key_for_tag(self, uid: str):
if not self._data:
return None
uid_normalized = uid.upper().replace(" ", "")
tags = self._data.get("tags", {})
tag_data = tags.get(uid_normalized)
if tag_data and "key" in tag_data:
return tag_data["key"]
return None
def set_key_for_tag(self, uid: str, key, name=None):
if not self._data:
self._data = {"tags": {}}
uid_normalized = uid.upper().replace(" ", "")
if "tags" not in self._data:
self._data["tags"] = {}
if uid_normalized not in self._data["tags"]:
self._data["tags"][uid_normalized] = {}
self._data["tags"][uid_normalized]["key"] = key
if name:
self._data["tags"][uid_normalized]["name"] = name
def get_tag_name(self, uid: str):
if not self._data:
return None
uid_normalized = uid.upper().replace(" ", "")
tags = self._data.get("tags", {})
tag_data = tags.get(uid_normalized)
if tag_data and "name" in tag_data:
return tag_data["name"]
return None
def get_key_for_card(self, identifier: CardIdentifier):
"""CPLC-aware key lookup."""
if not self._data:
return None
tags = self._data.get("tags", {})
# Try CPLC hash first
if identifier.cplc_hash:
cplc_normalized = identifier.cplc_hash.upper()
if cplc_normalized in tags:
tag_data = tags[cplc_normalized]
if tag_data and "key" in tag_data:
return tag_data["key"]
# Fall back to UID
if identifier.uid:
uid_normalized = identifier.uid.upper().replace(" ", "")
if uid_normalized in tags:
tag_data = tags[uid_normalized]
if tag_data and "key" in tag_data:
return tag_data["key"]
return None
def get_name_for_card(self, identifier: CardIdentifier):
"""CPLC-aware name lookup."""
if not self._data:
return None
tags = self._data.get("tags", {})
# Try CPLC hash first
if identifier.cplc_hash:
cplc_normalized = identifier.cplc_hash.upper()
if cplc_normalized in tags:
tag_data = tags[cplc_normalized]
if tag_data and "name" in tag_data:
return tag_data["name"]
# Fall back to UID
if identifier.uid:
uid_normalized = identifier.uid.upper().replace(" ", "")
if uid_normalized in tags:
tag_data = tags[uid_normalized]
if tag_data and "name" in tag_data:
return tag_data["name"]
return None
def set_key_for_card(self, identifier: CardIdentifier, key, name=None):
"""CPLC-aware key storage."""
if not self._data:
self._data = {"tags": {}}
if "tags" not in self._data:
self._data["tags"] = {}
# Use CPLC hash as primary key if available
if identifier.cplc_hash:
primary_key = identifier.cplc_hash.upper()
elif identifier.uid:
primary_key = identifier.uid.upper().replace(" ", "")
else:
return
if primary_key not in self._data["tags"]:
self._data["tags"][primary_key] = {}
self._data["tags"][primary_key]["key"] = key
# Store UID as reference if using CPLC
if identifier.cplc_hash and identifier.uid:
self._data["tags"][primary_key]["uid"] = identifier.uid.upper().replace(" ", "")
if name:
self._data["tags"][primary_key]["name"] = name
def upgrade_to_cplc(self, old_uid: str, cplc_hash: str) -> bool:
"""Migrate UID-based entry to CPLC."""
if not self._data:
return False
tags = self._data.get("tags", {})
uid_normalized = old_uid.upper().replace(" ", "")
cplc_normalized = cplc_hash.upper()
if uid_normalized not in tags:
return False
# Get existing entry
old_entry = tags[uid_normalized]
# Create new CPLC-keyed entry
new_entry = dict(old_entry)
new_entry["uid"] = uid_normalized
new_entry["migrated_from_uid"] = True
# Add new and remove old
tags[cplc_normalized] = new_entry
del tags[uid_normalized]
return True
try:
import keyring
except ImportError:
keyring = None
WIDTH_HEIGHT = [800, 600]
APP_TITLE = "GlobalPlatform GUI"
"""
[dict[str, bool]] known_keys:
[bool] uid:str - if the UID uses a default key, true, else false
[bool] cache_latest_release=False
"""
DEFAULT_CONFIG = {
"cache_latest_release": False,
"last_checked": {},
"known_tags": {},
"cache_timeout": "session", # Cache timeout for secure storage unlock
"window": {
"height": WIDTH_HEIGHT[1],
"width": WIDTH_HEIGHT[0],
},
"plugin_command_consent": {}, # plugin_name -> bool (user consent for external commands)
"custom_gp_version": None, # None = built-in, else release tag string
"custom_fdsm_version": None, # None = built-in, else release tag string
}
"""
tags:
{
"name": default is uid,
"key": default is DEFAULT_KEY
}
"""
DEFAULT_DATA = {"tags": {}}
DEFAULT_DATA_FILE = {
"meta": {"version": 1, "encryption": None, "sale": None, "wrapped_key": None},
"data": DEFAULT_DATA,
}
# Use app data directory for secure storage and config
DATA_FILE = get_default_storage_path()
CONFIG_FILE = get_default_config_path()
# Legacy paths for migration
LEGACY_DATA_FILE = "data.enc.json"
LEGACY_CONFIG_FILE = "config.json"
#
# Folder for caching .cap downloads
#
CAP_DOWNLOAD_DIR = os.path.join(tempfile.gettempdir(), "gp_caps")
os.makedirs(CAP_DOWNLOAD_DIR, exist_ok=True)
#
# If you still need to skip certain .cap files, keep them here.
#
unsupported_apps = ["openjavacard-ndef-tiny.cap", "keycard.cap"]
# AID prefix groups - apps sharing a prefix are mutually exclusive
# When an installed AID starts with a group prefix, all available apps
# whose AIDs also start with that prefix will be filtered out
AID_PREFIX_GROUPS = [
# FIDO2 / U2F family (A0000006472F0002 vs A0000006472F000101)
"A0000006472F",
]
def get_plugin_instance(plugin):
"""
Get a plugin instance.
All plugins are now YAML-based and stored as adapter instances.
This function is kept for API compatibility.
"""
return plugin
def load_plugins():
"""
Discover and load YAML plugins.
Scans the /plugins folder for .yaml/.yml files with valid plugin schemas.
Returns a dict plugin_map: { plugin_name: YamlPluginAdapter }.
E.g. { "smartpgp": <YamlPluginAdapter>, "flexsecure-applets": <YamlPluginAdapter>, ... }
Note: All plugins are loaded. Use get_enabled_plugins() to filter by disabled list.
"""
plugin_map = {}
try:
from src.plugins.yaml.loader import YamlPluginLoader
# Use resource_path for PyInstaller compatibility
base_dir = resource_path(".")
loader = YamlPluginLoader(base_dir)
yaml_plugins = loader.discover()
for plugin_name, adapter in yaml_plugins.items():
plugin_map[plugin_name] = adapter
print(f"Loaded plugin: {plugin_name}")
# Report any loading errors
for path, error in loader.get_errors():
print(f"Error loading plugin {path}: {error}")
except ImportError as e:
print(f"Plugin system not available: {e}")
except Exception as e:
print(f"Error loading plugins: {e}")
return plugin_map
# MessageQueue is now imported from src.views.widgets.status_bar
if os.name == "nt":
width_height = [2 * x for x in WIDTH_HEIGHT]
class GPManagerApp(QMainWindow):
# Signals for cross-thread Fidesmo fetch callbacks
_fidesmo_fetch_done = pyqtSignal(object)
_fidesmo_fetch_error = pyqtSignal(str)
def __init__(self):
super().__init__()
self.nfc_thread = None
self.secure_storage = None
self.secure_storage_instance = SecureStorage(
DATA_FILE, service_name="GlobalPlatformGUI"
)
self.secure_storage_dialog = None
self.setWindowTitle(APP_TITLE)
self.setWindowIcon(QIcon(resource_path("favicon.ico")))
self.layout = QVBoxLayout()
self.central_widget = QWidget(self) # Create the central widget
self.central_widget.setLayout(
self.layout
) # Set the layout on the central widget
self.setCentralWidget(self.central_widget)
# Status message queue at the top (animated conveyor)
self.message_queue = MessageQueue(self)
self.layout.addWidget(self.message_queue)
self.message_queue.add_message("Checking for readers...")
# Loading indicator (shown during async operations)
self.loading_indicator = LoadingIndicator(self)
self.layout.addWidget(self.loading_indicator)
# Create the menu bar
self.menu_bar = self.menuBar()
file_menu = self.menu_bar.addMenu("File")
create_plugin_action = QAction("Create Plugin...", self)
create_plugin_action.triggered.connect(self.show_plugin_designer)
file_menu.addAction(create_plugin_action)
file_menu.addSeparator()
settings_action = QAction("Settings", self)
settings_action.triggered.connect(self.show_settings)
quit_action = QAction("Quit", self)
quit_action.triggered.connect(self.quit_app)
file_menu.addAction(settings_action)
file_menu.addSeparator()
file_menu.addAction(quit_action)
tag_menu = self.menu_bar.addMenu("Tags")
set_tag_name_action = QAction("Set Name", self)
set_tag_name_action.triggered.connect(self.set_tag_name)
set_tag_key_action = QAction("Set Key", self)
set_tag_key_action.triggered.connect(self.set_tag_key)
change_tag_key_action = QAction("⚠️ Change Key ⚠️", self)
change_tag_key_action.triggered.connect(self.change_tag_key)
change_uid_mode_action = QAction("Change UID Mode", self)
change_uid_mode_action.triggered.connect(self.change_uid_mode)
manage_tags_action = QAction("Manage Known Tags", self)
manage_tags_action.triggered.connect(self.manage_tags)
# Store action references for enabling/disabling
self._set_tag_name_action = set_tag_name_action
self._set_tag_key_action = set_tag_key_action
self._change_tag_key_action = change_tag_key_action
self._change_uid_mode_action = change_uid_mode_action
self._manage_tags_action = manage_tags_action
tag_menu.addAction(set_tag_name_action)
tag_menu.addAction(set_tag_key_action)
tag_menu.addAction(change_tag_key_action)
tag_menu.addAction(change_uid_mode_action)
tag_menu.addSeparator()
tag_menu.addAction(manage_tags_action)
# Initialize actions as disabled - handle_tag_menu will enable appropriately
set_tag_name_action.setEnabled(False)
set_tag_key_action.setEnabled(False)
change_tag_key_action.setEnabled(False)
change_uid_mode_action.setEnabled(False)
manage_tags_action.setEnabled(False)
self.tag_menu = tag_menu
# Readers menu
self.readers_menu = self.menu_bar.addMenu("Readers")
self._reader_action_group = QActionGroup(self)
self._reader_action_group.setExclusive(True)
self._reader_actions = []
self._no_readers_action = QAction("No readers found", self)
self._no_readers_action.setEnabled(False)
self.readers_menu.addAction(self._no_readers_action)
self.fidesmo_menu = self.menu_bar.addMenu("Fidesmo")
self._browse_store_action = QAction("Browse Fidesmo Store...", self)
self._browse_store_action.triggered.connect(self._browse_fidesmo_store)
self.fidesmo_menu.addAction(self._browse_store_action)
# Plugins menu (populated dynamically from plugin menu_items)
self.plugins_menu = self.menu_bar.addMenu("Plugins")
self._plugin_menu_actions = {} # {plugin_name: {item_id: QAction}}
self._plugin_menu_item_defs = {} # {plugin_name: {item_id: MenuItemDefinition}}
self.plugins_menu.menuAction().setVisible(False) # Hidden until plugins populate it
# Help menu
help_menu = self.menu_bar.addMenu("Help")
about_action = QAction("About", self)
about_action.triggered.connect(self._show_about_dialog)
help_menu.addAction(about_action)
# Check Java availability for FDSM/Fidesmo support
self._java_info = None
self._fdsm_available = False
QTimer.singleShot(0, self._check_java_for_fdsm)
self.config = self.load_config()
self.write_config()
# Apply cache timeout from config to secure storage instance
cache_timeout = self.config.get("cache_timeout", "session")
self.secure_storage_instance.set_cache_timeout(cache_timeout)
# Initialize debug logging from config
from src.plugins.yaml import set_debug_enabled
set_debug_enabled(self.config.get("show_debug", False))
self.resize(self.config["window"]["width"], self.config["window"]["height"])
self.write_config()
self.key = None
self.layout.addWidget(horizontal_rule())
# Track available readers (selection managed via Readers menu)
self._available_readers = []
# Fidesmo mode state
self._fidesmo_mode = False
self._fidesmo_store_apps = []
# Installed / Available lists
self.installed_app_names = []
self.installed_aids = {} # Store raw AIDs for AID-based filtering
self.installed_list = QListWidget()
self.available_list = QListWidget()
grid_layout = QGridLayout()
grid_layout.addWidget(QLabel("Installed Apps"), 0, 0)
grid_layout.addWidget(self.installed_list, 1, 0)
# Available apps header: label on left, inline spinner on right
available_header = QWidget()
available_header_layout = QHBoxLayout(available_header)
available_header_layout.setContentsMargins(0, 0, 0, 0)
self.available_label = QLabel("Available Apps")
available_header_layout.addWidget(self.available_label)
available_header_layout.addStretch()
self._available_spinner = LoadingIndicator(available_header, interval=80, compact=True)
available_header_layout.addWidget(self._available_spinner)
grid_layout.addWidget(available_header, 0, 1)
grid_layout.addWidget(self.available_list, 1, 1)
# No static buttons - contextual buttons appear in details pane
self._action_buttons_enabled = False
self._selected_app_name = None
self._selected_is_installed = False
self.apps_grid_layout = grid_layout
# Connect both lists to show details pane with contextual buttons
self.installed_list.currentItemChanged.connect(
lambda item: self._on_app_selected(item, is_installed=True)
)
self.available_list.currentItemChanged.connect(
lambda item: self._on_app_selected(item, is_installed=False)
)
self.layout.addLayout(self.apps_grid_layout)
# Progress bar for downloads
self.download_bar = QProgressBar()
self.download_bar.hide()
self.layout.addWidget(self.download_bar)
self.central_widget.setLayout(self.layout)
self.nfc_thread = None
# Load secure storage
if os.path.exists(DATA_FILE):
self._load_secure_storage_with_retry()
if self.secure_storage:
# Make sure all our tags in secure storage are in config
updated_config = False
for tag in self.secure_storage["tags"].keys():
if not self.config["known_tags"].get(tag):
self.config["known_tags"][tag] = (
self.secure_storage["tags"][tag]["key"] == DEFAULT_KEY
)
updated_config = True
if updated_config:
self.write_config()
# Enable "Manage Known Tags" action
if hasattr(self, '_manage_tags_action'):
self._manage_tags_action.setEnabled(True)
else:
# You can opt out... But I'm gonna ask every time.
self.prompt_setup()
# Update menu state based on storage status
self._update_storage_menu_state()
#
# Initialize CardController (MVC)
#
self._init_card_controller()
#
# 1) Load all plugins
#
self.plugin_map = load_plugins()
if self.plugin_map:
print("Loaded plugins:", list(self.plugin_map.keys()))
else:
print("No plugins found or repos folder missing.")
#
# 2) Build a combined {cap_name: (plugin_name, download_url)}
# from ALL plugins (needed for management of installed apps)
# Filtering for "available for install" happens in populate_available_list()
#
self.available_apps_info = {} # {cap_name: (plugin_name, url)} - active provider
self.cap_providers = {} # {cap_name: [(plugin_name, url), ...]} - all providers
self.app_descriptions = {}
self.app_display_names = {} # {cap_name: display_name} - friendly names from metadata
self.storage = {}
self.management_only_plugins = {} # {plugin_name: plugin_instance}
self.compatible_aid_plugins = {} # {installed_AID: (plugin_name, plugin_instance)}
disabled_plugins = self._get_disabled_plugins()
for plugin_name, plugin_cls_or_instance in self.plugin_map.items():
# Handle both class (Python plugins) and instance (YAML plugins)
if isinstance(plugin_cls_or_instance, type):
plugin_instance = plugin_cls_or_instance()
else:
plugin_instance = plugin_cls_or_instance
plugin_instance.load_storage()
# Management-only plugins have no CAP to install — skip fetching
if hasattr(plugin_instance, 'is_management_only') and plugin_instance.is_management_only():
self.management_only_plugins[plugin_name] = plugin_instance
continue
# Check if cache needs to be invalidated for YAML plugins with variants
cache_stale = (
not self.config["last_checked"].get(plugin_name, False)
or self.config["last_checked"][plugin_name]["last"]
<= time.time() - 24 * 60 * 60
)
# For YAML plugins with variants, check if cached caps match variants
if not cache_stale and hasattr(plugin_instance, 'get_variants'):
variants = plugin_instance.get_variants()
if variants:
variant_filenames = {v['filename'] for v in variants}
cached_caps = set(self.config["last_checked"].get(plugin_name, {}).get("apps", {}).keys())
# Invalidate cache if it has caps not in variants
if cached_caps and not cached_caps.issubset(variant_filenames):
cache_stale = True
if cache_stale:
caps = plugin_instance.fetch_available_caps()
if len(caps.keys()) > 0:
self.config["last_checked"][plugin_name] = {}
self.config["last_checked"][plugin_name]["apps"] = caps
self.config["last_checked"][plugin_name]["last"] = time.time()
self.config["last_checked"][plugin_name][
"release"
] = plugin_instance.release
self.write_config()
else:
self.message_queue.add_message(
"No apps returned. Check connection and/or url."
)
else:
caps = self.config["last_checked"][plugin_name]["apps"]
if self.config["last_checked"][plugin_name].get("release", False):
plugin_instance.set_release(
self.config["last_checked"][plugin_name]["release"]
)
if len(caps.keys()) == 0: # Probably a failure in fetching.
caps = plugin_instance.fetch_available_caps()
if len(caps.keys()) == 0:
self.message_queue.add_message(
f"Unable to fetch apps for {plugin_name}."
)
return
self.config["last_checked"][plugin_name]["apps"] = caps
self.write_config()
# For YAML plugins using cached data, set cap names for AID matching
if hasattr(plugin_instance, 'set_cached_cap_names'):
plugin_instance.set_cached_cap_names(list(caps.keys()))
for cap_n, url in caps.items():
# Track all providers for this CAP
if cap_n not in self.cap_providers:
self.cap_providers[cap_n] = []
self.cap_providers[cap_n].append((plugin_name, url))
# Check for conflict with existing provider
if cap_n in self.available_apps_info:
existing_plugin, _ = self.available_apps_info[cap_n]
# Only warn if both plugins are enabled
if existing_plugin not in disabled_plugins and plugin_name not in disabled_plugins:
self.message_queue.add_message(
f"Plugin conflict: '{cap_n}' provided by both "
f"'{existing_plugin}' and '{plugin_name}'. "
f"Disable one in Settings > Plugins."
)
# Use the enabled plugin, or prefer YAML plugins (loaded last)
if existing_plugin in disabled_plugins:
self.available_apps_info[cap_n] = (plugin_name, url)
elif plugin_name not in disabled_plugins:
# Both enabled - YAML (loaded last) takes precedence
self.available_apps_info[cap_n] = (plugin_name, url)
else:
self.available_apps_info[cap_n] = (plugin_name, url)
descriptions = plugin_instance.get_descriptions()
for cap_n, description_md in descriptions.items():
self.app_descriptions[cap_n] = description_md
# Get display names from metadata
if hasattr(plugin_instance, 'get_display_names'):
display_names = plugin_instance.get_display_names()
for cap_n, display_name in display_names.items():
self.app_display_names[cap_n] = display_name
# Merge for easy access to storage requirements
self.storage = self.storage | plugin_instance.storage
#
# 3) Populate the "Available Apps" list
#
self.populate_available_list()
# 3b) Build Plugins menu from loaded plugins
self._build_plugins_menu()
#
# 4) Start NFC handler
#
from src.services.tool_version_service import ToolVersionService
custom_gp_path = ToolVersionService.resolve_gp_path(
self.config.get("custom_gp_version")
)
custom_fdsm_path = ToolVersionService.resolve_fdsm_path(
self.config.get("custom_fdsm_version")
)
self.nfc_thread = NFCHandlerThread(
self,
custom_gp_path=custom_gp_path,
custom_fdsm_path=custom_fdsm_path,
)
self.nfc_thread.readers_updated_signal.connect(self.readers_updated)
self.nfc_thread.card_present_signal.connect(self.update_card_presence)
self.nfc_thread.status_update_signal.connect(self.process_nfc_status)
self.nfc_thread.operation_complete_signal.connect(self.on_operation_complete)
self.nfc_thread.installed_apps_updated_signal.connect(
self.on_installed_apps_updated
)
self.nfc_thread.error_signal.connect(self.show_error_dialog)
self.nfc_thread.title_bar_signal.connect(self.update_title_bar)
self.nfc_thread.known_tags_update_signal.connect(self.update_known_tags)
self.nfc_thread.key_config_update_signal.connect(self.update_key_config)
self.nfc_thread.show_key_prompt_signal.connect(self.prompt_for_key)
self.nfc_thread.get_key_signal.connect(self.get_key)
self.nfc_thread.key_setter_signal.connect(self.nfc_thread.key_setter)
self.nfc_thread.cplc_retrieved_signal.connect(self.on_cplc_retrieved)
self.nfc_thread.fidesmo_mode_signal.connect(self._on_fidesmo_mode_changed)
self.nfc_thread.fidesmo_confirm_signal.connect(self._on_fidesmo_confirm)
# Loading dialog for card operations
self._loading_dialog = LoadingDialog(parent=self)
# Track last operation for selection behavior
# "detection", "install", "uninstall", or None
self._last_operation = None
self._pending_install_cap = None # Cap name being installed
# Key prompt cancellation flag - when True, all PCSC operations are halted
# This prevents sending wrong keys to cards which could brick them
self._key_prompt_cancelled = False
self._key_prompt_active = False # True while key entry dialog is open
# Initially disable action buttons
self._update_action_buttons_state(False)
self.current_plugin = None
self.nfc_thread.start()
if self.secure_storage:
self.handle_tag_menu()
def changeEvent(self, event):
"""
This exists because I have messed up twice now, forgetting to
close the app and doing gp/smart card stuff in another window
-- scary!
"""
if event.type() == QEvent.ActivationChange:
if self.isActiveWindow():
self.nfc_thread.resume()
else:
self.nfc_thread.pause()
# No need to sleep - pause is non-blocking
super().changeEvent(event)
def _init_card_controller(self):
"""Initialize the CardController and subscribe to EventBus events."""
# Create a storage service wrapper for the CardController
# Note: We're using the existing secure_storage_instance for now
# In the future, this can use StorageService directly
storage_wrapper = _StorageServiceAdapter(self.secure_storage_instance, self.secure_storage)
# Create the CardController
self.card_controller = CardController(
storage_service=storage_wrapper,
config_service=None, # Will be added when ConfigController is ready
)
# Get the EventBus singleton
self._event_bus = EventBus.instance()
# Subscribe to CardController events
self._event_bus.key_prompt.connect(self._on_key_prompt_event)
self._event_bus.key_validated.connect(self._on_key_validated_event)
self._event_bus.card_state.connect(self._on_card_state_changed_event)
self._event_bus.status_message.connect(self._on_status_message_event)
self._event_bus.error.connect(self._on_error_event)
def _on_key_prompt_event(self, event: KeyPromptEvent):
"""Handle KeyPromptEvent from CardController."""
# Bridge to existing prompt_for_key method
self.prompt_for_key(event.uid, "")
def _on_key_validated_event(self, event: KeyValidatedEvent):
"""Handle KeyValidatedEvent from CardController."""
if event.valid:
self.handle_tag_menu()
# Additional handling can be added here
def _on_card_state_changed_event(self, event: CardStateChangedEvent):
"""Handle CardStateChangedEvent from CardController."""
# Update UI based on new card state
if event.state.is_authenticated:
self._update_action_buttons_state(True)
elif not event.state.is_connected:
self._update_action_buttons_state(False)
def _on_status_message_event(self, event: StatusMessageEvent):
"""Handle StatusMessageEvent from EventBus."""
self.message_queue.add_message(event.message)
def _on_error_event(self, event: ErrorEvent):
"""Handle ErrorEvent from EventBus."""
if not event.recoverable:
self.show_error_dialog(event.message)
else:
self.message_queue.add_message(f"Error: {event.message}")
def handle_details_pane_back(self):
"""Remove the details pane and restore installed apps list."""
# Clear selection state
self._selected_app_name = None
self._selected_is_installed = False
# Clear visual selection in both lists
self.installed_list.clearSelection()
self.available_list.clearSelection()
# Remove the details pane (single spanning widget in col 0)
for row in range(2):
item = self.apps_grid_layout.itemAtPosition(row, 0)
if item:
widget = item.widget()
if widget:
self.apps_grid_layout.removeWidget(widget)
widget.setParent(None)
# Restore the installed apps list
self.apps_grid_layout.addWidget(QLabel("Installed Apps"), 0, 0)
self.apps_grid_layout.addWidget(self.installed_list, 1, 0)
self.installed_list.show()
def _on_app_selected(self, item, is_installed: bool):
"""Handle app selection from either installed or available list."""
if item is None:
return
# Clear selection in the other list to avoid confusion
if is_installed:
self.available_list.clearSelection()
else:
self.installed_list.clearSelection()
# Get cap_name from UserRole data (for available list) or text (for installed)
app_name = item.data(Qt.UserRole) or item.text()
# Strip version suffix if present (e.g., "App.cap (v1.0)" -> "App.cap")
if " (v" in app_name:
app_name = app_name.split(" (v")[0]
self._selected_app_name = app_name
self._selected_is_installed = is_installed
# Show details pane with contextual buttons
self._show_app_details(app_name, is_installed)
def _show_app_details(self, app_name: str, is_installed: bool):
"""Show details pane with app info and contextual action buttons."""
description = self.app_descriptions.get(app_name, "")
display_name = self.app_display_names.get(app_name, app_name)
# Single content widget that spans both grid rows in column 0
content_widget = QWidget()
content_layout = QVBoxLayout(content_widget)
content_layout.setContentsMargins(0, 0, 0, 0)
# content_layout.setSpacing(3)