-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
501 lines (451 loc) · 19.9 KB
/
main.js
File metadata and controls
501 lines (451 loc) · 19.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
// main.js - Electron main process for FolderVault
// Implements folder traversal, encryption/decryption, secure delete, and IPC handlers.
const { app, BrowserWindow, dialog, ipcMain, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const util = require('util');
const stream = require('stream');
// Enable live-reload in development when source files change.
// Only enable when NODE_ENV is not 'production' and the app is not packaged.
if (process.env.NODE_ENV !== 'production' && !app.isPackaged) {
try {
// Require electron-reload and watch the project directory
// Ignore node_modules, logs, dist, and test folders to avoid reloads during file operations
require('electron-reload')(__dirname, {
electron: require('electron'),
ignored: [
/node_modules/,
/logs/,
/dist/,
/test_tmp/,
/test_tmp2/,
/test_many/,
/\.log$/
]
});
console.log('Live reload enabled (development)');
} catch (e) {
// If electron-reload is not installed, ignore silently.
console.log('electron-reload not available:', e.message);
}
}
const pipeline = util.promisify(stream.pipeline);
const scrypt = util.promisify(crypto.scrypt);
const MAGIC = Buffer.from('ELECTRON'); // 8 bytes
const SALT_LEN = 16;
const IV_LEN = 12;
const AUTH_TAG_LEN = 16;
let mainWindow = null;
let cancelRequested = false;
// Controller for cooperative cancellation of long-running operations
let activeOpController = null;
// Simple log file for diagnostics (appends)
const LOG_DIR = path.join(__dirname, 'logs');
try { fs.mkdirSync(LOG_DIR, { recursive: true }); } catch (e) { /* ignore */ }
// Global error handlers to capture unexpected crashes and surface them to the UI/logs
process.on('uncaughtException', (err) => {
try { sendLog('uncaughtException:', err && err.stack ? err.stack : err && err.message ? err.message : String(err)); } catch (e) { console.error(e); }
});
process.on('unhandledRejection', (reason) => {
try { sendLog('unhandledRejection:', reason && reason.stack ? reason.stack : String(reason)); } catch (e) { console.error(e); }
});
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 1000,
minHeight: 700,
center: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
enableRemoteModule: false,
zoomFactor: 1.0
}
});
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Ensure zoom level is set to 100% (1.0) after window is ready
mainWindow.webContents.once('did-finish-load', () => {
mainWindow.webContents.setZoomFactor(1.0);
});
// Also set zoom when window is shown (in case it was restored)
mainWindow.once('show', () => {
mainWindow.webContents.setZoomFactor(1.0);
});
}
app.whenReady().then(() => {
createWindow();
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});
// Utility to send log messages to renderer
function sendLog(...parts) {
const msg = parts.join(' ');
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.send('vault-log', msg);
}
console.log(msg);
// Append to a log file for support (best-effort)
try {
const stamp = new Date().toISOString();
fs.appendFile(path.join(LOG_DIR, 'app.log'), `[${stamp}] ${msg}\n`, () => { });
} catch (e) { /* ignore */ }
}
function sendProgress(data) {
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.send('vault-progress', data);
}
}
// Transform stream that counts bytes and reports progress via a callback
const { Transform } = require('stream');
class CountingTransform extends Transform {
constructor(total = 0, onProgress = () => { }) {
super();
this.total = total;
this.seen = 0;
this.onProgress = onProgress;
}
_transform(chunk, encoding, callback) {
this.seen += chunk.length;
try { this.onProgress(this.seen, this.total); } catch (e) { /* ignore */ }
this.push(chunk);
callback();
}
}
// Async generator to walk a directory recursively
async function* walk(dir) {
const dirents = await fs.promises.readdir(dir, { withFileTypes: true });
for (const dirent of dirents) {
const res = path.resolve(dir, dirent.name);
if (dirent.isDirectory()) {
yield* walk(res);
} else if (dirent.isFile()) {
yield res;
}
}
}
// Secure delete: overwrite file with random data multiple times and unlink (best-effort)
async function secureDelete(filePath, passes = 3) {
try {
const stats = await fs.promises.stat(filePath);
const size = stats.size;
const fd = await fs.promises.open(filePath, 'r+');
try {
const chunk = 64 * 1024; // 64KB buffer
// Reuse a single buffer and fill it with random bytes to avoid many allocations
const buf = Buffer.allocUnsafe(chunk);
for (let pass = 0; pass < passes; pass++) {
let written = 0;
while (written < size) {
const toWrite = Math.min(chunk, size - written);
// Fill only the needed portion with random bytes
crypto.randomFillSync(buf, 0, toWrite);
await fd.write(buf, 0, toWrite, written);
written += toWrite;
}
// fs.promises.FileHandle may or may not expose sync(); use whichever is available
if (typeof fd.sync === 'function') {
await fd.sync();
} else {
// fallback to fsync on the numeric fd
await fs.promises.fsync(fd.fd);
}
}
} finally {
await fd.close();
}
await fs.promises.unlink(filePath);
sendLog('secureDelete: removed', filePath);
} catch (err) {
sendLog('secureDelete failed for', filePath, '-', err.message);
}
}
// Encrypt a single file -> creates filePath + '.enc'
// encryptFile supports an options object { signal } to support abortion
async function encryptFile(filePath, password, options = {}) {
const salt = crypto.randomBytes(SALT_LEN);
const iv = crypto.randomBytes(IV_LEN);
// Derive key with scrypt parameters N=16384, r=8, p=1
const key = await scrypt(password, salt, 32, { N: 16384, r: 8, p: 1 });
try {
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const outPath = `${filePath}.enc`;
const writeStream = fs.createWriteStream(outPath);
// Write header: MAGIC | SALT | IV
writeStream.write(MAGIC);
writeStream.write(salt);
writeStream.write(iv);
// Stream the file through the cipher into output (respect optional signal)
// Create read stream (support signal option in Node >= 16.7)
const readOpts = options.signal ? { signal: options.signal } : undefined;
const readStream = fs.createReadStream(filePath, readOpts);
// counting transform for per-file byte progress
const stats = await fs.promises.stat(filePath);
const totalBytes = stats.size;
const counter = new CountingTransform(totalBytes, (seen) => {
sendProgress({ type: 'file-progress', file: filePath, seen, total: totalBytes });
});
// wire abort to destroy streams quickly
const abortHandler = () => {
try { readStream.destroy(new Error('aborted')); } catch (e) { }
try { cipher.destroy(new Error('aborted')); } catch (e) { }
try { writeStream.destroy(new Error('aborted')); } catch (e) { }
};
if (options.signal) options.signal.addEventListener('abort', abortHandler, { once: true });
await pipeline(readStream, counter, cipher, writeStream);
// After pipeline completes, retrieve auth tag and append it
const authTag = cipher.getAuthTag();
await fs.promises.appendFile(outPath, authTag);
sendLog('Encrypted', filePath, '->', outPath);
return outPath;
} finally {
// Zero the key buffer to reduce leakage window
try { if (key && typeof key.fill === 'function') key.fill(0); } catch (e) { /* best-effort */ }
}
}
// Decrypt a .enc file (expects header MAGIC|SALT|IV and trailing AUTH_TAG)
// decryptFile supports options { signal } and uses an atomic write (temp+rename)
async function decryptFile(encPath, password, options = {}) {
const handle = await fs.promises.open(encPath, 'r');
try {
const stat = await handle.stat();
const fileSize = stat.size;
// Read header
const headerLen = MAGIC.length + SALT_LEN + IV_LEN;
if (fileSize < headerLen + AUTH_TAG_LEN) {
throw new Error('File too small to be valid');
}
const headerBuf = Buffer.alloc(headerLen);
await handle.read(headerBuf, 0, headerLen, 0);
const magic = headerBuf.slice(0, MAGIC.length);
if (!magic.equals(MAGIC)) {
throw new Error('Invalid file magic');
}
const salt = headerBuf.slice(MAGIC.length, MAGIC.length + SALT_LEN);
const iv = headerBuf.slice(MAGIC.length + SALT_LEN, headerLen);
// Read auth tag (last 16 bytes)
const authTagBuf = Buffer.alloc(AUTH_TAG_LEN);
await handle.read(authTagBuf, 0, AUTH_TAG_LEN, fileSize - AUTH_TAG_LEN);
const key = await scrypt(password, salt, 32, { N: 16384, r: 8, p: 1 });
try {
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTagBuf);
const outPath = encPath.endsWith('.enc') ? encPath.slice(0, -4) : `${encPath}.dec`;
const tmpPath = outPath + '.tmp-' + crypto.randomBytes(6).toString('hex');
const start = headerLen;
const end = fileSize - AUTH_TAG_LEN - 1; // inclusive end position (Node.js end is inclusive)
// Handle empty files (0 bytes of encrypted data) - end will be start - 1
// This is valid - it means the original file was empty
const hasEncryptedData = end >= start;
const totalBytes = hasEncryptedData ? (end - start + 1) : 0; // +1 because end is inclusive
// Stream decrypted output to a temp file, then fsync & rename atomically
let readStream;
let counter;
if (hasEncryptedData) {
// Normal case: file has encrypted data
const readOpts = Object.assign({ start, end }, options.signal ? { signal: options.signal } : {});
readStream = fs.createReadStream(encPath, readOpts);
counter = new CountingTransform(totalBytes, (seen) => {
sendProgress({ type: 'file-progress', file: encPath, seen, total: totalBytes });
});
} else {
// Empty file case: create an empty stream (no data to decrypt)
// Use stream.Readable which is already available via the stream module
const { Readable } = stream;
readStream = new Readable({
read() {
this.push(null); // End of stream immediately
}
});
counter = new CountingTransform(0, (seen) => {
sendProgress({ type: 'file-progress', file: encPath, seen, total: 0 });
});
}
// wire abort to destroy streams quickly
const abortHandler = () => {
try { if (readStream) readStream.destroy(new Error('aborted')); } catch (e) { }
try { decipher.destroy(new Error('aborted')); } catch (e) { }
};
if (options.signal) options.signal.addEventListener('abort', abortHandler, { once: true });
try {
const writeStream = fs.createWriteStream(tmpPath);
await pipeline(readStream, counter, decipher, writeStream);
// Ensure data is flushed to disk (best-effort)
try {
const fd = await fs.promises.open(tmpPath, 'r+');
try {
if (typeof fd.sync === 'function') await fd.sync();
else await fs.promises.fsync(fd.fd);
} finally {
await fd.close();
}
} catch (e) {
// ignore fsync failures but log
sendLog('fsync failed for', tmpPath, '-', e.message);
}
await fs.promises.rename(tmpPath, outPath);
sendLog('Decrypted', encPath, '->', outPath);
return outPath;
} catch (err) {
// If decryption fails (e.g., wrong password), clean up the temp file
try {
await fs.promises.unlink(tmpPath).catch(() => { });
sendLog('Cleaned up temp file after decryption error:', tmpPath);
} catch (e) { /* ignore cleanup errors */ }
throw err; // re-throw the original error
}
} finally {
// Zero key buffer
try { if (key && typeof key.fill === 'function') key.fill(0); } catch (e) { /* best-effort */ }
}
} finally {
await handle.close();
}
}
// IPC handlers
ipcMain.handle('choose-folder', async () => {
const res = await dialog.showOpenDialog(mainWindow, { properties: ['openDirectory'] });
if (res.canceled || res.filePaths.length === 0) return null;
return res.filePaths[0];
});
ipcMain.handle('open-app-folder', async () => {
try {
// Open the directory where the main script is located
const dir = __dirname;
await shell.openPath(dir);
sendLog('Opened app folder:', dir);
return { opened: true, path: dir };
} catch (err) {
sendLog('open-app-folder failed:', err.message);
return { opened: false, error: err.message };
}
});
ipcMain.handle('show-confirm', async (event, { title, message }) => {
try {
const res = await dialog.showMessageBox(mainWindow, {
type: 'warning',
buttons: ['Yes', 'No'],
defaultId: 1,
cancelId: 1,
title: title || 'Confirm',
message: message || ''
});
return res.response === 0;
} catch (err) {
sendLog('show-confirm failed:', err.message);
return false;
}
});
ipcMain.handle('cancel-operation', async () => {
cancelRequested = true;
// If there's an active controller, abort it to attempt to stop streaming operations
try {
if (activeOpController && typeof activeOpController.abort === 'function') {
activeOpController.abort();
}
} catch (e) { /* ignore */ }
sendLog('Operation cancellation requested');
return { cancelled: true };
});
ipcMain.handle('encrypt-folder', async (event, { folder, password, options = {} }) => {
// options: { keepOriginals: boolean, secureDelete: boolean }
cancelRequested = false;
sendLog('Starting encryption for', folder);
// create a controller for this operation to support cooperative cancellation
const controller = new AbortController();
activeOpController = controller;
let count = 0;
try {
let total = 0;
for await (const _ of walk(folder)) total++;
let processed = 0;
for await (const file of walk(folder)) {
if (cancelRequested) {
sendLog('Encryption cancelled by user');
break;
}
// Skip already encrypted files
if (file.endsWith('.enc')) {
sendLog('Skipping (already .enc):', file);
sendProgress({ type: 'file', file, action: 'skip' });
processed++;
continue;
}
sendProgress({ type: 'file', file, action: 'start', index: processed + 1, total });
try {
const encPath = await encryptFile(file, password, { signal: controller.signal });
sendProgress({ type: 'file', file, action: 'done', out: encPath });
if (!options.keepOriginals) {
if (options.secureDelete) await secureDelete(file);
else await fs.promises.unlink(file).catch(() => sendLog('unlink failed for', file));
}
count++;
} catch (err) {
sendLog('Error encrypting', file, '-', err.message);
sendProgress({ type: 'file', file, action: 'error', error: err.message });
}
processed++;
sendProgress({ type: 'progress', processed, total });
}
sendLog('Encryption complete. Files processed:', String(count));
return { success: true, processed: count };
} catch (err) {
sendLog('Encryption failed:', err.message);
return { success: false, error: err.message };
} finally {
// clear active controller for this operation
try { activeOpController = null; } catch (e) { }
}
});
ipcMain.handle('decrypt-folder', async (event, { folder, password, options = {} }) => {
// options: { keepOriginals: boolean, secureDelete: boolean }
cancelRequested = false;
sendLog('Starting decryption for', folder);
const controller = new AbortController();
activeOpController = controller;
let count = 0;
try {
let total = 0;
for await (const _ of walk(folder)) total++;
let processed = 0;
for await (const file of walk(folder)) {
if (cancelRequested) {
sendLog('Decryption cancelled by user');
break;
}
if (!file.endsWith('.enc')) {
processed++;
sendProgress({ type: 'file', file, action: 'skip' });
continue;
}
sendProgress({ type: 'file', file, action: 'start', index: processed + 1, total });
try {
const outPath = await decryptFile(file, password, { signal: controller.signal });
sendProgress({ type: 'file', file, action: 'done', out: outPath });
if (!options.keepOriginals) {
if (options.secureDelete) await secureDelete(file);
else await fs.promises.unlink(file).catch(() => sendLog('unlink failed for', file));
}
count++;
} catch (err) {
sendLog('Error decrypting', file, '-', err.message);
sendProgress({ type: 'file', file, action: 'error', error: err.message });
}
processed++;
sendProgress({ type: 'progress', processed, total });
}
sendLog('Decryption complete. Files processed:', String(count));
return { success: true, processed: count };
} catch (err) {
sendLog('Decryption failed:', err.message);
return { success: false, error: err.message };
} finally {
try { activeOpController = null; } catch (e) { }
}
});