-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
953 lines (866 loc) · 36.9 KB
/
Copy pathmain.js
File metadata and controls
953 lines (866 loc) · 36.9 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
const { app, BrowserWindow, ipcMain, Menu, Tray, nativeImage, dialog, shell } = require('electron');
const https = require('https');
const path = require('path');
const fs = require('fs');
const { exec, spawn, execFile } = require('child_process');
// Backend macOS (dislocker) — ładowany tylko na darwin
const mac = (process.platform === 'darwin') ? require('./backend-macos') : null;
// Provider WMI BitLockera — obecny na WSZYSTKICH edycjach Windows (też Home)
const WMI_NS = 'root\\CIMV2\\Security\\MicrosoftVolumeEncryption';
let mainWindow = null;
let tray = null;
// Stan aplikacji (ochrona przed zabiciem podczas operacji)
const appState = {
isQuitting: false, // true tylko gdy user świadomie wychodzi
busy: false, // trwa krytyczna operacja (szyfrowanie/deszyfrowanie/odblokowanie)
busyLabel: '' // opis operacji do pokazania w tray
};
const ICON_PATH = path.join(__dirname, 'assets', 'icon.png');
const TRAY_ICON_PATH = path.join(__dirname, 'assets', 'tray.png');
// --- i18n procesu głównego (tray, dialogi, komunikaty zwracane do UI) ---
let mainLang = 'pl';
const MT = {
pl: {
'tray.title': 'BitLockPick — Menedżer BitLocker',
'tray.idle': '○ Bezczynny',
'tray.show': 'Pokaż okno',
'tray.quit': 'Zakończ',
'tray.tipBusy': 'BitLockPick — {label}',
'tray.tipIdle': 'BitLockPick — bezczynny',
'tray.busyDefault': 'Operacja w toku...',
'notif.opTitle': 'Operacja w toku',
'notif.opBody': 'BitLocker pracuje w tle. Aplikacja została zminimalizowana do zasobnika.',
'notif.bgTitle': 'Działam w tle',
'notif.bgBody': 'Operacja BitLocker trwa. Kliknij ikonę w zasobniku, by wrócić.',
'quit.keep': 'Pozostaw w tle',
'quit.quit': 'Zakończ mimo to',
'quit.title': 'Trwa operacja BitLocker',
'quit.msg': 'Trwa krytyczna operacja na dysku (szyfrowanie/deszyfrowanie).',
'quit.detail': 'Zamknięcie aplikacji teraz jest bezpieczne dla danych (proces BitLocker działa w systemie), ale stracisz podgląd postępu. Zalecane: pozostaw w tle.',
'enc.keyErr': 'Błąd pobierania klucza, sprawdź stan dysku.',
'enc.keyManual': 'Uruchomiono szyfrowanie, ale nie udało się wyodrębnić klucza automatycznie. Użyj Get-BitLockerVolume w PowerShell.',
'busy.recover': 'Odzyskiwanie klucza dysku {L}:',
'busy.recoverProgress': 'Odzyskiwanie {L}: {tried}/{tot}',
'rec.winOnly': 'Odzyskiwanie działa tylko na Windows.',
'rec.running': 'Odzyskiwanie już trwa.',
'rec.badLetter': 'Wybierz zablokowany dysk docelowy.',
'rec.markUnknown': 'Zaznacz co najmniej jeden nieznany blok (przycisk „?").',
'rec.badKnown': 'Znany blok nie spełnia sumy kontrolnej mod-11: {b}. Napraw go najpierw w Walidatorze.',
'rec.tooBig': 'Przestrzeń {total} kombinacji jest zbyt duża dla metody online (limit {cap}, ~1 brakujący blok). Dla 2+ brakujących bloków użyj offline GPU (np. bitcracker).',
'rec.spawn': 'Nie udało się uruchomić PowerShell: {e}',
'rec.proc': 'Błąd procesu PowerShell: {e}',
'rec.sessionMismatch': 'Zapisana sesja nie pasuje do bieżących ustawień. Wznów z zapisaną sesją lub zacznij od nowa.',
'rec.sessionComplete': 'Zapisana sesja jest już ukończona.',
'err.badLetter': 'Nieprawidłowa litera dysku.'
},
en: {
'tray.title': 'BitLockPick — BitLocker Manager',
'tray.idle': '○ Idle',
'tray.show': 'Show window',
'tray.quit': 'Quit',
'tray.tipBusy': 'BitLockPick — {label}',
'tray.tipIdle': 'BitLockPick — idle',
'tray.busyDefault': 'Operation in progress...',
'notif.opTitle': 'Operation in progress',
'notif.opBody': 'BitLocker is working in the background. The app was minimized to the tray.',
'notif.bgTitle': 'Running in background',
'notif.bgBody': 'A BitLocker operation is running. Click the tray icon to return.',
'quit.keep': 'Keep in background',
'quit.quit': 'Quit anyway',
'quit.title': 'BitLocker operation in progress',
'quit.msg': 'A critical drive operation is running (encryption/decryption).',
'quit.detail': 'Closing the app now is safe for your data (BitLocker runs in the system), but you lose the progress view. Recommended: keep it in the background.',
'enc.keyErr': 'Error retrieving the key, check the drive state.',
'enc.keyManual': 'Encryption started, but the key could not be extracted automatically. Use Get-BitLockerVolume in PowerShell.',
'busy.recover': 'Recovering key for drive {L}:',
'busy.recoverProgress': 'Recovering {L}: {tried}/{tot}',
'rec.winOnly': 'Recovery works on Windows only.',
'rec.running': 'Recovery is already running.',
'rec.badLetter': 'Select a target locked drive.',
'rec.markUnknown': 'Mark at least one unknown block (the "?" button).',
'rec.badKnown': 'A known block does not satisfy the mod-11 checksum: {b}. Fix it first in the Validator.',
'rec.tooBig': 'The space of {total} combinations is too large for the online method (limit {cap}, ~1 missing block). For 2+ missing blocks use an offline GPU tool (e.g. bitcracker).',
'rec.spawn': 'Failed to start PowerShell: {e}',
'rec.proc': 'PowerShell process error: {e}',
'rec.sessionMismatch': 'Saved session does not match current settings. Resume the saved session or start fresh.',
'rec.sessionComplete': 'Saved session is already complete.',
'err.badLetter': 'Invalid drive letter.'
}
};
function mt(key, vars) {
const table = MT[mainLang] || MT.pl;
let s = (key in table) ? table[key] : (MT.pl[key] !== undefined ? MT.pl[key] : key);
if (vars) for (const k in vars) s = s.replace(new RegExp('\\{' + k + '\\}', 'g'), vars[k]);
return s;
}
// ====================================================================
// SINGLE INSTANCE LOCK — nie pozwalamy uruchomić dwóch kopii
// ====================================================================
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (!mainWindow.isVisible()) mainWindow.show();
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 900,
minHeight: 600,
frame: false, // usuwamy natywny pasek — własny, przezroczysty
titleBarStyle: 'hidden',
backgroundColor: '#0a0b10',
icon: ICON_PATH,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
},
show: false
});
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
// Otwieraj linki zewnętrzne w przeglądarce
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// Zamknięcie okna: jeśli to nie świadome wyjście -> chowaj do tray
mainWindow.on('close', (e) => {
if (!appState.isQuitting) {
e.preventDefault();
mainWindow.hide();
if (appState.busy) {
showTrayNotification(mt('notif.opTitle'), appState.busyLabel || mt('notif.opBody'));
}
}
});
// Wyślij stan maksymalizacji do renderera (do ikony przycisku)
const sendMaxState = () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('window-maximized', mainWindow.isMaximized());
}
};
mainWindow.on('maximize', sendMaxState);
mainWindow.on('unmaximize', sendMaxState);
}
// ====================================================================
// TRAY
// ====================================================================
function buildTrayImage() {
let img = nativeImage.createFromPath(TRAY_ICON_PATH);
if (img.isEmpty()) {
// awaryjnie — pusty obrazek nie wywali aplikacji
img = nativeImage.createEmpty();
}
return img;
}
function updateTray() {
if (!tray) return;
const statusLine = appState.busy
? `● ${appState.busyLabel || mt('tray.busyDefault')}`
: mt('tray.idle');
const contextMenu = Menu.buildFromTemplate([
{ label: mt('tray.title'), enabled: false },
{ type: 'separator' },
{ label: statusLine, enabled: false },
{ type: 'separator' },
{
label: mt('tray.show'),
click: () => {
if (mainWindow) {
mainWindow.show();
mainWindow.focus();
}
}
},
{
label: mt('tray.quit'),
click: () => requestQuit()
}
]);
tray.setToolTip(appState.busy
? mt('tray.tipBusy', { label: appState.busyLabel || mt('tray.busyDefault') })
: mt('tray.tipIdle'));
tray.setContextMenu(contextMenu);
}
function showTrayNotification(title, body) {
if (tray && process.platform === 'win32') {
try {
tray.displayBalloon({ title, content: body, icon: buildTrayImage() });
} catch (_) { /* balloon nie zawsze dostępny */ }
}
}
function createTray() {
tray = new Tray(buildTrayImage());
tray.on('click', () => {
if (mainWindow) {
if (mainWindow.isVisible()) {
mainWindow.focus();
} else {
mainWindow.show();
mainWindow.focus();
}
}
});
updateTray();
}
// Świadome wyjście — z ostrzeżeniem gdy trwa operacja
function requestQuit() {
if (appState.busy) {
const choice = dialog.showMessageBoxSync(mainWindow, {
type: 'warning',
buttons: [mt('quit.keep'), mt('quit.quit')],
defaultId: 0,
cancelId: 0,
title: mt('quit.title'),
message: mt('quit.msg'),
detail: (appState.busyLabel ? appState.busyLabel + '\n\n' : '') + mt('quit.detail')
});
if (choice === 0) return; // pozostaw w tle
}
appState.isQuitting = true;
app.quit();
}
// ====================================================================
// LIFECYCLE
// ====================================================================
app.whenReady().then(() => {
Menu.setApplicationMenu(null);
createWindow();
createTray();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// Nie zamykaj aplikacji przy zamknięciu okna — żyje w tray
app.on('window-all-closed', () => {
// celowo pusto — wychodzimy tylko przez requestQuit()
});
app.on('before-quit', () => {
appState.isQuitting = true;
});
// ====================================================================
// POWERSHELL HELPER
// ====================================================================
function runPowerShell(command) {
return new Promise((resolve) => {
if (process.platform !== 'win32') {
resolve({ success: false, error: 'Ta operacja jest dostępna tylko na systemie Windows.' });
return;
}
const buffer = Buffer.from(command, 'utf16le');
const base64Command = buffer.toString('base64');
// execFile (nie exec) — omija cmd.exe i jego limit ~8191 znaków wiersza poleceń
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', base64Command], { maxBuffer: 1024 * 1024 * 16, windowsHide: true }, (error, stdout, stderr) => {
if (error) {
resolve({ success: false, error: stderr || error.message });
} else {
resolve({ success: true, stdout });
}
});
});
}
// Waliduje literę dysku, by uniknąć wstrzyknięcia do skryptu PowerShell
function safeLetter(letter) {
const m = String(letter || '').trim().match(/^([A-Za-z])/);
return m ? m[1].toUpperCase() : null;
}
// ====================================================================
// IPC — OKNO / TRAY / STAN
// ====================================================================
ipcMain.on('window-minimize', () => { if (mainWindow) mainWindow.minimize(); });
ipcMain.on('window-maximize', () => {
if (!mainWindow) return;
if (mainWindow.isMaximized()) mainWindow.unmaximize();
else mainWindow.maximize();
});
ipcMain.on('window-close', () => {
// "X" chowa do tray (zgodnie z zamysłem: apka żyje w tle)
if (mainWindow) mainWindow.hide();
if (appState.busy) {
showTrayNotification(mt('notif.bgTitle'), appState.busyLabel || mt('notif.bgBody'));
}
});
ipcMain.handle('window-is-maximized', () => mainWindow ? mainWindow.isMaximized() : false);
// Język procesu głównego (tray/dialogi)
ipcMain.on('app:set-lang', (event, lang) => {
mainLang = (lang === 'en') ? 'en' : 'pl';
updateTray();
});
// Renderer zgłasza rozpoczęcie/zakończenie krytycznej operacji
ipcMain.on('set-busy', (event, payload) => {
appState.busy = !!(payload && payload.busy);
appState.busyLabel = (payload && payload.label) ? String(payload.label) : '';
updateTray();
});
// ====================================================================
// IPC — SYSTEM
// ====================================================================
ipcMain.handle('get-os', () => process.platform);
ipcMain.handle('check-admin', async () => {
if (process.platform !== 'win32') return false;
const script = `
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
Write-Output $isAdmin
`;
const result = await runPowerShell(script);
if (result.success && result.stdout) {
return result.stdout.trim().toLowerCase() === 'true';
}
return false;
});
ipcMain.handle('get-drives', async () => {
if (process.platform === 'darwin') return mac.getDrives();
if (process.platform !== 'win32') {
return { success: false, error: 'Not on Windows' };
}
// Backend oparty na WMI Win32_EncryptableVolume — provider obecny na WSZYSTKICH
// edycjach Windows (także Home; Get-BitLockerVolume/moduł cmdletów Home nie ma).
// Wartości liczbowe, niezależne od języka.
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ns = '${WMI_NS}'
$supported = $true
$blByLetter = @{}
try {
$vols = Get-CimInstance -Namespace $ns -ClassName Win32_EncryptableVolume -ErrorAction Stop
foreach ($v in $vols) {
if ($v.DriveLetter) { $blByLetter[[string]($v.DriveLetter.TrimEnd(':'))] = $v }
}
} catch { $supported = $false }
$result = @()
$drives = Get-Volume | Where-Object { $_.DriveLetter -ne $null }
foreach ($d in $drives) {
$letter = [string]$d.DriveLetter
$bl = $blByLetter[$letter]
$status = 'None'; $protection = 'Off'; $isLocked = $false; $encPercent = $null; $keyProtectors = @()
$size = $d.Size; $sizeRemaining = $d.SizeRemaining
if ($bl) {
$lockRes = Invoke-CimMethod -InputObject $bl -MethodName 'GetLockStatus' -ErrorAction SilentlyContinue
$isLocked = ($lockRes -and $lockRes.ReturnValue -eq 0 -and $lockRes.LockStatus -eq 1)
$convRes = Invoke-CimMethod -InputObject $bl -MethodName 'GetConversionStatus' -ErrorAction SilentlyContinue
$conv = if ($convRes -and $convRes.ReturnValue -eq 0) { $convRes.ConversionStatus } else { $bl.ConversionStatus }
if ($convRes -and $convRes.ReturnValue -eq 0) { $encPercent = $convRes.EncryptionPercentage }
$ps = [int]$bl.ProtectionStatus
$protection = switch ($ps) { 1 { 'On' } 2 { 'Unknown' } default { 'Off' } }
if ($isLocked) {
$status = 'FullyEncrypted'
} else {
switch ([int]$conv) {
0 { $status = 'None' }
1 { $status = 'FullyEncrypted' }
2 { $status = 'EncryptionInProgress' }
3 { $status = 'DecryptionInProgress' }
default { $status = 'None' }
}
}
try {
$kpRes = Invoke-CimMethod -InputObject $bl -MethodName 'GetKeyProtectors' -Arguments @{ KeyProtectorType = [uint32]0 } -ErrorAction SilentlyContinue
if ($kpRes -and $kpRes.VolumeKeyProtectorID) {
foreach ($id in $kpRes.VolumeKeyProtectorID) {
$tRes = Invoke-CimMethod -InputObject $bl -MethodName 'GetKeyProtectorType' -Arguments @{ VolumeKeyProtectorID = $id } -ErrorAction SilentlyContinue
$tnum = if ($tRes) { [int]$tRes.KeyProtectorType } else { 0 }
$tname = switch ($tnum) { 1 {'Tpm'} 2 {'ExternalKey'} 3 {'RecoveryPassword'} 8 {'Password'} default {"Type$tnum"} }
$keyProtectors += @{ Id = $id; Type = $tname }
}
}
} catch {}
if ((-not $size -or $size -eq 0)) {
try {
$ld = Get-CimInstance -ClassName Win32_LogicalDisk -Filter ("DeviceID='" + $letter + ":'") -ErrorAction SilentlyContinue
if ($ld -and $ld.Size) { $size = $ld.Size }
} catch {}
}
}
$result += @{
Letter = $letter; Label = $d.FileSystemLabel; FileSystem = $d.FileSystem
Size = $size; SizeRemaining = $sizeRemaining
EncryptionStatus = $status; ProtectionStatus = $protection; EncryptionPercentage = $encPercent
IsLocked = $isLocked; KeyProtectors = $keyProtectors
}
}
(@{ BitLockerSupported = $supported; Drives = $result }) | ConvertTo-Json -Depth 5
`;
const result = await runPowerShell(script);
if (result.success && result.stdout) {
try {
const data = JSON.parse(result.stdout);
if (data && data.Drives && !Array.isArray(data.Drives)) {
data.Drives = [data.Drives];
}
if (data && !data.Drives) data.Drives = [];
return { success: true, data };
} catch (e) {
return { success: false, error: 'Błąd przetwarzania danych JSON z PowerShell: ' + e.message, raw: result.stdout };
}
}
return { success: false, error: result.error || 'Nieznany błąd podczas pobierania dysków.' };
});
// Pobierz obiekt woluminu WMI po literze (fragment PowerShell)
function wmiVolSnippet(L) {
return `$vol = Get-CimInstance -Namespace '${WMI_NS}' -ClassName Win32_EncryptableVolume -Filter "DriveLetter='${L}:'"`;
}
// Uruchom skrypt WMI zwracający JSON @{ Ok=...; Error=...; RecoveryKey=... }
async function runWmiJson(script) {
const result = await runPowerShell(script);
if (result.success && result.stdout && result.stdout.trim()) {
try { return JSON.parse(result.stdout); }
catch (e) { return { Ok: false, Error: 'Parse: ' + e.message }; }
}
return { Ok: false, Error: result.error || 'Nieznany błąd.' };
}
ipcMain.handle('unlock-drive', async (event, params) => {
if (process.platform === 'darwin') return mac.unlockDrive(params);
const { letter, password, type } = params;
const L = safeLetter(letter);
if (!L) return { success: false, error: mt('err.badLetter') };
let method, args;
if (type === 'password') {
const pw = String(password).replace(/'/g, "''");
method = 'UnlockWithPassphrase';
args = `@{ Passphrase = '${pw}' }`;
} else {
const key = String(password).trim().replace(/[^0-9-]/g, '');
method = 'UnlockWithNumericalPassword';
args = `@{ NumericalPassword = '${key}' }`;
}
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
${wmiVolSnippet(L)}
if (-not $vol) { (@{ Ok = $false; Error = 'Nie znaleziono woluminu BitLocker.' }) | ConvertTo-Json }
else {
$r = Invoke-CimMethod -InputObject $vol -MethodName '${method}' -Arguments ${args}
if ($r.ReturnValue -eq 0) { (@{ Ok = $true }) | ConvertTo-Json }
else { (@{ Ok = $false; Error = ('BitLocker: 0x{0:X8}' -f ([uint32]$r.ReturnValue)) }) | ConvertTo-Json }
}
`;
const d = await runWmiJson(script);
return d.Ok ? { success: true } : { success: false, error: d.Error };
});
ipcMain.handle('lock-drive', async (event, { letter }) => {
if (process.platform === 'darwin') return mac.lockDrive({ letter });
const L = safeLetter(letter);
if (!L) return { success: false, error: mt('err.badLetter') };
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
${wmiVolSnippet(L)}
if (-not $vol) { (@{ Ok = $false; Error = 'Nie znaleziono woluminu BitLocker.' }) | ConvertTo-Json }
else {
$r = Invoke-CimMethod -InputObject $vol -MethodName 'Lock' -Arguments @{ ForceDismount = $true }
if ($r.ReturnValue -eq 0) { (@{ Ok = $true }) | ConvertTo-Json }
else { (@{ Ok = $false; Error = ('BitLocker: 0x{0:X8}' -f ([uint32]$r.ReturnValue)) }) | ConvertTo-Json }
}
`;
const d = await runWmiJson(script);
return d.Ok ? { success: true } : { success: false, error: d.Error };
});
ipcMain.handle('enable-bitlocker', async (event, { letter, password }) => {
if (process.platform === 'darwin') return mac.enableBitLocker({ letter, password });
const L = safeLetter(letter);
if (!L) return { success: false, error: mt('err.badLetter') };
const pw = String(password).replace(/'/g, "''");
// WMI Encrypt: EncryptionMethod 6 = XTS-AES-128, EncryptionFlags 1 = tylko zajęte miejsce.
// Na Windows Home Encrypt() bywa licencyjnie blokowany -> zwracamy czytelny błąd (best-effort).
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
${wmiVolSnippet(L)}
if (-not $vol) { (@{ Ok = $false; Error = 'Nie znaleziono woluminu.' }) | ConvertTo-Json }
else {
$null = Invoke-CimMethod -InputObject $vol -MethodName 'ProtectKeyWithPassphrase' -Arguments @{ FriendlyName = 'BitLockPick'; Passphrase = '${pw}' } -ErrorAction SilentlyContinue
$null = Invoke-CimMethod -InputObject $vol -MethodName 'ProtectKeyWithNumericalPassword' -Arguments @{ FriendlyName = 'BitLockPick Recovery' } -ErrorAction SilentlyContinue
$enc = Invoke-CimMethod -InputObject $vol -MethodName 'Encrypt' -Arguments @{ EncryptionMethod = [uint32]6; EncryptionFlags = [uint32]1 }
if ($enc.ReturnValue -ne 0) {
(@{ Ok = $false; Error = ('BitLocker Encrypt: 0x{0:X8} (na Windows Home szyfrowanie bywa niedostepne)' -f ([uint32]$enc.ReturnValue)) }) | ConvertTo-Json
} else {
$vol2 = Get-CimInstance -Namespace '${WMI_NS}' -ClassName Win32_EncryptableVolume -Filter "DriveLetter='${L}:'"
$kp = Invoke-CimMethod -InputObject $vol2 -MethodName 'GetKeyProtectors' -Arguments @{ KeyProtectorType = [uint32]3 }
$key = ''
foreach ($id in $kp.VolumeKeyProtectorID) {
$np = Invoke-CimMethod -InputObject $vol2 -MethodName 'GetKeyProtectorNumericalPassword' -Arguments @{ VolumeKeyProtectorID = $id }
if ($np.ReturnValue -eq 0) { $key = $np.NumericalPassword }
}
(@{ Ok = $true; RecoveryKey = $key }) | ConvertTo-Json
}
}
`;
const d = await runWmiJson(script);
if (d.Ok) return { success: true, recoveryKey: d.RecoveryKey || mt('enc.keyManual') };
return { success: false, error: d.Error };
});
ipcMain.handle('disable-bitlocker', async (event, { letter }) => {
if (process.platform === 'darwin') return mac.disableBitLocker({ letter });
const L = safeLetter(letter);
if (!L) return { success: false, error: mt('err.badLetter') };
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
${wmiVolSnippet(L)}
if (-not $vol) { (@{ Ok = $false; Error = 'Nie znaleziono woluminu BitLocker.' }) | ConvertTo-Json }
else {
$r = Invoke-CimMethod -InputObject $vol -MethodName 'Decrypt'
if ($r.ReturnValue -eq 0) { (@{ Ok = $true }) | ConvertTo-Json }
else { (@{ Ok = $false; Error = ('BitLocker: 0x{0:X8}' -f ([uint32]$r.ReturnValue)) }) | ConvertTo-Json }
}
`;
const d = await runWmiJson(script);
return d.Ok ? { success: true } : { success: false, error: d.Error };
});
ipcMain.handle('get-backup-key', async (event, { letter }) => {
if (process.platform === 'darwin') return mac.getBackupKey({ letter });
const L = safeLetter(letter);
if (!L) return { success: false, error: mt('err.badLetter') };
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
${wmiVolSnippet(L)}
if (-not $vol) { (@{ Ok = $false; Error = 'Nie znaleziono woluminu.' }) | ConvertTo-Json }
else {
$kp = Invoke-CimMethod -InputObject $vol -MethodName 'GetKeyProtectors' -Arguments @{ KeyProtectorType = [uint32]3 }
$key = ''
foreach ($id in $kp.VolumeKeyProtectorID) {
$np = Invoke-CimMethod -InputObject $vol -MethodName 'GetKeyProtectorNumericalPassword' -Arguments @{ VolumeKeyProtectorID = $id }
if ($np.ReturnValue -eq 0 -and $np.NumericalPassword) { $key = $np.NumericalPassword }
}
if ($key) { (@{ Ok = $true; RecoveryKey = $key }) | ConvertTo-Json }
else { (@{ Ok = $false; Error = 'Brak klucza odzyskiwania na tym woluminie.' }) | ConvertTo-Json }
}
`;
const d = await runWmiJson(script);
return d.Ok ? { success: true, recoveryKey: d.RecoveryKey } : { success: false, error: d.Error };
});
// ====================================================================
// RECOVERY LAB — eksperymentalne odzyskiwanie klucza metodą siłową
// Testuje TYLKO kandydatów spełniających sumę kontrolną mod-11 (65536/blok).
// Cap: obsługa online do ~1 brakującego bloku (metoda przez Unlock-BitLocker).
// ====================================================================
let recoveryProc = null; // Windows: uchwyt spawn
let macRecovery = null; // macOS: uchwyt { stop() }
const RECOVERY_CAP = 200000; // maks. liczba kandydatów dla metody online
const RECOVERY_SESSION_VERSION = 1;
let recoveryLastTried = 0;
let recoveryTotal = 0;
let recoverySaveTimer = null;
let currentRecoverySession = null;
function recoverySessionPath() {
return path.join(app.getPath('userData'), 'recovery-session.json');
}
function readRecoverySession() {
try {
const raw = fs.readFileSync(recoverySessionPath(), 'utf8');
const s = JSON.parse(raw);
if (s && s.version === RECOVERY_SESSION_VERSION
&& s.letter && Array.isArray(s.blocks)
&& Array.isArray(s.unknownIndices)
&& typeof s.tried === 'number' && typeof s.total === 'number'
&& s.tried < s.total) {
return s;
}
} catch (_) {}
return null;
}
function writeRecoverySession(session) {
try {
const dir = app.getPath('userData');
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(recoverySessionPath(), JSON.stringify(session, null, 2), 'utf8');
} catch (_) {}
}
function clearRecoverySession() {
try { fs.unlinkSync(recoverySessionPath()); } catch (_) {}
currentRecoverySession = null;
}
function saveRecoveryProgress(tried, total) {
if (!currentRecoverySession) return;
currentRecoverySession.tried = tried;
currentRecoverySession.total = total;
currentRecoverySession.updatedAt = new Date().toISOString();
writeRecoverySession(currentRecoverySession);
}
function startRecoveryAutoSave() {
stopRecoveryAutoSave();
recoverySaveTimer = setInterval(() => {
if (currentRecoverySession) writeRecoverySession(currentRecoverySession);
}, 30000);
}
function stopRecoveryAutoSave() {
if (recoverySaveTimer) {
clearInterval(recoverySaveTimer);
recoverySaveTimer = null;
}
}
function finishRecoverySession(clear) {
stopRecoveryAutoSave();
if (clear) clearRecoverySession();
}
function blocksMatchSession(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== 8 || b.length !== 8) return false;
for (let i = 0; i < 8; i++) {
if (String(a[i] || '').trim() !== String(b[i] || '').trim()) return false;
}
return true;
}
ipcMain.handle('recovery:get-session', () => readRecoverySession());
ipcMain.handle('recovery:clear-session', () => {
finishRecoverySession(true);
return true;
});
ipcMain.on('recovery:start', (event, payload) => {
const sender = event.sender;
let doneSent = false;
const done = (obj, clearSession) => {
if (doneSent) return;
doneSent = true;
finishRecoverySession(!!clearSession);
try { sender.send('recovery:done', obj); } catch (_) {}
};
const startOffset = Math.max(0, Math.floor(Number(payload && payload.startOffset) || 0));
// --- macOS: brute-force przez dislocker (moduł backend-macos) ---
if (process.platform === 'darwin') {
if (macRecovery) { done({ success: false, error: mt('rec.running') }); return; }
const L = String((payload && payload.letter) || '?');
const raw = (payload && Array.isArray(payload.blocks)) ? payload.blocks : [];
const known = [];
for (let i = 0; i < 8; i++) {
const b = String(raw[i] || '').trim();
known.push(/^[0-9]{6}$/.test(b) ? b : '');
}
const unknown = [];
for (let i = 0; i < 8; i++) if (known[i] === '') unknown.push(i);
const total = Math.pow(65536, unknown.length);
if (startOffset > 0) {
const saved = readRecoverySession();
if (!saved || saved.letter !== L || !blocksMatchSession(saved.blocks, known) || saved.total !== total) {
done({ success: false, error: mt('rec.sessionMismatch') });
return;
}
currentRecoverySession = saved;
} else {
currentRecoverySession = {
version: RECOVERY_SESSION_VERSION,
letter: L,
blocks: known,
unknownIndices: unknown,
tried: 0,
total,
startedAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
writeRecoverySession(currentRecoverySession);
}
recoveryLastTried = startOffset;
recoveryTotal = total;
startRecoveryAutoSave();
appState.busy = true;
appState.busyLabel = mt('busy.recover', { L });
updateTray();
const finish = (obj) => {
macRecovery = null;
appState.busy = false; appState.busyLabel = ''; updateTray();
const clearSession = !!(obj.success || obj.notfound);
if (!clearSession && recoveryLastTried > 0) saveRecoveryProgress(recoveryLastTried, recoveryTotal);
done(obj, clearSession);
};
macRecovery = mac.startRecovery({ ...payload, startOffset }, {
onProgress: (p) => {
recoveryLastTried = p.tried || 0;
recoveryTotal = p.total || recoveryTotal;
saveRecoveryProgress(recoveryLastTried, recoveryTotal);
try { sender.send('recovery:progress', p); } catch (_) {}
appState.busyLabel = mt('busy.recoverProgress', { L, tried: p.tried, tot: p.total });
updateTray();
},
onDone: (obj) => finish(obj)
});
return;
}
if (process.platform !== 'win32') { done({ success: false, error: mt('rec.winOnly') }); return; }
if (recoveryProc) { done({ success: false, error: mt('rec.running') }); return; }
const L = safeLetter(payload && payload.letter);
if (!L) { done({ success: false, error: mt('rec.badLetter') }); return; }
const raw = (payload && Array.isArray(payload.blocks)) ? payload.blocks : [];
const known = [];
for (let i = 0; i < 8; i++) {
const b = String(raw[i] || '').trim();
known.push(/^[0-9]{6}$/.test(b) ? b : '');
}
const unknown = [];
for (let i = 0; i < 8; i++) if (known[i] === '') unknown.push(i);
if (unknown.length === 0) { done({ success: false, error: mt('rec.markUnknown') }); return; }
// Znane bloki muszą spełniać mod-11
const bad = known.filter(b => b !== '' && !((parseInt(b, 10) % 11 === 0) && (parseInt(b, 10) / 11 <= 65535)));
if (bad.length) { done({ success: false, error: mt('rec.badKnown', { b: bad.join(', ') }) }); return; }
const nloc = mainLang === 'en' ? 'en-US' : 'pl-PL';
const total = Math.pow(65536, unknown.length);
if (total > RECOVERY_CAP) {
done({ success: false, error: mt('rec.tooBig', { total: total.toLocaleString(nloc), cap: RECOVERY_CAP.toLocaleString(nloc) }) });
return;
}
if (startOffset >= total) { done({ success: false, error: mt('rec.sessionComplete') }); return; }
if (startOffset > 0) {
const saved = readRecoverySession();
if (!saved || saved.letter !== L || !blocksMatchSession(saved.blocks, known) || saved.total !== total) {
done({ success: false, error: mt('rec.sessionMismatch') });
return;
}
currentRecoverySession = saved;
} else {
currentRecoverySession = {
version: RECOVERY_SESSION_VERSION,
letter: L,
blocks: known,
unknownIndices: unknown,
tried: 0,
total,
startedAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
writeRecoverySession(currentRecoverySession);
}
recoveryLastTried = startOffset;
recoveryTotal = total;
startRecoveryAutoSave();
const knownPs = known.map(b => `'${b}'`).join(',');
const unknownPs = unknown.join(',');
const script = `
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$vol = Get-CimInstance -Namespace '${WMI_NS}' -ClassName Win32_EncryptableVolume -Filter "DriveLetter='${L}:'"
if (-not $vol) { Write-Output "NOTFOUND"; exit }
$known = @(${knownPs})
$unknown = @(${unknownPs})
$radix = 65536
$total = 1
foreach ($u in $unknown) { $total = $total * $radix }
$startOffset = ${startOffset}
$counters = New-Object 'int[]' $unknown.Count
$rem = $startOffset
for ($ji = $unknown.Count - 1; $ji -ge 0; $ji--) {
$counters[$ji] = $rem % $radix
$rem = [math]::Floor($rem / $radix)
}
$found = $null
$i = $startOffset
if ($startOffset -gt 0) { Write-Output "PROGRESS $startOffset $total" }
while ($i -lt $total) {
$parts = $known.Clone()
for ($j = 0; $j -lt $unknown.Count; $j++) {
$q = $counters[$j]
$parts[$unknown[$j]] = '{0:D6}' -f ($q * 11)
}
$key = ($parts -join '-')
$r = Invoke-CimMethod -InputObject $vol -MethodName 'UnlockWithNumericalPassword' -Arguments @{ NumericalPassword = $key } -ErrorAction SilentlyContinue
if ($r -and $r.ReturnValue -eq 0) {
$found = $key
break
}
$k = 0
while ($k -lt $unknown.Count) {
$counters[$k]++
if ($counters[$k] -lt $radix) { break }
$counters[$k] = 0
$k++
}
$i++
if ($i % 200 -eq 0) { Write-Output "PROGRESS $i $total" }
}
if ($found) { Write-Output "FOUND $found" } else { Write-Output "NOTFOUND" }
`;
const b64 = Buffer.from(script, 'utf16le').toString('base64');
appState.busy = true;
appState.busyLabel = mt('busy.recover', { L });
updateTray();
try {
recoveryProc = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', b64], { windowsHide: true });
} catch (err) {
appState.busy = false; appState.busyLabel = ''; updateTray();
finishRecoverySession(true);
done({ success: false, error: mt('rec.spawn', { e: err.message }) });
return;
}
sender.send('recovery:progress', { tried: startOffset, total });
let buf = '';
recoveryProc.stdout.on('data', (d) => {
buf += d.toString();
const lines = buf.split(/\r?\n/);
buf = lines.pop();
for (const line of lines) {
const t = line.trim();
if (t.startsWith('PROGRESS ')) {
const p = t.split(/\s+/);
const tried = Number(p[1]); const tot = Number(p[2]);
recoveryLastTried = tried;
recoveryTotal = tot;
saveRecoveryProgress(tried, tot);
try { sender.send('recovery:progress', { tried, total: tot }); } catch (_) {}
appState.busyLabel = mt('busy.recoverProgress', { L, tried, tot });
updateTray();
} else if (t.startsWith('FOUND ')) {
done({ success: true, key: t.slice(6).trim(), letter: L }, true);
} else if (t === 'NOTFOUND') {
done({ success: false, notfound: true }, true);
}
}
});
recoveryProc.on('close', () => {
recoveryProc = null;
appState.busy = false; appState.busyLabel = ''; updateTray();
if (recoveryLastTried > 0) saveRecoveryProgress(recoveryLastTried, recoveryTotal);
done({ success: false, stopped: true }, false);
});
recoveryProc.on('error', (err) => {
recoveryProc = null;
appState.busy = false; appState.busyLabel = ''; updateTray();
if (recoveryLastTried > 0) saveRecoveryProgress(recoveryLastTried, recoveryTotal);
done({ success: false, error: mt('rec.proc', { e: err.message }) }, false);
});
});
ipcMain.on('recovery:stop', () => {
if (recoveryProc) {
try { recoveryProc.kill(); } catch (_) {}
}
if (macRecovery) {
try { macRecovery.stop(); } catch (_) {}
}
});
ipcMain.on('open-external', (_e, url) => {
if (typeof url === 'string' && /^https?:\/\//i.test(url)) {
shell.openExternal(url).catch(() => {});
}
});
ipcMain.handle('verify-gumroad-license', async (_e, licenseKey) => {
const key = String(licenseKey || '').trim();
if (!key) return { ok: false, message: 'empty key' };
const body = `product_permalink=bitlockpick&license_key=${encodeURIComponent(key)}&increment_uses_count=false`;
return new Promise((resolve) => {
const req = https.request({
hostname: 'api.gumroad.com',
path: '/v2/licenses/verify',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body)
}
}, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
try {
const json = JSON.parse(data);
resolve({ ok: !!json.success, message: json.message || '' });
} catch (err) {
resolve({ ok: false, message: err.message });
}
});
});
req.on('error', (err) => resolve({ ok: false, message: err.message }));
req.write(body);
req.end();
});
});