-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
678 lines (577 loc) · 20.8 KB
/
main.js
File metadata and controls
678 lines (577 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
const { app, BrowserWindow, ipcMain, globalShortcut, dialog, safeStorage } = require('electron');
const path = require('path');
const { exec, spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
let mainWindow;
// Helper: Get Active Window Title (Windows only for now)
const getActiveWindowTitle = () => {
return new Promise((resolve, reject) => {
const psScript = `
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
}
"@
$hwnd = [Win32]::GetForegroundWindow()
$sb = [System.Text.StringBuilder]::new(256)
[void][Win32]::GetWindowText($hwnd, $sb, 256)
$sb.ToString()
`;
// Using powershell to execute
const command = `powershell -NoProfile -ExecutionPolicy Bypass -Command "${psScript.replace(/"/g, '\\"')}"`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error('Title Error:', error);
resolve('');
return;
}
resolve(stdout.trim());
});
});
};
// Helper: Send Keys via VBScript (More reliable for mixed characters than raw PS SendKeys)
// Helper: Send Keys via VBScript (Secure Stdin Pipe - No File)
const sendKeys = (username, password) => {
const escape = (str) => {
if (!str) return '';
return str.replace(/([+^%~(){}[\]])/g, "{$1}");
};
const userEsc = escape(username);
const passEsc = escape(password);
const vbsContent = `
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Sleep 500
WshShell.SendKeys "${userEsc}"
WScript.Sleep 300
WshShell.SendKeys "{TAB}"
WScript.Sleep 300
WshShell.SendKeys "${passEsc}"
WScript.Sleep 300
WshShell.SendKeys "{ENTER}"
`;
// Execute VBScript via Stdin (Fileless)
const proc = spawn('cscript', ['//Nologo', '//E:vbs', '-']);
proc.stdin.write(vbsContent);
proc.stdin.end();
proc.on('error', (err) => console.error("AutoType Error:", err));
};
// Biometric Helpers (Windows Hello via PowerShell)
const checkBiometryAvailability = () => {
return new Promise((resolve) => {
const psScript = `
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asb = [System.Runtime.InteropServices.WindowsRuntime.AsyncInfo]
[Windows.Security.Credentials.UI.UserConsentVerifier, Windows.Security.Credentials.UI, ContentType=WindowsRuntime] | Out-Null
$res = [Windows.Security.Credentials.UI.UserConsentVerifier]::CheckAvailabilityAsync().GetResults()
$res -eq "Available"
`;
const command = `powershell -NoProfile -ExecutionPolicy Bypass -Command "${psScript.replace(/"/g, '\\"')}"`;
exec(command, (error, stdout) => {
resolve(stdout.trim().toLowerCase() === 'true');
});
});
};
const promptBiometry = (reason) => {
return new Promise((resolve) => {
const psScript = `
Add-Type -AssemblyName System.Runtime.WindowsRuntime
[Windows.Security.Credentials.UI.UserConsentVerifier, Windows.Security.Credentials.UI, ContentType=WindowsRuntime] | Out-Null
$operation = [Windows.Security.Credentials.UI.UserConsentVerifier]::RequestVerificationAsync("${reason}")
$result = $operation.GetResults()
$result -eq "Verified"
`;
const command = `powershell -NoProfile -ExecutionPolicy Bypass -Command "${psScript.replace(/"/g, '\\"')}"`;
exec(command, (error, stdout) => {
resolve(stdout.trim().toLowerCase() === 'true');
});
});
};
function createWindow() {
// Geliştirme ortamında (isPackaged false ise) public klasöründen,
// üretimde (build sonrası) build klasöründen ikonu al.
const isDev = !app.isPackaged;
const iconPath = isDev
? path.join(__dirname, 'public/favicon.ico')
: path.join(__dirname, 'build/favicon.ico');
mainWindow = new BrowserWindow({
width: 1000,
height: 700,
minWidth: 360,
minHeight: 500,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
devTools: isDev,
sandbox: true,
webSecurity: true,
disableBlinkFeatures: 'Auxclick'
},
autoHideMenuBar: true,
backgroundColor: '#0f172a',
title: 'WinVault',
icon: iconPath,
show: false
});
// Security
mainWindow.webContents.on('preload-error', (event, preloadPath, error) => {
console.error(`Unable to load preload ${preloadPath}: ${error.message}`);
});
// CSP Settings for Platform Security (Strict)
mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self' data: blob:; script-src 'self' blob: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' http://127.0.0.1:* https: ws:;"
],
'X-Content-Type-Options': ['nosniff'],
'X-Frame-Options': ['DENY']
}
});
});
const isDevelopment = process.env.ELECTRON_START_URL;
const startUrl = isDevelopment
? process.env.ELECTRON_START_URL
: `file://${path.join(__dirname, 'build/index.html')}`;
mainWindow.loadURL(startUrl);
if (isDevelopment) {
mainWindow.webContents.openDevTools();
}
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
// Global Panic: Ctrl+Shift+Space
globalShortcut.register('CommandOrControl+Shift+Space', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
mainWindow.webContents.send('global-shortcut-triggered');
}
});
// Auto-Type: Ctrl+Alt+A
globalShortcut.register('CommandOrControl+Alt+A', async () => {
console.log("Auto-Type Triggered");
try {
const title = await getActiveWindowTitle();
console.log("Active Window:", title);
// Ignore if WinVault itself is active
if (title.includes("WinVault")) {
// Maybe just focus?
return;
}
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('auto-type-request', title);
}
} catch (e) {
console.error(e);
}
});
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// --- IPC LISTENERS ---
ipcMain.on('set-mini-mode', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
win.setSize(380, 650, true); // Telefon boyutu
win.setAlwaysOnTop(true, 'floating'); // Her zaman üstte
}
});
ipcMain.on('set-normal-mode', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
win.setSize(1000, 700, true); // Normal boyut
win.setAlwaysOnTop(false);
win.center();
}
});
ipcMain.on('panic-action', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
win.minimize();
}
});
ipcMain.on('perform-auto-type', (event, { username, password }) => {
sendKeys(username, password);
});
ipcMain.handle('select-backup-folder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (result.canceled) return null;
return result.filePaths[0];
});
// Backup Encryption Helper - AES-256-GCM (PBKDF2 Derived Key)
const encryptBackupData = (data, password) => {
if (!password) throw new Error('Backup password required');
const salt = crypto.randomBytes(16);
// Key Derivation: PBKDF2-HMAC-SHA256
const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(data, 'utf-8', 'base64');
encrypted += cipher.final('base64');
const authTag = cipher.getAuthTag();
// Format: salt . iv . authTag . encrypted
return salt.toString('base64') + '.' +
iv.toString('base64') + '.' +
authTag.toString('base64') + '.' +
encrypted;
};
const decryptBackupData = (encryptedData, password) => {
if (!password) throw new Error('Backup password required');
const parts = encryptedData.split('.');
if (parts.length !== 4) {
throw new Error('Invalid encrypted backup format');
}
const salt = Buffer.from(parts[0], 'base64');
const iv = Buffer.from(parts[1], 'base64');
const authTag = Buffer.from(parts[2], 'base64');
const encrypted = parts[3];
const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'base64', 'utf-8');
decrypted += decipher.final('utf-8');
return decrypted;
};
ipcMain.handle('save-backup-file', async (event, filePath, content, password) => {
try {
const encrypted = encryptBackupData(content, password);
fs.writeFileSync(filePath, encrypted, 'utf-8');
return true;
} catch (e) {
console.error("Backup Save Error:", e);
return false;
}
});
ipcMain.handle('load-backup-file', async (event, filePath, password) => {
try {
const encrypted = fs.readFileSync(filePath, 'utf-8');
// Eğer şifreli format değilse (eski backup - key gömülü), yeni yöntemle çözülemez.
// Ancak geriye dönük uyumluluk için eski key extraction deneyebiliriz ama şu an "Security Overhaul" yapıyoruz.
// Eski backuplar çalışmayabilir, bu beklenen bir durum.
// Veya basitçe, split uzunluğu 4 ise ve password varsa dene.
if (!encrypted.includes('.') || encrypted.split('.').length !== 4) {
// Plain text or legacy? Plain text ise dön.
if (encrypted.startsWith('{')) return encrypted;
throw new Error('Unsupported format');
}
const decrypted = decryptBackupData(encrypted, password);
return decrypted;
} catch (e) {
console.error("Backup Load Error:", e);
return null;
}
});
ipcMain.handle('save-file', async (event, { name, data }) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (!win) return false;
// Sanitize filename to remove invalid characters
const safeName = name.replace(/[<>:"/\\|?*]/g, '_');
const { filePath } = await dialog.showSaveDialog(win, {
defaultPath: safeName,
title: 'Dosyayı Kaydet'
});
if (filePath) {
try {
let cleanBase64 = data;
// Robustly extract base64 data (everything after the first comma)
const commaIndex = data.indexOf(',');
if (commaIndex !== -1) {
cleanBase64 = data.substring(commaIndex + 1);
}
// Validate base64 data
if (!cleanBase64 || cleanBase64.trim() === '') {
console.error("Empty base64 data");
return false;
}
fs.writeFileSync(filePath, Buffer.from(cleanBase64, 'base64'));
console.log(`File saved successfully: ${filePath}`);
return true;
} catch (e) {
console.error("File Save Error:", e);
return false;
}
}
return false; // User canceled
});
ipcMain.handle('check-biometry', async () => {
return await checkBiometryAvailability();
});
ipcMain.handle('prompt-biometry', async (event, reason) => {
return await promptBiometry(reason);
});
ipcMain.handle('encrypt-key', async (event, key) => {
if (!safeStorage.isEncryptionAvailable()) return null;
const buffer = safeStorage.encryptString(key);
return buffer.toString('base64');
});
ipcMain.handle('decrypt-key', async (event, encryptedKey) => {
if (!safeStorage.isEncryptionAvailable()) return null;
const buffer = Buffer.from(encryptedKey, 'base64');
return safeStorage.decryptString(buffer);
});
// Hardware ID (Motherboard Serial)
ipcMain.handle('get-device-id', async () => {
return new Promise((resolve) => {
// First try: Baseboard Serial Number
exec('wmic baseboard get serialnumber', (error, stdout) => {
let serial = '';
if (!error && stdout) {
serial = stdout.replace('SerialNumber', '').trim();
}
// Validation: If empty or default string, fallback to CPU ID or UUID
if (!serial || serial === 'Default String' || serial.length < 3) {
exec('wmic csproduct get uuid', (err2, stdout2) => {
if (!err2 && stdout2) {
resolve(stdout2.replace('UUID', '').trim());
} else {
resolve('UNKNOWN-HWID-' + Math.random().toString(36).substring(7));
}
});
} else {
resolve(serial);
}
});
});
});
// --- BROWSER EXTENSION SERVER (Native Messaging Compatible) ---
const http = require('http');
const EXT_PORT = 19845;
// Rate limiting for security
const rateLimiter = new Map();
const rateLimitCheck = (clientIP) => {
const now = Date.now();
const windowMs = 15 * 60 * 1000; // 15 minutes
const maxRequests = 200;
if (!rateLimiter.has(clientIP)) {
rateLimiter.set(clientIP, { count: 1, resetTime: now + windowMs });
return { allowed: true };
}
const client = rateLimiter.get(clientIP);
if (now > client.resetTime) {
rateLimiter.set(clientIP, { count: 1, resetTime: now + windowMs });
return { allowed: true };
}
if (client.count >= maxRequests) {
return { allowed: false, waitTime: client.resetTime - now };
}
client.count++;
return { allowed: true };
};
// Validate localhost connection only
const isLocalhost = (ip) => {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1' || ip === 'localhost';
};
// HTTP Server for Native Messaging Host communication
const extServer = http.createServer((req, res) => {
// Security headers
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Type', 'application/json');
// CORS for extension (if needed for fallback)
const origin = req.headers.origin || '';
if (origin.startsWith('chrome-extension://') || origin.startsWith('moz-extension://')) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Native-Host, X-Request-Id');
}
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// Only allow localhost connections
const clientIP = req.socket.remoteAddress || req.connection.remoteAddress || '';
if (!isLocalhost(clientIP)) {
console.warn('[ExtServer] Rejected non-localhost connection:', clientIP);
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Only localhost connections allowed' }));
return;
}
// Rate limiting check
const rateLimitResult = rateLimitCheck(clientIP);
if (!rateLimitResult.allowed) {
res.writeHead(429, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Rate limit exceeded', waitTime: rateLimitResult.waitTime }));
return;
}
// Verify Native Host header
const nativeHostHeader = (req.headers['x-native-host'] || '').toLowerCase().trim();
if (req.url !== '/api/status' && nativeHostHeader !== 'winvault') {
console.warn(`[ExtServer] Invalid X-Native-Host: "${nativeHostHeader}" (Expected: "winvault") from URL: ${req.url}`);
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid request source', received: nativeHostHeader }));
return;
}
try {
const url = new URL(req.url, `http://${req.headers.host}`);
// --- API Status Check (for debugging) ---
if (url.pathname === '/api/status' && req.method === 'GET') {
const isLocked = !mainWindow || mainWindow.isDestroyed();
res.writeHead(200);
res.end(JSON.stringify({
status: 'online',
version: '2.0.0',
appReady: !isLocked,
timestamp: Date.now()
}));
return;
}
// --- Native Messaging API: Message Handler ---
if (url.pathname === '/api/native-message' && req.method === 'POST') {
if (!mainWindow || mainWindow.isDestroyed()) {
res.writeHead(503);
res.end(JSON.stringify({ error: 'WinVault is not ready' }));
return;
}
let body = '';
req.on('data', chunk => {
body += chunk.toString();
// Size protection (max 64KB)
if (body.length > 64 * 1024) {
req.socket.destroy();
}
});
req.on('end', async () => {
try {
const message = JSON.parse(body);
const { action, requestId, domain, username, password } = message;
if (!requestId) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Request ID required' }));
return;
}
console.log(`[ExtServer] Native message: ${action} (${requestId})`);
// Handle different actions
switch (action) {
case 'SEARCH':
if (!domain) {
res.writeHead(400);
res.end(JSON.stringify({ requestId, error: 'Domain required' }));
return;
}
// Setup response handler
let responded = false;
const searchTimeout = setTimeout(() => {
if (!responded) {
responded = true;
res.writeHead(408);
res.end(JSON.stringify({ requestId, error: 'Search timeout' }));
}
}, 4000);
const searchHandler = (event, results) => {
if (responded) return;
responded = true;
clearTimeout(searchTimeout);
res.writeHead(200);
res.end(JSON.stringify({
requestId,
results: results || [],
appStatus: 'unlocked'
}));
};
ipcMain.once('extension-search-response', searchHandler);
mainWindow.webContents.send('extension-search-request', domain);
break;
case 'SAVE':
if (!domain || !username || !password) {
res.writeHead(400);
res.end(JSON.stringify({ requestId, error: 'Missing fields' }));
return;
}
let saveResponded = false;
const saveTimeout = setTimeout(() => {
if (!saveResponded) {
saveResponded = true;
res.writeHead(408);
res.end(JSON.stringify({ requestId, error: 'Save timeout' }));
}
}, 4000);
const saveHandler = (event, result) => {
if (saveResponded) return;
saveResponded = true;
clearTimeout(saveTimeout);
res.writeHead(200);
res.end(JSON.stringify({
requestId,
ok: result && result.ok,
message: result?.message || 'Saved'
}));
};
ipcMain.once('extension-save-response', saveHandler);
mainWindow.webContents.send('extension-save-request', { domain, username, password });
break;
default:
res.writeHead(400);
res.end(JSON.stringify({ requestId, error: 'Unknown action' }));
}
} catch (error) {
console.error('[ExtServer] Parse error:', error.message);
res.writeHead(400);
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
// 404 for other paths
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not found' }));
} catch (e) {
console.error('[ExtServer] Error:', e.message);
res.writeHead(500);
res.end(JSON.stringify({ error: 'Internal server error' }));
}
});
// Start extension server with Port Hopping
let currentPort = EXT_PORT;
const startServer = (port) => {
extServer.listen(port, '127.0.0.1', () => {
console.log(`[ExtServer] WinVault Extension Server running on 127.0.0.1:${port}`);
});
};
startServer(currentPort);
// Error handling for server
extServer.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.warn(`[ExtServer] Port ${currentPort} is already in use, trying next...`);
currentPort++;
if (currentPort < EXT_PORT + 10) {
setTimeout(() => {
extServer.removeAllListeners('listening'); // Clean up old listeners if any
try { extServer.close(); } catch (e) { }
startServer(currentPort);
}, 100);
} else {
console.error('[ExtServer] Could not find an available port.');
}
} else {
console.error('[ExtServer] Server error:', err.message);
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Cleanup on exit
app.on('will-quit', () => {
extServer.close();
});