-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpopup.js
More file actions
1292 lines (1093 loc) · 38.7 KB
/
Copy pathpopup.js
File metadata and controls
1292 lines (1093 loc) · 38.7 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
// H3 Aspis Popup Script
// Dashboard logic and user interactions
console.log('[H3 Aspis Popup] Loading...');
// State
const state = {
currentTab: 'scan',
user: null,
stats: { addressesScanned: 0, threatsDetected: 0, safeFound: 0 },
currentScanResult: null,
pageFilters: new Set(), // Active status filters for Page tab
historyFilters: new Set(), // Active status filters for History tab
historyTimeFilter: 'all' // Time filter for History tab
};
/**
* Initialize popup
*/
async function init() {
console.log('[H3 Aspis Popup] Initializing...');
// Setup tab navigation
setupTabs();
// Setup scan tab
setupScanTab();
// Setup page tab
setupPageTab();
// Setup history tab
setupHistoryTab();
// Setup settings tab
setupSettingsTab();
// Load user info
await loadUserInfo();
// Load stats
await loadStats();
console.log('[H3 Aspis Popup] Initialized');
}
/**
* Setup tab navigation
*/
function setupTabs() {
const tabButtons = document.querySelectorAll('.tab-btn');
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
const targetTab = btn.dataset.tab;
switchTab(targetTab);
});
});
}
/**
* Switch to a specific tab
* @param {string} tabName - Tab identifier
*/
function switchTab(tabName) {
// Update state
state.currentTab = tabName;
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
if (btn.dataset.tab === tabName) {
btn.classList.add('active');
btn.setAttribute('aria-selected', 'true');
} else {
btn.classList.remove('active');
btn.setAttribute('aria-selected', 'false');
}
});
// Update tab panels
document.querySelectorAll('.tab-panel').forEach(panel => {
if (panel.id === `tab-${tabName}`) {
panel.classList.add('active');
} else {
panel.classList.remove('active');
}
});
// Load tab-specific data
if (tabName === 'history') {
loadHistory();
} else if (tabName === 'page') {
loadCurrentPageData();
}
}
/**
* Setup scan tab functionality
*/
function setupScanTab() {
const input = document.getElementById('manual-address-input');
const scanBtn = document.getElementById('manual-scan-btn');
const resultCard = document.getElementById('scan-result');
const loadingState = document.getElementById('scan-loading');
// Scan button handler
scanBtn.addEventListener('click', async () => {
const address = input.value.trim();
if (!address) {
showNotification('Please enter an address', 'warning');
return;
}
if (!isValidAddress(address)) {
showNotification('Invalid address format', 'error');
return;
}
await performManualScan(address);
});
// Enter key handler
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
scanBtn.click();
}
});
}
/**
* Perform manual address scan
* @param {string} address - Address to scan
*/
async function performManualScan(address) {
const resultCard = document.getElementById('scan-result');
const loadingState = document.getElementById('scan-loading');
// Show loading
resultCard.classList.add('hidden');
loadingState.classList.remove('hidden');
try {
// Send message to background
const response = await chrome.runtime.sendMessage({
type: 'MANUAL_SCAN',
address: address
});
if (!response.success) {
throw new Error(response.error || 'Scan failed');
}
// Display result
displayScanResult(response.result, address);
// Update stats
state.stats.addressesScanned++;
if (response.result.status === 'red') {
state.stats.threatsDetected++;
} else if (response.result.status === 'green') {
state.stats.safeFound++;
}
updateStatsDisplay();
} catch (error) {
console.error('[H3 Aspis Popup] Scan error:', error);
showNotification('Scan failed: ' + error.message, 'error');
} finally {
loadingState.classList.add('hidden');
}
}
/**
* Display scan result in UI
* @param {Object} result - Analysis result
* @param {string} address - Scanned address
*/
function displayScanResult(result, address) {
const resultCard = document.getElementById('scan-result');
const badge = document.getElementById('result-badge');
const addressEl = document.getElementById('result-address');
const title = document.getElementById('result-title');
const description = document.getElementById('result-description');
const type = document.getElementById('result-type');
const risk = document.getElementById('result-risk');
const confidence = document.getElementById('result-confidence');
const fullAnalysis = document.getElementById('result-full-analysis');
// Update badge
badge.className = `result-badge ${result.status}`;
badge.textContent = result.status.toUpperCase();
// Update address
addressEl.textContent = shortenAddress(address);
addressEl.title = address;
// Update content
title.textContent = result.summary || 'Analysis Complete';
description.textContent = result.reason || 'No additional information';
// Update metadata
type.textContent = result.type || 'Unknown';
risk.textContent = result.riskLevel || 'Unknown';
confidence.textContent = result.confidence ?
`${(result.confidence * 100).toFixed(0)}%` : 'N/A';
// Update full analysis
fullAnalysis.innerHTML = formatFullAnalysis(result);
// Show card
resultCard.classList.remove('hidden');
// Save to state
state.currentScanResult = { result, address };
}
/**
* Format full analysis details
* @param {Object} result
* @returns {string} HTML string
*/
function formatFullAnalysis(result) {
let html = '';
if (result.flags && result.flags.length > 0) {
html += '<p><strong>Flags:</strong></p><ul>';
result.flags.forEach(flag => {
html += `<li>${flag.replace(/_/g, ' ')}</li>`;
});
html += '</ul>';
}
if (result.sanctionsData) {
html += `<p><strong>Sanctions Information:</strong></p>`;
html += `<p><strong>Source:</strong> ${result.sanctionsData.source}</p>`;
html += `<p><strong>Label:</strong> ${result.sanctionsData.label}</p>`;
if (result.sanctionsData.reason) {
html += `<p><strong>Reason:</strong> ${result.sanctionsData.reason}</p>`;
}
}
if (result.isGated) {
html += `<p style="margin-top: 12px; padding: 12px; background: rgba(255, 215, 0, 0.1); border-radius: 8px;">
⚠️ <strong>Limited Analysis:</strong> Upgrade to H3 Aspis Pro for full security details.
</p>`;
}
if (!html) {
html = '<p>No additional details available.</p>';
}
return html;
}
/**
* Setup page tab functionality
*/
function setupPageTab() {
const rescanBtn = document.getElementById('rescan-page-btn');
const clearBtn = document.getElementById('clear-highlights-btn');
rescanBtn.addEventListener('click', async () => {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.tabs.sendMessage(tab.id, { type: 'RESCAN_PAGE' });
showNotification('Page rescanned', 'success');
setTimeout(() => loadCurrentPageData(), 500);
} catch (error) {
console.error('[H3 Aspis Popup] Rescan error:', error);
showNotification('Failed to rescan page', 'error');
}
});
clearBtn.addEventListener('click', async () => {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.tabs.sendMessage(tab.id, { type: 'CLEAR_HIGHLIGHTS' });
showNotification('Highlights cleared', 'success');
loadCurrentPageData();
} catch (error) {
console.error('[H3 Aspis Popup] Clear error:', error);
showNotification('Failed to clear highlights', 'error');
}
});
// Setup filter pills
setupFilterPills('page');
}
/**
* Load current page analysis data
*/
async function loadCurrentPageData() {
const listEl = document.getElementById('page-addresses-list');
try {
// Get current tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab || !tab.id) {
console.warn('[H3 Aspis Popup] No active tab found');
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">⚠️</span>
<p>No active tab</p>
</div>
`;
return;
}
// Get page scan data from content script
let response;
try {
response = await chrome.tabs.sendMessage(tab.id, {
type: 'GET_PAGE_DATA'
});
} catch (msgError) {
// Content script might not be loaded yet
console.warn('[H3 Aspis Popup] Could not get page data:', msgError.message);
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">🔄</span>
<p>Content script loading...</p>
<p class="empty-hint">Refresh the page if this persists</p>
</div>
`;
return;
}
if (response && response.success && response.addresses && response.addresses.length > 0) {
// Apply status filters
let addresses = applyStatusFilters(response.addresses, state.pageFilters);
if (addresses.length === 0) {
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">🔍</span>
<p>No matches found</p>
<p class="empty-hint">Try different filters</p>
</div>
`;
return;
}
// Group addresses by status
const grouped = {
red: [],
yellow: [],
blue: [],
green: [],
purple: [],
addressbook: [],
analyzing: [],
pending: []
};
addresses.forEach(item => {
let status = item.status || 'analyzing';
// Map addressbook status to purple for grouping
if (status === 'addressbook') {
status = 'purple';
}
if (!grouped[status]) {
console.warn('[H3 Aspis Popup] Unknown status:', status);
grouped.analyzing = grouped.analyzing || [];
grouped.analyzing.push(item);
} else {
grouped[status].push(item);
}
});
let html = '';
// Show analyzing first
if (grouped.analyzing.length > 0) {
html += `<div class="status-group analyzing-group">
<h3>Analyzing (${grouped.analyzing.length})</h3>
${grouped.analyzing.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
// Show threats (red)
if (grouped.red.length > 0) {
html += `<div class="status-group red-group">
<h3>Threats (${grouped.red.length})</h3>
${grouped.red.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
// Show warnings (yellow)
if (grouped.yellow.length > 0) {
html += `<div class="status-group yellow-group">
<h3>Warnings (${grouped.yellow.length})</h3>
${grouped.yellow.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
// Show safe (green)
if (grouped.green.length > 0) {
html += `<div class="status-group green-group">
<h3>Safe (${grouped.green.length})</h3>
${grouped.green.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
// Show info (blue)
if (grouped.blue.length > 0) {
html += `<div class="status-group blue-group">
<h3>Info (${grouped.blue.length})</h3>
${grouped.blue.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
// Show addressbook (purple)
if (grouped.purple.length > 0) {
html += `<div class="status-group purple-group">
<h3>Addressbook (${grouped.purple.length})</h3>
${grouped.purple.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
// Show pending
if (grouped.pending && grouped.pending.length > 0) {
html += `<div class="status-group pending-group">
<h3>Pending (${grouped.pending.length})</h3>
${grouped.pending.map(item => createPageAddressHTML(item)).join('')}
</div>`;
}
listEl.innerHTML = html;
console.log('[H3 Aspis Popup] Displayed', response.addresses.length, 'addresses on page tab');
} else {
console.log('[H3 Aspis Popup] No addresses to display on page tab');
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">🔍</span>
<p>No addresses detected yet</p>
<p class="empty-hint">Visit a Web3 site or DApp</p>
</div>
`;
}
} catch (error) {
console.error('[H3 Aspis Popup] Page data load error:', error);
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">📄</span>
<p>No addresses on this page</p>
<p class="empty-hint">Or content script not injected</p>
</div>
`;
}
}
/**
* Create HTML for page address item
* @param {Object} item
* @returns {string}
*/
function createPageAddressHTML(item) {
const address = item.address;
const status = item.status || 'analyzing';
const summary = item.summary || (status === 'analyzing' ? 'Analysis in progress...' : 'No summary');
const tag = item.tag || null; // Addressbook tag if exists
// Determine display based on status and tag
let displayName = address;
let tagBadge = '';
if (tag) {
// Show tag prominently
displayName = tag;
tagBadge = `<span class="tag-badge">📋 ${tag}</span>`;
} else {
displayName = shortenAddress(address);
}
// Status badge with appropriate styling
const statusDisplay = status === 'addressbook' ? 'SAVED' : status.toUpperCase();
const statusClass = status === 'analyzing' ? 'analyzing pulse' : status;
return `
<div class="address-item ${statusClass}" data-address="${address}">
<div class="result-header">
<span class="result-badge ${statusClass}">${statusDisplay}</span>
<span class="result-address" title="${address}">
${displayName}
</span>
</div>
${tag ? `<div class="tag-info">${tagBadge}</div>` : ''}
<p style="font-size: 12px; color: var(--color-text-secondary); margin-top: 4px;">
${summary}
</p>
</div>
`;
}
/**
* Setup history tab functionality
*/
function setupHistoryTab() {
const filterBtns = document.querySelectorAll('.filter-btn');
filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
// Update active state
filterBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
// Store time filter and reload
const filter = btn.dataset.filter;
state.historyTimeFilter = filter;
loadHistory();
});
});
// Setup filter pills
setupFilterPills('history');
}
/**
* Setup filter pills for Page or History tab
* @param {string} tab - 'page' or 'history'
*/
function setupFilterPills(tab) {
const pillsContainer = document.getElementById(`${tab}-filter-pills`);
const activeFiltersContainer = document.getElementById(`${tab}-active-filters`);
const pills = pillsContainer.querySelectorAll('.pill-btn');
pills.forEach(pill => {
pill.addEventListener('click', () => {
const status = pill.dataset.status;
const filterSet = tab === 'page' ? state.pageFilters : state.historyFilters;
// Toggle filter
if (filterSet.has(status)) {
filterSet.delete(status);
pill.classList.remove('active');
} else {
filterSet.add(status);
pill.classList.add('active');
}
// Update active filters display
updateActiveFilters(tab);
// Reload data with filters
if (tab === 'page') {
loadCurrentPageData();
} else {
loadHistory();
}
});
});
}
/**
* Update active filters display
* @param {string} tab - 'page' or 'history'
*/
function updateActiveFilters(tab) {
const container = document.getElementById(`${tab}-active-filters`);
const filterSet = tab === 'page' ? state.pageFilters : state.historyFilters;
if (filterSet.size === 0) {
container.innerHTML = '';
return;
}
const filterNames = {
red: 'Threats',
yellow: 'Warnings',
green: 'Safe',
blue: 'Info',
purple: 'Addressbook',
analyzing: 'Analyzing'
};
container.innerHTML = Array.from(filterSet).map(status => `
<span class="active-filter-tag status-${status}" data-status="${status}">
${filterNames[status]}
<span class="remove-filter">×</span>
</span>
`).join('');
// Add click handlers to remove filters
container.querySelectorAll('.active-filter-tag').forEach(tag => {
tag.addEventListener('click', () => {
const status = tag.dataset.status;
filterSet.delete(status);
// Update pill button
const pill = document.querySelector(`#${tab}-filter-pills .pill-btn[data-status="${status}"]`);
if (pill) pill.classList.remove('active');
// Update display and reload
updateActiveFilters(tab);
if (tab === 'page') {
loadCurrentPageData();
} else {
loadHistory();
}
});
});
}
/**
* Filter items by status
* @param {Array} items - Items to filter
* @param {Set} filters - Active status filters
* @returns {Array} - Filtered items
*/
function applyStatusFilters(items, filters) {
if (filters.size === 0) return items;
return items.filter(item => {
const status = item.status || item.result?.status || 'blue';
return filters.has(status) || (status === 'addressbook' && filters.has('purple'));
});
}
/**
* Load scan history
*/
async function loadHistory() {
const listEl = document.getElementById('history-list');
try {
const response = await chrome.runtime.sendMessage({
type: 'GET_HISTORY',
filters: { timeRange: state.historyTimeFilter }
});
if (response.success && response.history && response.history.length > 0) {
// Apply status filters
let filteredHistory = applyStatusFilters(response.history, state.historyFilters);
if (filteredHistory.length > 0) {
listEl.innerHTML = filteredHistory.map(item =>
createHistoryItemHTML(item)
).join('');
} else {
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">🔍</span>
<p>No matches found</p>
<p class="empty-hint">Try different filters</p>
</div>
`;
}
} else {
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">📜</span>
<p>No history yet</p>
<p class="empty-hint">Scan some addresses to get started</p>
</div>
`;
}
} catch (error) {
console.error('[H3 Aspis Popup] History load error:', error);
listEl.innerHTML = `
<div class="empty-state">
<span class="empty-icon">⚠️</span>
<p>Failed to load history</p>
</div>
`;
}
}
/**
* Create HTML for history item
* @param {Object} item
* @returns {string}
*/
function createHistoryItemHTML(item) {
const result = item.result || item;
const status = result.status || 'blue';
const summary = result.summary || 'No summary available';
const timestamp = item.timestamp ? new Date(item.timestamp).toLocaleString() : 'Unknown time';
return `
<div class="address-item" data-address="${item.address}" onclick="showHistoryDetails('${item.address}')">
<div class="result-header">
<span class="result-badge ${status}">${status.toUpperCase()}</span>
<span class="result-address" title="${item.address}">${shortenAddress(item.address)}</span>
</div>
<p style="font-size: 12px; color: var(--color-text-secondary); margin-top: 4px;">
${summary}
</p>
<p style="font-size: 11px; color: var(--color-text-tertiary); margin-top: 4px;">
${timestamp}
</p>
</div>
`;
}
/**
* Setup settings tab functionality
*/
function setupSettingsTab() {
// Auth button
const authBtn = document.getElementById('auth-btn');
authBtn.addEventListener('click', handleAuth);
// History toggle
const historyToggle = document.getElementById('history-toggle');
historyToggle.addEventListener('change', async (e) => {
await chrome.storage.local.set({ historyEnabled: e.target.checked });
showNotification('Setting saved', 'success');
});
// Auto-scan toggle
const autoScanToggle = document.getElementById('auto-scan-toggle');
autoScanToggle.addEventListener('change', async (e) => {
await chrome.storage.local.set({ autoScanEnabled: e.target.checked });
showNotification('Setting saved', 'success');
});
// Addressbook functionality
setupAddressbook();
// Audit trail functionality
setupAuditTrail();
// Clear cache
const clearCacheBtn = document.getElementById('clear-cache-btn');
clearCacheBtn.addEventListener('click', async () => {
await chrome.runtime.sendMessage({ type: 'CLEAR_CACHE' });
showNotification('Cache cleared', 'success');
});
// Load current settings
loadSettings();
}
/**
* Handle authentication
*/
async function handleAuth() {
// Authentication removed - extension is fully local
showNotification('Extension runs locally, no login needed', 'info');
}
/**
* Setup addressbook functionality
*/
function setupAddressbook() {
const addBtn = document.getElementById('addressbook-add-btn');
const addressInput = document.getElementById('addressbook-address-input');
const tagInput = document.getElementById('addressbook-tag-input');
const securityToggle = document.getElementById('addressbook-security-toggle');
const syncSelect = document.getElementById('addressbook-sync-select');
const exportBtn = document.getElementById('addressbook-export-btn');
const importBtn = document.getElementById('addressbook-import-btn');
// Add contact
addBtn.addEventListener('click', async () => {
const address = addressInput.value.trim();
const tag = tagInput.value.trim();
if (!address || !tag) {
showNotification('Please enter both address and tag', 'warning');
return;
}
if (!isValidAddress(address)) {
showNotification('Invalid address format', 'error');
return;
}
try {
// Get current addressbook
const { addressbook = {} } = await chrome.storage.local.get(['addressbook']);
// Add new entry
addressbook[address.toLowerCase()] = {
tag: tag,
address: address,
addedAt: Date.now()
};
// Save
await chrome.storage.local.set({ addressbook });
// Clear inputs
addressInput.value = '';
tagInput.value = '';
// Reload list
loadAddressbook();
// Notify content scripts to reload addressbook
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) {
chrome.tabs.sendMessage(tab.id, { type: 'RELOAD_ADDRESSBOOK' }).catch(() => {});
}
showNotification('Contact added successfully', 'success');
} catch (error) {
console.error('[Addressbook] Add error:', error);
showNotification('Failed to add contact', 'error');
}
});
// Security check toggle
securityToggle.addEventListener('change', async (e) => {
await chrome.storage.local.set({ addressbookSecurityCheck: e.target.checked });
showNotification('Setting saved', 'success');
// Notify content scripts
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) {
chrome.tabs.sendMessage(tab.id, { type: 'RELOAD_ADDRESSBOOK' }).catch(() => {});
}
});
// Sync settings (local only)
syncSelect.addEventListener('change', async (e) => {
// Force local storage only
await chrome.storage.local.set({ addressbookSync: 'local' });
showNotification('Using local storage', 'success');
});
// Export
exportBtn.addEventListener('click', async () => {
try {
const { addressbook = {} } = await chrome.storage.local.get(['addressbook']);
const dataStr = JSON.stringify(addressbook, null, 2);
const blob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `h3-aspis-addressbook-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
showNotification('Addressbook exported', 'success');
} catch (error) {
console.error('[Addressbook] Export error:', error);
showNotification('Failed to export', 'error');
}
});
// Import
importBtn.addEventListener('click', () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const text = await file.text();
const importedData = JSON.parse(text);
// Validate data
if (typeof importedData !== 'object') {
throw new Error('Invalid format');
}
// Get current addressbook
const { addressbook = {} } = await chrome.storage.local.get(['addressbook']);
// Merge
const merged = { ...addressbook, ...importedData };
// Save
await chrome.storage.local.set({ addressbook: merged });
// Reload
loadAddressbook();
// Notify content scripts
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) {
chrome.tabs.sendMessage(tab.id, { type: 'RELOAD_ADDRESSBOOK' }).catch(() => {});
}
showNotification('Addressbook imported', 'success');
} catch (error) {
console.error('[Addressbook] Import error:', error);
showNotification('Failed to import', 'error');
}
};
input.click();
});
// Load addressbook
loadAddressbook();
}
/**
* Load and display addressbook
*/
async function loadAddressbook() {
try {
const { addressbook = {}, addressbookSecurityCheck = false } =
await chrome.storage.local.get(['addressbook', 'addressbookSecurityCheck']);
const listEl = document.getElementById('addressbook-list');
const countEl = document.getElementById('addressbook-count');
const securityToggle = document.getElementById('addressbook-security-toggle');
// Update toggle
securityToggle.checked = addressbookSecurityCheck;
const entries = Object.values(addressbook);
countEl.textContent = entries.length;
if (entries.length === 0) {
listEl.innerHTML = '<p style="text-align: center; color: var(--color-text-light); padding: 20px;">No contacts yet</p>';
return;
}
// Sort by most recent
entries.sort((a, b) => (b.addedAt || 0) - (a.addedAt || 0));
listEl.innerHTML = entries.map(entry => `
<div class="addressbook-item" data-address="${entry.address}">
<div class="addressbook-item-info">
<div class="addressbook-tag">${escapeHtml(entry.tag)}</div>
<div class="addressbook-address">${shortenAddress(entry.address)}</div>
</div>
<div class="addressbook-item-actions">
<button class="addressbook-btn-icon addressbook-copy-btn" data-address="${entry.address}" title="Copy Address">
📋
</button>
<button class="addressbook-btn-icon addressbook-delete-btn" data-address="${entry.address}" title="Delete">
🗑️
</button>
</div>
</div>
`).join('');
// Add event listeners to buttons (can't use inline onclick due to CSP)
listEl.querySelectorAll('.addressbook-copy-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const button = e.target.closest('button');
const address = button.dataset.address;
copyToClipboardWithFeedback(address, button);
});
});
listEl.querySelectorAll('.addressbook-delete-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const address = e.target.closest('button').dataset.address;
const entry = Object.values(addressbook).find(e => e.address === address);
showDeleteConfirmation(address, entry?.tag || 'this contact');
});
});
} catch (error) {
console.error('[Addressbook] Load error:', error);
}
}
/**
* Show branded delete confirmation modal
* @param {string} address
* @param {string} tag
*/
function showDeleteConfirmation(address, tag) {
// Create modal overlay
const overlay = document.createElement('div');
overlay.className = 'modal-overlay';
overlay.innerHTML = `
<div class="modal">
<div class="modal-header">
<span class="modal-icon">🗑️</span>
<h3 class="modal-title">Remove Contact?</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to remove <strong>${escapeHtml(tag)}</strong> from your addressbook?</p>
<p style="font-size: 12px; margin-top: 8px; color: var(--color-text-light);">
${shortenAddress(address)}
</p>
</div>
<div class="modal-actions">
<button class="modal-btn modal-btn-cancel">Cancel</button>
<button class="modal-btn modal-btn-confirm">Remove</button>
</div>
</div>
`;