-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1925 lines (1682 loc) · 61.5 KB
/
main.js
File metadata and controls
1925 lines (1682 loc) · 61.5 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
/**
* @fileoverview Main process for Secure Vault - handles app lifecycle, security, and auto-updates
*/
const { app, BrowserWindow, ipcMain, dialog, shell, Menu, desktopCapturer, globalShortcut, Notification, clipboard, Tray, nativeImage } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const Store = require('electron-store');
const { ImportExportManager } = require('./import-export');
const i18n = require('./i18n');
/**
* @type {BrowserWindow|null} Main application window
*/
let mainWindow;
let tray;
/**
* @type {boolean} Whether an update has been downloaded and is ready to install
*/
let updateDownloaded = false;
/**
* @type {boolean} Whether the vault is currently locked
*/
let isLocked = true;
/**
* @type {NodeJS.Timeout|null} Timeout for periodic update checks
*/
let updateCheckTimeout = null;
/**
* @type {Store|null} Encrypted store for vault data
*/
let vaultStore = null;
/**
* @type {NodeJS.Timeout|null} Timeout for automatic vault locking
*/
let sessionTimeout = null;
/**
* @type {number} Number of consecutive failed password attempts
*/
let failedAttempts = 0;
/**
* @type {number} Timestamp of last failed password attempt
*/
let lastFailedAttempt = 0;
/**
* @type {boolean} Whether auto-update is currently checking for updates
*/
let isCheckingForUpdates = false;
/**
* @type {ImportExportManager} Import/Export manager instance
*/
const importExportManager = new ImportExportManager();
/**
* Configuration store for application settings
*/
const store = new Store({
name: 'secure-vault-config',
encryptionKey: process.env.NODE_ENV === 'development' ? 'dev-key' : undefined
});
/**
* Derives encryption key from master password using PBKDF2
* @param {string} password - The master password
* @returns {string} Derived encryption key as hex string
*/
function deriveEncryptionKey(password) {
let salt = store.get('encryptionSalt');
if (!salt) {
salt = crypto.randomBytes(32).toString('hex');
store.set('encryptionSalt', salt);
}
return crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha512').toString('hex');
}
/**
* Initializes the encrypted vault store with derived key
* @param {string} password - The master password
*/
function initializeVaultStore(password) {
try {
const encryptionKey = deriveEncryptionKey(password);
vaultStore = new Store({
name: 'secure-vault-data',
encryptionKey: encryptionKey
});
/* Test store access to ensure it's not corrupted */
vaultStore.get('passwordEntries', []);
} catch (error) {
/* Check if this is a one-time corruption recovery */
const recoveryFlag = store.get('vaultRecoveryPerformed', false);
if (!recoveryFlag) {
console.log('First-time vault corruption detected. Performing recovery...');
try {
/* Mark recovery as performed to prevent infinite loops */
store.set('vaultRecoveryPerformed', true);
/* Generate new salt for corrupted vault recovery */
const newSalt = crypto.randomBytes(32).toString('hex');
store.set('encryptionSalt', newSalt);
console.log('Generated new encryption salt for corrupted vault recovery');
/* Create new encryption key with fresh salt */
const freshKey = crypto.pbkdf2Sync(password, newSalt, 100000, 32, 'sha512').toString('hex');
/* Use the original vault name but with fresh encryption */
vaultStore = new Store({
name: 'secure-vault-data',
encryptionKey: freshKey,
clearInvalidConfig: true
});
/* Initialize with empty data structure */
vaultStore.set('passwordEntries', []);
vaultStore.set('totpEntries', []);
vaultStore.set('categories', []);
console.log('Fresh vault store created successfully with new encryption');
console.log('WARNING: Previous vault data was corrupted and could not be recovered.');
} catch (secondError) {
console.error('Failed to create fresh vault store:', secondError);
throw new Error(i18n.t('errors.unable_initialize_vault'));
}
} else {
/* Recovery already performed, but still failing - this indicates a persistent issue */
console.error('Vault store still corrupted after recovery attempt.');
throw new Error(i18n.t('errors.vault_corruption_persists'));
}
}
}
/**
* Ensures vault store is ready for operations
* @returns {Object|null} Error object if vault is locked, null otherwise
*/
function ensureVaultStoreReady() {
if (isLocked || !vaultStore) {
return { success: false, error: i18n.t('errors.vault_locked') };
}
resetSessionTimeout();
return null;
}
/**
* Resets the automatic session timeout
*/
function resetSessionTimeout() {
if (sessionTimeout) {
clearTimeout(sessionTimeout);
}
sessionTimeout = setTimeout(function() {
if (!isLocked) {
lockVaultInternal();
}
}, 30 * 60 * 1000);
}
/**
* Locks the vault and clears sensitive data
*/
function lockVaultInternal() {
isLocked = true;
vaultStore = null;
if (sessionTimeout) {
clearTimeout(sessionTimeout);
sessionTimeout = null;
}
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('vault-auto-locked');
}
}
/**
* Creates the main application window
*/
function createWindow() {
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 1000,
minHeight: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
},
icon: getIconPath(),
show: false,
frame: false,
titleBarStyle: 'hidden',
backgroundColor: '#0a0e1a',
title: i18n.t('app.title')
});
mainWindow.setMenu(null);
mainWindow.loadFile('index.html');
mainWindow.once('ready-to-show', function() {
mainWindow.show();
if (process.argv.includes('--dev') || process.env.NODE_ENV === 'development') {
mainWindow.webContents.openDevTools();
}
setTimeout(function() {
if (!process.argv.includes('--dev')) {
checkForUpdatesOnStartup();
schedulePeriodicUpdates();
}
}, 2000);
});
mainWindow.on('close', function(event) {
const settings = store.get('appSettings', {});
if (settings.closeToTray !== false && !app.isQuiting) {
event.preventDefault();
mainWindow.hide();
}
});
mainWindow.on('closed', function() {
mainWindow = null;
if (updateCheckTimeout) {
clearTimeout(updateCheckTimeout);
}
if (sessionTimeout) {
clearTimeout(sessionTimeout);
}
globalShortcut.unregisterAll();
});
mainWindow.webContents.setWindowOpenHandler(function(details) {
shell.openExternal(details.url);
return { action: 'deny' };
});
createTray();
}
/**
* Creates the system tray
*/
function createTray() {
const trayIcon = nativeImage.createFromPath(getIconPath());
tray = new Tray(trayIcon.resize({ width: 16, height: 16 }));
const contextMenu = Menu.buildFromTemplate([
{
label: i18n.t('tray.show_secure_vault'),
click: function() {
mainWindow.show();
mainWindow.focus();
}
},
{
label: i18n.t('tray.lock_vault'),
click: function() {
mainWindow.webContents.send('lock-vault');
}
},
{ type: 'separator' },
{
label: i18n.t('tray.quit'),
click: function() {
app.isQuiting = true;
app.quit();
}
}
]);
tray.setToolTip(i18n.t('tray.tooltip'));
tray.setContextMenu(contextMenu);
tray.on('double-click', function() {
mainWindow.show();
mainWindow.focus();
});
}
/**
* Gets the appropriate icon path for the current platform
* @returns {string} Path to the icon file
*/
function getIconPath() {
const iconPaths = {
win32: 'assets/icon.ico',
darwin: 'assets/icon.icns',
linux: 'assets/icon.png'
};
const iconPath = iconPaths[process.platform] || iconPaths.linux;
return path.join(__dirname, iconPath);
}
/**
* Sets up auto-updater event handlers and configuration
*/
function setupAutoUpdater() {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.allowDowngrade = false;
autoUpdater.allowPrerelease = false;
autoUpdater.on('checking-for-update', function() {
console.log('Checking for update...');
isCheckingForUpdates = true;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update-checking');
}
});
autoUpdater.on('update-available', function(info) {
console.log('Update available:', info);
isCheckingForUpdates = false;
store.set('lastUpdateInfo', {
version: info.version,
releaseDate: info.releaseDate,
downloadUrl: info.files?.[0]?.url
});
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update-available', info);
}
});
autoUpdater.on('update-not-available', function(info) {
console.log('Update not available:', info);
isCheckingForUpdates = false;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update-not-available', info);
}
});
autoUpdater.on('error', function(err) {
console.error('Update error:', err);
isCheckingForUpdates = false;
store.set('lastUpdateError', {
message: err.message,
timestamp: new Date().toISOString()
});
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update-error', err);
}
});
autoUpdater.on('download-progress', function(progressObj) {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update-download-progress', progressObj);
}
});
autoUpdater.on('update-downloaded', function(info) {
console.log('Update downloaded:', info);
updateDownloaded = true;
store.set('updateDownloaded', true);
store.set('updateReadyToInstall', {
version: info.version,
downloadedAt: new Date().toISOString()
});
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('update-downloaded', info);
}
});
}
/**
* Checks for updates on application startup
*/
async function checkForUpdatesOnStartup() {
try {
const autoCheckEnabled = store.get('autoCheckUpdates', true);
if (!autoCheckEnabled || isCheckingForUpdates) {
return;
}
const lastCheck = store.get('lastUpdateCheck', 0);
const now = Date.now();
const oneDayMs = 24 * 60 * 60 * 1000;
if (now - lastCheck < oneDayMs) {
return;
}
store.set('lastUpdateCheck', now);
if (process.platform !== 'linux' && app.isPackaged) {
console.log('Checking for updates on startup...');
await autoUpdater.checkForUpdates();
}
} catch (error) {
console.error('Error checking for updates on startup:', error);
store.set('lastUpdateError', {
message: error.message,
timestamp: new Date().toISOString(),
context: 'startup'
});
}
}
/**
* Schedules periodic update checks
*/
function schedulePeriodicUpdates() {
const checkInterval = 6 * 60 * 60 * 1000; // 6 hours
updateCheckTimeout = setInterval(async function() {
try {
const autoCheckEnabled = store.get('autoCheckUpdates', true);
if (!autoCheckEnabled || isCheckingForUpdates || !app.isPackaged) {
return;
}
if (process.platform !== 'linux') {
console.log('Periodic update check...');
await autoUpdater.checkForUpdates();
}
} catch (error) {
console.error('Error during periodic update check:', error);
}
}, checkInterval);
}
/**
* Forces an immediate update check
* @returns {Promise<Object>} Result of update check
*/
async function forceUpdateCheck() {
try {
if (isCheckingForUpdates) {
return { success: false, error: i18n.t('errors.update_in_progress') };
}
if (process.platform === 'linux') {
return { success: false, error: i18n.t('errors.updates_not_supported_linux') };
}
if (!app.isPackaged) {
return { success: false, error: i18n.t('errors.updates_packaged_only') };
}
store.set('lastUpdateCheck', Date.now());
const result = await autoUpdater.checkForUpdates();
return { success: true, updateInfo: result };
} catch (error) {
console.error('Error forcing update check:', error);
return { success: false, error: error.message };
}
}
/**
* IPC handler to get available desktop sources for screen capture
*/
ipcMain.handle('get-desktop-sources', async function() {
try {
const sources = await desktopCapturer.getSources({
types: ['screen', 'window'],
thumbnailSize: { width: 1920, height: 1080 }
});
return {
success: true,
sources: sources.map(function(source) {
return {
id: source.id,
name: source.name,
thumbnail: source.thumbnail.toDataURL()
};
})
};
} catch (error) {
console.error('Error getting desktop sources:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler to capture screen from specific source
* @param {Event} event - IPC event
* @param {string} sourceId - ID of the desktop source to capture
*/
ipcMain.handle('capture-screen', async function(event, sourceId) {
try {
const sources = await desktopCapturer.getSources({
types: ['screen', 'window'],
thumbnailSize: { width: 1920, height: 1080 }
});
const source = sources.find(function(s) {
return s.id === sourceId;
});
if (!source) {
return { success: false, error: i18n.t('errors.source_not_found') };
}
return {
success: true,
dataUrl: source.thumbnail.toDataURL(),
width: source.thumbnail.getSize().width,
height: source.thumbnail.getSize().height
};
} catch (error) {
console.error('Error capturing screen:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler to check for application updates
*/
ipcMain.handle('check-for-updates', async function() {
try {
const result = await forceUpdateCheck();
return result;
} catch (error) {
console.error('Error checking for updates:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler to download available update
*/
ipcMain.handle('download-update', async function() {
try {
if (isCheckingForUpdates) {
return { success: false, error: i18n.t('errors.update_in_progress') };
}
await autoUpdater.downloadUpdate();
return { success: true };
} catch (error) {
console.error('Error downloading update:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler to install downloaded update and restart app
*/
ipcMain.handle('install-update', async function() {
try {
if (updateDownloaded) {
store.set('updateDownloaded', false);
autoUpdater.quitAndInstall();
return { success: true };
} else {
return { success: false, error: i18n.t('errors.no_update_downloaded') };
}
} catch (error) {
console.error('Error installing update:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler to get update information and status
*/
ipcMain.handle('get-update-info', async function() {
try {
const lastUpdateInfo = store.get('lastUpdateInfo', null);
const lastUpdateError = store.get('lastUpdateError', null);
const updateReadyToInstall = store.get('updateReadyToInstall', null);
return {
success: true,
version: app.getVersion(),
updateDownloaded: updateDownloaded,
platform: process.platform,
autoCheckEnabled: store.get('autoCheckUpdates', true),
lastCheck: store.get('lastUpdateCheck', 0),
isCheckingForUpdates: isCheckingForUpdates,
lastUpdateInfo: lastUpdateInfo,
lastUpdateError: lastUpdateError,
updateReadyToInstall: updateReadyToInstall,
supportsUpdates: process.platform !== 'linux' && app.isPackaged
};
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* IPC handler to enable/disable automatic update checks
* @param {Event} event - IPC event
* @param {boolean} enabled - Whether to enable auto-update checks
*/
ipcMain.handle('set-auto-check-updates', async function(event, enabled) {
try {
store.set('autoCheckUpdates', enabled);
if (!enabled && updateCheckTimeout) {
clearInterval(updateCheckTimeout);
updateCheckTimeout = null;
} else if (enabled && !updateCheckTimeout) {
schedulePeriodicUpdates();
}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* IPC handler to clear update cache and history
*/
ipcMain.handle('clear-update-cache', async function() {
try {
store.delete('lastUpdateInfo');
store.delete('lastUpdateError');
store.delete('updateReadyToInstall');
store.delete('updateDownloaded');
updateDownloaded = false;
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* IPC handler to minimize the main window
*/
ipcMain.handle('window-minimize', function() {
if (mainWindow && !mainWindow.isDestroyed()) {
const settings = store.get('appSettings', {});
if (settings.closeToTray !== false) {
mainWindow.hide();
} else {
mainWindow.minimize();
}
}
return { success: true };
});
/**
* IPC handler to maximize/unmaximize the main window
*/
ipcMain.handle('window-maximize', function() {
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow.maximize();
}
}
return { success: true };
});
/**
* IPC handler to close the main window
*/
ipcMain.handle('window-close', function() {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.close();
}
return { success: true };
});
/**
* IPC handler to check if window is maximized
*/
ipcMain.handle('window-is-maximized', function() {
return mainWindow && !mainWindow.isDestroyed() ? mainWindow.isMaximized() : false;
});
/**
* IPC handler to setup initial master password
* @param {Event} event - IPC event
* @param {string} password - Master password to setup
*/
ipcMain.handle('setup-master-password', async function(event, password) {
try {
const saltRounds = 12;
const hash = await bcrypt.hash(password, saltRounds);
store.set('masterPasswordHash', hash);
store.set('isSetup', true);
initializeVaultStore(password);
isLocked = false;
resetSessionTimeout();
return { success: true };
} catch (error) {
console.error('Error setting up master password:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler to verify master password with rate limiting
* @param {Event} event - IPC event
* @param {string} password - Master password to verify
*/
ipcMain.handle('verify-master-password', async function(event, password) {
try {
const now = Date.now();
const timeSinceLastAttempt = now - lastFailedAttempt;
if (timeSinceLastAttempt > 15 * 60 * 1000) {
failedAttempts = 0;
}
if (failedAttempts > 0) {
const delay = Math.min(30000, 1000 * Math.pow(2, failedAttempts - 1));
if (timeSinceLastAttempt < delay) {
const remaining = Math.ceil((delay - timeSinceLastAttempt) / 1000);
return { success: false, error: `Too many failed attempts. Try again in ${remaining} seconds.` };
}
}
const storedHash = store.get('masterPasswordHash');
if (!storedHash) {
return { success: false, error: i18n.t('errors.master_password_not_set') };
}
const isValid = await bcrypt.compare(password, storedHash);
if (isValid) {
failedAttempts = 0;
initializeVaultStore(password);
isLocked = false;
resetSessionTimeout();
return { success: true };
} else {
failedAttempts++;
lastFailedAttempt = now;
return { success: false, error: i18n.t('errors.invalid_password') };
}
} catch (error) {
console.error('Error verifying master password:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('change-master-password', async function(event, currentPassword, newPassword) {
try {
const storedHash = store.get('masterPasswordHash');
if (!storedHash) {
return { success: false, error: i18n.t('errors.master_password_not_set') };
}
const isValid = await bcrypt.compare(currentPassword, storedHash);
if (!isValid) {
return { success: false, error: i18n.t('errors.current_password_incorrect') };
}
const saltRounds = 12;
const newHash = await bcrypt.hash(newPassword, saltRounds);
store.set('masterPasswordHash', newHash);
return { success: true };
} catch (error) {
console.error('Error changing master password:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('lock-vault', async function() {
try {
lockVaultInternal();
return { success: true };
} catch (error) {
console.error('Error locking vault:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('is-vault-setup', async function() {
try {
const isSetup = store.get('isSetup', false);
return { success: true, isSetup: isSetup, isLocked: isLocked };
} catch (error) {
console.error('Error checking vault setup:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('save-password-entry', async function(event, entry) {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const entries = vaultStore.get('passwordEntries', []);
if (entry.id) {
const index = entries.findIndex(function(e) {
return e.id === entry.id;
});
if (index !== -1) {
entries[index] = Object.assign({}, entry, { updatedAt: new Date().toISOString() });
}
} else {
entry.id = Date.now().toString();
entry.createdAt = new Date().toISOString();
entry.updatedAt = new Date().toISOString();
entries.push(entry);
}
vaultStore.set('passwordEntries', entries);
return { success: true, entry: entry };
} catch (error) {
console.error('Error saving password entry:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('get-password-entries', async function() {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const entries = vaultStore.get('passwordEntries', []);
return { success: true, entries: entries };
} catch (error) {
console.error('Error getting password entries:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('delete-password-entry', async function(event, entryId) {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const entries = vaultStore.get('passwordEntries', []);
const filteredEntries = entries.filter(function(e) {
return e.id !== entryId;
});
vaultStore.set('passwordEntries', filteredEntries);
return { success: true };
} catch (error) {
console.error('Error deleting password entry:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('save-totp-entry', async function(event, entry) {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const entries = vaultStore.get('totpEntries', []);
if (entry.id) {
const index = entries.findIndex(function(e) {
return e.id === entry.id;
});
if (index !== -1) {
entries[index] = Object.assign({}, entry, { updatedAt: new Date().toISOString() });
}
} else {
entry.id = Date.now().toString();
entry.createdAt = new Date().toISOString();
entry.updatedAt = new Date().toISOString();
entries.push(entry);
}
vaultStore.set('totpEntries', entries);
return { success: true, entry: entry };
} catch (error) {
console.error('Error saving TOTP entry:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('get-totp-entries', async function() {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const entries = vaultStore.get('totpEntries', []);
return { success: true, entries: entries };
} catch (error) {
console.error('Error getting TOTP entries:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('delete-totp-entry', async function(event, entryId) {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const entries = vaultStore.get('totpEntries', []);
const filteredEntries = entries.filter(function(e) {
return e.id !== entryId;
});
vaultStore.set('totpEntries', filteredEntries);
return { success: true };
} catch (error) {
console.error('Error deleting TOTP entry:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler for enhanced vault export with multiple format support
* @param {Event} event - IPC event
* @param {string} format - Export format (csv, json, securevault, etc.)
* @param {string} password - Password for encrypted formats
*/
ipcMain.handle('export-vault', async function(event, format = 'json', password = null) {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const formatInfo = importExportManager.supportedFormats[format] || i18n.t('formats.unknown_format');
const extensions = {
'csv': ['csv'],
'json': ['json'],
'securevault': ['svault'],
'lastpass': ['csv'],
'bitwarden': ['json']
};
const result = await dialog.showSaveDialog(mainWindow, {
title: `Export Vault Data - ${formatInfo}`,
defaultPath: `secure-vault-backup-${new Date().toISOString().split('T')[0]}.${extensions[format]?.[0] || 'json'}`,
filters: [
{ name: formatInfo, extensions: extensions[format] || ['json'] },
{ name: i18n.t('file_types.all_files'), extensions: ['*'] }
]
});
if (result.canceled) {
return { success: false, canceled: true };
}
const passwordEntries = vaultStore.get('passwordEntries', []);
const totpEntries = vaultStore.get('totpEntries', []);
const allEntries = [...passwordEntries, ...totpEntries];
await importExportManager.exportData(allEntries, format, result.filePath, password);
return { success: true, path: result.filePath, format: format, count: allEntries.length };
} catch (error) {
console.error('Error exporting vault:', error);
return { success: false, error: error.message };
}
});
/**
* IPC handler for enhanced vault import with multiple format support
* @param {Event} event - IPC event
* @param {string} password - Password for encrypted formats
*/
ipcMain.handle('import-vault', async function(event, password = null) {
try {
const lockCheck = ensureVaultStoreReady();
if (lockCheck) return lockCheck;
const result = await dialog.showOpenDialog(mainWindow, {
title: i18n.t('dialogs.import_vault_title'),
filters: [
{ name: i18n.t('file_types.csv_files'), extensions: ['csv'] },
{ name: i18n.t('file_types.json_files'), extensions: ['json'] },
{ name: i18n.t('file_types.secure_vault_files'), extensions: ['svault'] },
{ name: 'WinAuth Files', extensions: ['txt', 'wa.txt'] },
{ name: i18n.t('file_types.all_files'), extensions: ['*'] }
],
properties: ['openFile']
});
if (result.canceled) {
return { success: false, canceled: true };
}
const importResult = await importExportManager.importData(result.filePaths[0], password);
let passwordCount = 0;
let totpCount = 0;
if (importResult.success && importResult.entries && importResult.entries.length > 0) {
/* Separate password and TOTP entries */
const passwordEntries = [];
const totpEntries = [];
for (const entry of importResult.entries) {
if (entry.type === 'totp' || entry.secret || entry.totp) {
/* Convert to TOTP entry format */
totpEntries.push({
id: entry.id,
name: entry.name,
secret: entry.secret || entry.totp,
issuer: entry.issuer || entry.category || i18n.t('import.default_issuer'),
digits: entry.digits || 6,
period: entry.period || 30,
createdAt: entry.created || new Date().toISOString(),