-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
5129 lines (4616 loc) · 194 KB
/
Copy pathmain.js
File metadata and controls
5129 lines (4616 loc) · 194 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
const { app, BrowserWindow, ipcMain, Notification, shell, dialog, nativeImage, session, safeStorage } = require('electron');
const path = require('path');
const fs = require('fs');
const https = require('https');
const http = require('http');
const crypto = require('crypto');
const url = require('url');
const { execSync, spawn } = require('child_process');
const Store = require('electron-store');
const imapSimple = require('imap-simple');
const { simpleParser } = require('mailparser');
const nodemailer = require('nodemailer');
const fetch = require('node-fetch');
// ============ EIO FIX (v5.0.6) ============
// When launched without a terminal (desktop icon, autostart), stdout/stderr are
// closed. Any console.log() call then throws "Error: write EIO" which Electron
// catches as an uncaught exception and shows a native error dialog.
// Fix: wrap all console methods to silently swallow EIO write errors.
['log', 'warn', 'error', 'info', 'debug'].forEach((method) => {
const original = console[method].bind(console);
console[method] = (...args) => {
try {
original(...args);
} catch (e) {
if (e.code !== 'EIO') throw e;
// EIO = broken pipe / no terminal — silently ignore
}
};
});
// ============ SOCKET / IMAP ERROR HANDLER ============
// Catches uncaught exceptions from IMAP socket errors (writeAfterFIN, ECONNRESET,
// EPIPE) that bubble up from the connection pool when the server closes a kept-alive
// connection. These are transient network events — log them, don't crash.
const SILENT_ERRORS = new Set(['ECONNRESET', 'EPIPE', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED']);
process.on('uncaughtException', (err) => {
const msg = err?.message || '';
if (
SILENT_ERRORS.has(err?.code) ||
msg.includes('socket has been ended') ||
msg.includes('write after end') ||
msg.includes('writeAfterFIN') ||
msg.includes('This socket is closed') ||
msg.includes('read ECONNRESET')
) {
console.warn('[uncaughtException] IMAP/socket error (non-fatal):', msg);
return; // suppress — the pool will reconnect on next request
}
// Re-throw anything else so real bugs still surface
console.error('[uncaughtException] Fatal:', err);
throw err;
});
process.on('unhandledRejection', (reason) => {
const msg = reason?.message || String(reason);
if (
SILENT_ERRORS.has(reason?.code) ||
msg.includes('socket has been ended') ||
msg.includes('write after end') ||
msg.includes('writeAfterFIN') ||
msg.includes('This socket is closed')
) {
console.warn('[unhandledRejection] IMAP/socket error (non-fatal):', msg);
return;
}
console.error('[unhandledRejection]:', reason);
});
// ============ SANDBOX FIX (v3.0.9, verengt v6.10.0) ============
// v6.10.0: Sandbox nur noch für AppImage-Läufe deaktivieren — dort fehlt der
// SUID-Helper und Ubuntu 24.04+ blockiert unprivilegierte User-Namespaces
// (App startet sonst gar nicht). deb/rpm-Installationen bringen den
// chrome-sandbox-Helper mit korrekten Rechten mit und laufen jetzt wieder
// MIT Chromium-Sandbox — ein Renderer-Kompromiss (Mail-HTML) hat es damit
// deutlich schwerer. Muss vor app.whenReady() passieren.
// Auch im Dev-Modus (npm start/dev) deaktivieren: das electron-Binary in
// node_modules hat keinen SUID-Helper — auf Ubuntu 23.10+ (User-Namespace-
// Restriktionen) würde der Start sonst crashen.
if (process.platform === 'linux' && (process.env.APPIMAGE || process.env.APPDIR || !app.isPackaged)) {
app.commandLine.appendSwitch('no-sandbox');
app.commandLine.appendSwitch('disable-setuid-sandbox');
}
// App Version - read from package.json
const APP_VERSION = require('./package.json').version;
const GITHUB_REPO = 'Zenovs/coremail';
// Verschlüsselte Speicherung
// v4.5.6: Benutzerspezifischer Key statt hardcodiertem String.
// Der Key wird aus dem Home-Verzeichnis des Users abgeleitet — damit ist er
// pro Benutzer und Maschine einzigartig und steht nicht im Quellcode.
// Migrations-Logik: Falls die Config noch mit dem alten Key verschlüsselt ist,
// wird sie automatisch auf den neuen Key migriert.
const os = require('os');
const LEGACY_ENCRYPTION_KEY = 'coremail-secure-key-v1';
const deriveEncryptionKey = () =>
crypto.createHash('sha256')
.update(os.homedir() + '-coremail-v2')
.digest('hex');
let store;
try {
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
// Lese-Test: prüft ob der Key korrekt ist
store.get('accounts', []);
} catch (_) {
// Initiale Entschlüsselung gescheitert. Mögliche Ursachen:
// 1) Legacy-Key (alt < v4.5.6) → unten migrieren
// 2) safeStorage-Random-Key (v6.2.0–v6.3.0) → Recovery in app.whenReady() (recoverFromSafeStorageStore)
// Wir LÖSCHEN die Config-Datei NIE. Lieber leerer Fallback-Store als Datenverlust.
try {
const legacyStore = new Store({ encryptionKey: LEGACY_ENCRYPTION_KEY, name: 'coremail-config' });
const legacyData = legacyStore.store; // Gesamten Inhalt lesen
// Nur migrieren wenn wirklich Daten vorhanden — sonst würden wir die Config
// mit leerem Inhalt überschreiben wenn der Legacy-Key zufällig keinen Fehler wirft
if (!legacyData || Object.keys(legacyData).length === 0) {
throw new Error('Legacy store leer — keine Migration');
}
// Neu verschlüsseln mit dem benutzerspezifischen Key
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
store.store = legacyData;
console.log('[Store] Migration von Legacy-Key auf benutzerspezifischen Key erfolgreich.');
} catch (_) {
// Weder derived noch legacy → wahrscheinlich safeStorage-verschlüsselt
// Recovery erfolgt in app.whenReady(). Hier nur ein Fallback-Store mit anderem Namen,
// damit der globale `store` zumindest valide Methoden hat (set/get) und nichts überschreibt.
console.warn('[Store] Initial-Open fehlgeschlagen — Recovery wird in app.whenReady() versucht. Config wird NICHT gelöscht.');
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config-pending' });
}
}
let mainWindow;
// ============ FULL-TEXT-SEARCH-INDEX (SQLite + FTS5, v6.3.0) ============
// Lokaler Index aller bereits abgerufenen Mails. Sucht in <50ms, auch offline.
// Lazy-Loading: better-sqlite3 wird nur geladen wenn verfügbar; ohne fällt
// die Suche transparent auf den bisherigen IMAP-Server-Search zurück.
let searchDb = null;
let searchDbAvailable = false;
function initSearchIndex() {
try {
const Database = require('better-sqlite3');
const dbPath = path.join(app.getPath('userData'), 'coremail-search.db');
searchDb = new Database(dbPath);
searchDb.pragma('journal_mode = WAL');
searchDb.pragma('synchronous = NORMAL');
// Haupt-Tabelle: Mail-Metadaten + Suchfelder
searchDb.exec(`
CREATE TABLE IF NOT EXISTS emails (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id TEXT NOT NULL,
folder TEXT NOT NULL,
uid TEXT NOT NULL,
message_id TEXT,
subject TEXT,
from_addr TEXT,
to_addr TEXT,
cc_addr TEXT,
date INTEGER,
body TEXT,
has_attachments INTEGER DEFAULT 0,
seen INTEGER DEFAULT 0,
UNIQUE(account_id, folder, uid)
);
CREATE INDEX IF NOT EXISTS idx_emails_date ON emails(date DESC);
CREATE INDEX IF NOT EXISTS idx_emails_account ON emails(account_id, folder);
CREATE VIRTUAL TABLE IF NOT EXISTS emails_fts USING fts5(
subject, from_addr, to_addr, body,
content='emails', content_rowid='id',
tokenize='unicode61 remove_diacritics 2'
);
CREATE TRIGGER IF NOT EXISTS emails_ai AFTER INSERT ON emails BEGIN
INSERT INTO emails_fts(rowid, subject, from_addr, to_addr, body)
VALUES (new.id, new.subject, new.from_addr, new.to_addr, new.body);
END;
CREATE TRIGGER IF NOT EXISTS emails_ad AFTER DELETE ON emails BEGIN
INSERT INTO emails_fts(emails_fts, rowid, subject, from_addr, to_addr, body)
VALUES ('delete', old.id, old.subject, old.from_addr, old.to_addr, old.body);
END;
CREATE TRIGGER IF NOT EXISTS emails_au AFTER UPDATE ON emails BEGIN
INSERT INTO emails_fts(emails_fts, rowid, subject, from_addr, to_addr, body)
VALUES ('delete', old.id, old.subject, old.from_addr, old.to_addr, old.body);
INSERT INTO emails_fts(rowid, subject, from_addr, to_addr, body)
VALUES (new.id, new.subject, new.from_addr, new.to_addr, new.body);
END;
`);
searchDbAvailable = true;
console.log('[Search] FTS5-Index initialisiert:', dbPath);
} catch (e) {
searchDbAvailable = false;
console.warn('[Search] better-sqlite3 nicht verfügbar — Volltextsuche fällt auf Server-Suche zurück:', e.message);
}
}
// Stripped-down Body extrahieren für den Index (HTML → Text, Limit 50 KB pro Mail)
function htmlToSearchText(html) {
if (!html) return '';
const noScripts = String(html).replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, ' ');
const noTags = noScripts.replace(/<[^>]+>/g, ' ');
const decoded = noTags.replace(/&[a-z]+;/gi, ' ').replace(/&#\d+;/g, ' ');
return decoded.replace(/\s+/g, ' ').trim().slice(0, 50000);
}
let indexEmailStmt = null; // einmal vorbereitet — prepare() pro Mail ist beim Batch-Indexieren unnötiger Parse-Aufwand
function indexEmailInSearch({ accountId, folder, uid, messageId, subject, from, to, cc, date, body, html, hasAttachments, seen }) {
if (!searchDbAvailable || !searchDb) return false;
try {
const bodyText = (body && String(body).trim().length) ? String(body).slice(0, 50000) : htmlToSearchText(html);
if (!indexEmailStmt) {
indexEmailStmt = searchDb.prepare(`
INSERT INTO emails (account_id, folder, uid, message_id, subject, from_addr, to_addr, cc_addr, date, body, has_attachments, seen)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(account_id, folder, uid) DO UPDATE SET
subject=excluded.subject,
from_addr=excluded.from_addr,
to_addr=excluded.to_addr,
cc_addr=excluded.cc_addr,
date=excluded.date,
body=excluded.body,
has_attachments=excluded.has_attachments,
seen=excluded.seen
`);
}
indexEmailStmt.run(
String(accountId), String(folder), String(uid), messageId || null,
subject || '', from || '', to || '', cc || '',
date ? new Date(date).getTime() : 0,
bodyText, hasAttachments ? 1 : 0, seen ? 1 : 0
);
return true;
} catch (e) {
console.warn('[Search] indexEmail-Fehler:', e.message);
return false;
}
}
function searchEmailsFTS({ query, accountIds = [], limit = 50 }) {
if (!searchDbAvailable || !searchDb) return { success: false, error: 'Search-Index nicht verfügbar' };
try {
// Sanitize Query für FTS5: Sonderzeichen die FTS5 als Operatoren liest in Quotes setzen.
const safeQuery = query.trim().split(/\s+/).map(token => {
// Numerisch oder simples Wort: belassen (erlaubt Prefix-Matches mit *)
if (/^[a-zA-Z0-9äöüÄÖÜß]+$/.test(token)) return token + '*';
// Sonst quoten (alles im Token wird als Phrase gesucht)
return '"' + token.replace(/"/g, '""') + '"';
}).join(' ');
let sql = `
SELECT e.account_id, e.folder, e.uid, e.message_id, e.subject, e.from_addr, e.to_addr, e.date, e.has_attachments, e.seen,
snippet(emails_fts, 3, '<mark>', '</mark>', '…', 12) AS snippet,
rank
FROM emails_fts
JOIN emails e ON e.id = emails_fts.rowid
WHERE emails_fts MATCH ?
`;
const params = [safeQuery];
if (accountIds.length > 0) {
sql += ` AND e.account_id IN (${accountIds.map(() => '?').join(',')})`;
params.push(...accountIds);
}
sql += ` ORDER BY rank LIMIT ?`;
params.push(limit);
const rows = searchDb.prepare(sql).all(...params);
return {
success: true,
results: rows.map(r => ({
accountId: r.account_id,
folder: r.folder,
uid: r.uid,
messageId: r.message_id,
subject: r.subject,
from: r.from_addr,
to: r.to_addr,
date: r.date ? new Date(r.date).toISOString() : null,
hasAttachments: !!r.has_attachments,
seen: !!r.seen,
snippet: r.snippet
}))
};
} catch (e) {
console.error('[Search] FTS-Query-Fehler:', e.message);
return { success: false, error: e.message };
}
}
// Security: Strict Content-Security-Policy for renderer (defense-in-depth).
// Allowed: self for scripts/styles/images/fonts, data: for inline images, https: for tracker-image opt-in.
// External fetches (Microsoft Graph, GitHub API, Google Fonts) are explicitly listed.
function setupCSP() {
const isDev = process.env.NODE_ENV === 'development';
// 'unsafe-eval' braucht nur der react-scripts-Dev-Server. Im Production-Build
// wird es entfernt, damit eingeschleuster Code nicht per eval() laufen kann.
const scriptSrc = isDev
? "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
: "script-src 'self' 'unsafe-inline'; ";
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self'; " +
scriptSrc +
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
"font-src 'self' data: https://fonts.gstatic.com; " +
"img-src 'self' data: blob: https: http:; " + // Mail-Bilder erlauben (sind in Iframe-Sandbox)
"connect-src 'self' https://api.github.com https://graph.microsoft.com https://login.microsoftonline.com https://*.outlook.com; " +
"frame-src 'self' data:; " + // EmailHtmlFrame nutzt srcDoc (data:)
"object-src 'none'; " +
"base-uri 'none'"
]
}
});
});
}
function createWindow() {
setupCSP();
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 1000,
minHeight: 700,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js'),
// Mail-Client muss auch im Tray/minimiert weitersynchronisieren.
// Ohne dies drosselt/friert Chromium die setInterval-Timer des
// Renderers ein, sobald das Fenster verdeckt ist → Background-Sync
// stoppt (App.js:syncAllAccounts läuft dann faktisch nie).
backgroundThrottling: false
},
backgroundColor: '#0a0a0a',
icon: getIconPath(),
title: 'CoreMail Desktop'
});
const isDev = process.env.NODE_ENV === 'development';
// Security: Fenster-Öffnen und Navigation absichern (defense-in-depth).
// Ein window.open / target=_blank aus einer (bösartigen) Mail darf kein
// Electron-Fenster mit Node-Kontext öffnen; externe Links gehen in den
// System-Browser, In-App-Navigation bleibt auf die App beschränkt.
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//i.test(url) || url.startsWith('mailto:')) {
shell.openExternal(url);
}
return { action: 'deny' };
});
const allowNavigation = (event, url) => {
const ok = isDev
? url.startsWith('http://localhost:3000')
: (url.startsWith('file://') || url.startsWith('data:text/html'));
if (!ok) {
event.preventDefault();
if (/^https?:\/\//i.test(url) || url.startsWith('mailto:')) shell.openExternal(url);
}
};
mainWindow.webContents.on('will-navigate', allowNavigation);
mainWindow.webContents.on('will-redirect', allowNavigation);
// Kein Attach von untrusted WebContents (z.B. eingebettete Frames) mit Node
mainWindow.webContents.on('will-attach-webview', (event, webPreferences) => {
delete webPreferences.preload;
webPreferences.nodeIntegration = false;
webPreferences.contextIsolation = true;
});
// Debug logging for loading issues (v2.4.1)
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error(`[CoreMail] Failed to load: ${errorCode} - ${errorDescription}`);
console.error(`[CoreMail] URL: ${validatedURL}`);
});
mainWindow.webContents.on('did-finish-load', () => {
console.log('[CoreMail] Page loaded successfully');
});
// Handle render process crashes
let crashCount = 0;
mainWindow.webContents.on('render-process-gone', (event, details) => {
console.error('[CoreMail] Render process gone:', details.reason);
crashCount++;
// Max 3 Neustarts, danach aufgeben (verhindert Endlosschleife bei TMPDIR-Fehler)
if (details.reason !== 'killed' && crashCount <= 3) {
setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.reload();
}
}, 1000);
} else if (crashCount > 3) {
console.error('[CoreMail] Renderer crasht wiederholt — kein weiterer Neustart.');
}
});
mainWindow.webContents.on('unresponsive', () => {
console.error('[CoreMail] Window became unresponsive');
});
mainWindow.webContents.on('responsive', () => {
console.log('[CoreMail] Window is responsive again');
});
if (isDev) {
mainWindow.loadURL('http://localhost:3000');
mainWindow.webContents.openDevTools();
} else {
// Production: Load from build directory (v2.4.1 - improved path handling)
const indexPath = path.join(__dirname, 'build', 'index.html');
console.log('[CoreMail] Loading production build from:', indexPath);
// Check if file exists
if (fs.existsSync(indexPath)) {
mainWindow.loadFile(indexPath).catch(err => {
console.error('[CoreMail] Error loading index.html:', err);
});
} else {
console.error('[CoreMail] index.html not found at:', indexPath);
// Show error in window
mainWindow.loadURL(`data:text/html,<h1>Error: Build not found</h1><p>Expected: ${indexPath}</p>`);
}
}
mainWindow.on('closed', () => {
mainWindow = null;
});
// Context menu für Kopieren/Einfügen in der gesamten App
mainWindow.webContents.on('context-menu', (e, params) => {
const { Menu, MenuItem } = require('electron');
const menu = new Menu();
if (params.selectionText) {
menu.append(new MenuItem({ label: 'Kopieren', role: 'copy' }));
}
if (params.isEditable) {
menu.append(new MenuItem({ label: 'Ausschneiden', role: 'cut' }));
menu.append(new MenuItem({ label: 'Einfügen', role: 'paste' }));
menu.append(new MenuItem({ label: 'Alles auswählen', role: 'selectAll' }));
}
if (params.linkURL) {
const safeUrl = params.linkURL;
const isSafeUrl = safeUrl.startsWith('https://') || safeUrl.startsWith('http://') || safeUrl.startsWith('mailto:');
if (isSafeUrl) {
menu.append(new MenuItem({ label: 'Link öffnen', click: () => shell.openExternal(safeUrl) }));
}
menu.append(new MenuItem({ label: 'Link kopieren', click: () => require('electron').clipboard.writeText(params.linkURL) }));
}
if (menu.items.length > 0) menu.popup();
});
// Auto-Update Check on startup if enabled
const settings = store.get('appSettings', {});
if (settings.autoCheckUpdates !== false) {
setTimeout(() => {
checkForUpdates(true); // Silent check
}, 5000);
}
}
// v5.0.8: Set app identity before window creation so Linux WM_CLASS matches
// the StartupWMClass in the .desktop file → taskbar shows the correct icon
app.setName('coremail-desktop');
app.setAppUserModelId('com.coremail.desktop');
// v6.3.1 — Rollback der safeStorage-Migration aus v6.2.0.
// Grund: wenn safeStorage später nicht mehr entschlüsseln kann (Keyring-Reset,
// neue Linux-Session, Wallet-Neuinstallation), war die Config nicht mehr lesbar
// und Konten gingen verloren.
//
// Diese Recovery-Funktion:
// 1) Falls coremail-keyring.enc existiert → safeStorage entschlüsseln, Daten lesen,
// mit derived-key neu speichern, Keyring-Datei wegräumen.
// 2) Sollte safeStorage scheitern, aber die Config-Datei ist mit derived-key
// lesbar (z.B. weil v6.2.0 nie wirklich migriert hat) → nichts tun.
// 3) Sind beide Pfade tot, lassen wir die Datei in Ruhe (kein destruktives Reset).
async function recoverFromSafeStorageStore() {
const userDataPath = app.getPath('userData');
const keyFilePath = path.join(userDataPath, 'coremail-keyring.enc');
// Wenn keine Keyring-Datei vorhanden ist → nichts zu tun, derived-key passt
if (!fs.existsSync(keyFilePath)) {
return;
}
console.log('[Store-Recovery] Keyring-Datei gefunden — versuche Recovery der safeStorage-Daten…');
let canUseSafeStorage = false;
try { canUseSafeStorage = safeStorage.isEncryptionAvailable(); } catch (_) {}
if (!canUseSafeStorage) {
console.warn('[Store-Recovery] safeStorage nicht verfügbar — Keyring-Datei bleibt für späteren Recovery-Versuch.');
return;
}
let recoveredData = null;
try {
const encryptedKey = fs.readFileSync(keyFilePath);
const safeKey = safeStorage.decryptString(encryptedKey);
const safeStore = new Store({ encryptionKey: safeKey, name: 'coremail-config' });
recoveredData = safeStore.store;
if (!recoveredData || (typeof recoveredData === 'object' && Object.keys(recoveredData).length === 0)) {
throw new Error('Wiederhergestellte Daten sind leer');
}
} catch (e) {
console.warn('[Store-Recovery] safeStorage-Entschlüsselung fehlgeschlagen:', e.message);
return;
}
// Daten sind gerettet — jetzt mit derived-key neu speichern
try {
const configPath = path.join(userDataPath, 'coremail-config.json');
const backupPath = configPath + '.safestorage-backup';
if (fs.existsSync(configPath)) {
fs.copyFileSync(configPath, backupPath);
}
try { fs.unlinkSync(configPath); } catch (_) {}
const derivedStore = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
derivedStore.store = recoveredData;
const verifyAccounts = derivedStore.get('accounts', null);
if (!Array.isArray(verifyAccounts)) {
throw new Error(`Verifikation fehlgeschlagen — accounts ist kein Array`);
}
store = derivedStore;
try { fs.unlinkSync(keyFilePath); } catch (_) {}
console.log(`[Store-Recovery] ${verifyAccounts.length} Konten erfolgreich zum derived-key zurückmigriert.`);
} catch (e) {
console.error('[Store-Recovery] Rückmigration fehlgeschlagen:', e.message);
const configPath = path.join(userDataPath, 'coremail-config.json');
const backupPath = configPath + '.safestorage-backup';
if (!fs.existsSync(configPath) && fs.existsSync(backupPath)) {
try { fs.copyFileSync(backupPath, configPath); } catch (_) {}
}
}
}
// ── v6.13.0: Config-Verschlüsselung mit OS-Schlüsselbund (safeStorage v2) ────
// NUR auf macOS/Windows: Keychain bzw. DPAPI sind dort zuverlässig. Linux
// behält BEWUSST den derived-Key — die v6.2.0-Migration hat dort real Konten
// zerstört (libsecret/KWallet vergisst Sessions, siehe Postmortem v6.3.1).
// Prinzipien aus dem Postmortem:
// - NIE destruktiv: Backup vor der Migration bleibt dauerhaft liegen,
// neue Datei wird erst nach Read-Back-Verifikation atomar eingetauscht.
// - Bei JEDEM Fehler: unverändert beim bisherigen Schema bleiben.
// - Keyfile wird ZULETZT geschrieben — ein Crash mittendrin lässt die
// alte Config unangetastet (Selbstheilung räumt Reste weg).
const SAFESTORAGE_V2_KEYFILE = 'coremail-keyring-v2.enc';
async function migrateToSafeStorageV2() {
if (process.platform === 'linux') return;
let available = false;
try { available = safeStorage.isEncryptionAvailable(); } catch (_) {}
if (!available) return;
const userDataPath = app.getPath('userData');
const keyFilePath = path.join(userDataPath, SAFESTORAGE_V2_KEYFILE);
const configPath = path.join(userDataPath, 'coremail-config.json');
const backupPath = configPath + '.pre-safestorage-v2';
const tmpName = 'coremail-config-v2tmp';
const tmpPath = path.join(userDataPath, tmpName + '.json');
const derivedReadable = () => {
try {
const t = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
return Object.keys(t.store).length > 0 ? t : null;
} catch (_) { return null; }
};
// ── Fall 1: v2 bereits aktiv → Store mit Schlüsselbund-Key öffnen ──────────
if (fs.existsSync(keyFilePath)) {
try {
const key = safeStorage.decryptString(fs.readFileSync(keyFilePath));
const s = new Store({ encryptionKey: key, name: 'coremail-config' });
s.get('accounts', []); // Lese-Test — wirft bei falschem Key
store = s;
invalidateAccountsCache();
console.log('[Store] safeStorage-v2 aktiv (OS-Schlüsselbund).');
// Das Migrations-Backup ist mit dem ableitbaren Alt-Key verschlüsselt —
// dauerhaft neben der starken Config würde es deren Schutz aushebeln.
// Nach 30 Tagen stabilen v2-Betriebs wird es darum entfernt.
try {
if (fs.existsSync(backupPath)) {
const ageDays = (Date.now() - fs.statSync(backupPath).mtimeMs) / 86400000;
if (ageDays > 30) {
fs.unlinkSync(backupPath);
console.log('[Store] Migrations-Backup nach 30 Tagen v2-Betrieb entfernt.');
}
}
} catch (_) {}
return;
} catch (e) {
console.error('[Store] v2-Keyfile vorhanden, aber Öffnen fehlgeschlagen:', e.message);
// Selbstheilung: Wenn die Config in Wahrheit noch derived-lesbar ist
// (z.B. Crash zwischen Migrationsschritten), Keyfile-Rest entfernen.
const d = derivedReadable();
if (d) {
try { fs.unlinkSync(keyFilePath); } catch (_) {}
store = d;
invalidateAccountsCache();
console.warn('[Store] Keyfile-Rest entfernt — derived-Store bleibt aktiv.');
return;
}
// Config v2-verschlüsselt, aber Schlüsselbund gibt den Key nicht her
// (anderes Login, Keychain-Reset): NIE Daten zerstören — die aktuelle
// Config wird BEISEITEGELEGT (nicht überschrieben), erst dann das
// Backup eingespielt. Der Nutzer wird sichtbar informiert, weil das
// Backup vom Migrationstag stammen kann (Review-Befund v6.13.0).
if (fs.existsSync(backupPath)) {
try {
const lockedPath = configPath + '.v2-locked-' + Date.now();
if (fs.existsSync(configPath)) fs.renameSync(configPath, lockedPath);
fs.copyFileSync(backupPath, configPath);
const d2 = derivedReadable();
if (d2) {
try { fs.unlinkSync(keyFilePath); } catch (_) {}
store = d2;
invalidateAccountsCache();
const backupDate = new Date(fs.statSync(backupPath).mtimeMs).toLocaleDateString('de-DE');
console.warn('[Store] Aus pre-safestorage-v2-Backup wiederhergestellt (Stand: ' + backupDate + ').');
addLogEntry('settings', 'Schlüsselbund-Zugriff fehlgeschlagen — Backup wiederhergestellt', `Stand: ${backupDate}; neuere Config gesichert als ${path.basename(lockedPath)}`);
dialog.showMessageBox({
type: 'warning',
title: 'CoreMail — Konten wiederhergestellt',
message: 'Der Zugriff auf den OS-Schlüsselbund ist fehlgeschlagen.',
detail: `CoreMail hat deine Konten aus einem Backup vom ${backupDate} wiederhergestellt. Änderungen seit diesem Datum (neue Konten, Einstellungen) können fehlen.\n\nDie neuere, aktuell nicht lesbare Konfiguration wurde NICHT gelöscht, sondern gesichert als:\n${path.basename(lockedPath)}`,
buttons: ['OK']
}).catch(() => {});
return;
}
// Backup selbst nicht lesbar → alles zurück wie es war
try { fs.unlinkSync(configPath); } catch (_) {}
if (fs.existsSync(lockedPath)) fs.renameSync(lockedPath, configPath);
} catch (_) {}
}
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config-pending' });
console.error('[Store] v2-Recovery nicht möglich — Pending-Fallback, Config bleibt unangetastet.');
dialog.showMessageBox({
type: 'error',
title: 'CoreMail — Zugangsdaten nicht verfügbar',
message: 'Der Zugriff auf den OS-Schlüsselbund ist fehlgeschlagen.',
detail: 'Deine verschlüsselte Konfiguration bleibt unverändert auf der Festplatte erhalten, kann aber ohne den Schlüssel nicht gelesen werden. Starte die App neu, nachdem der Schlüsselbund wieder verfügbar ist (z.B. nach erneutem Login).',
buttons: ['OK']
}).catch(() => {});
return;
}
}
// ── Fall 2: Migration derived → v2 ─────────────────────────────────────────
try {
// Nur migrieren, wenn der aktuelle Store der echte derived-Store mit
// Daten ist (nicht der Pending-Fallback aus dem Modul-Load).
if (!store || (store.path || '').includes('pending')) {
// Gürtel+Hosenträger: Sollte die Config aus irgendeinem Grund
// unlesbar sein, obwohl kein v2-Keyfile existiert, und ein Backup
// liegt vor → Restore versuchen statt dauerhaft auf Pending zu hängen.
if (store && (store.path || '').includes('pending') && fs.existsSync(backupPath) && !derivedReadable()) {
try {
fs.copyFileSync(backupPath, configPath);
const d = derivedReadable();
if (d) {
store = d;
invalidateAccountsCache();
console.warn('[Store] Unlesbare Config aus pre-safestorage-v2-Backup wiederhergestellt.');
}
} catch (_) {}
}
return;
}
const currentData = store.store;
if (!currentData || Object.keys(currentData).length === 0) return;
// 1) Dauerhaftes Backup der bisherigen Config
if (fs.existsSync(configPath)) fs.copyFileSync(configPath, backupPath);
// 2) Zufalls-Key; neue Datei unter TEMPORÄREM Namen schreiben + verifizieren
const newKey = crypto.randomBytes(32).toString('hex');
try { fs.unlinkSync(tmpPath); } catch (_) {}
const tmp = new Store({ encryptionKey: newKey, name: tmpName });
tmp.store = currentData;
const check = new Store({ encryptionKey: newKey, name: tmpName });
const wantAccounts = JSON.stringify(currentData.accounts ?? null);
if (JSON.stringify(check.get('accounts', null)) !== wantAccounts) {
throw new Error('Read-Back-Verifikation fehlgeschlagen');
}
// 3) Keyfile VOR dem Tausch schreiben (inkl. Roundtrip-Prüfung):
// Crash nach diesem Schritt, aber vor dem Rename → nächster Start
// landet in Fall 1, Decrypt klappt, Config ist noch derived-lesbar
// → Selbstheilung entfernt den Keyfile-Rest. Crash NACH dem Rename
// → Fall 1 öffnet normal. Kein Fenster mehr, in dem die Config
// v2-verschlüsselt, der Key aber verloren ist (Review-Befund v6.13.0).
fs.writeFileSync(keyFilePath, safeStorage.encryptString(newKey));
if (safeStorage.decryptString(fs.readFileSync(keyFilePath)) !== newKey) {
throw new Error('Keyfile-Roundtrip fehlgeschlagen');
}
// 4) Atomarer Tausch
fs.renameSync(tmpPath, configPath);
store = new Store({ encryptionKey: newKey, name: 'coremail-config' });
invalidateAccountsCache();
console.log('[Store] Migration auf safeStorage-v2 erfolgreich (Backup: ' + backupPath + ').');
addLogEntry('settings', 'Zugangsdaten-Verschlüsselung auf OS-Schlüsselbund umgestellt', 'Backup: coremail-config.json.pre-safestorage-v2');
} catch (e) {
console.error('[Store] safeStorage-v2-Migration fehlgeschlagen — bisheriges Schema bleibt aktiv:', e.message);
try { fs.unlinkSync(tmpPath); } catch (_) {}
try { fs.unlinkSync(keyFilePath); } catch (_) {}
// Sicherstellen, dass der derived-Store lesbar ist; sonst Backup zurück
if (!derivedReadable() && fs.existsSync(backupPath)) {
try { fs.copyFileSync(backupPath, configPath); } catch (_) {}
}
try {
store = new Store({ encryptionKey: deriveEncryptionKey(), name: 'coremail-config' });
invalidateAccountsCache();
} catch (e2) {
console.error('[Store] Fallback-Öffnen fehlgeschlagen:', e2.message);
}
}
}
// v6.13.0: Nur eine Instanz — zwei parallele Prozesse könnten sich die
// Store-Migration zerschiessen (Review-Befund), und ein Mail-Client braucht
// ohnehin nur ein Fenster. Zweitstart fokussiert die bestehende Instanz.
if (!app.requestSingleInstanceLock()) {
app.quit();
}
app.on('second-instance', () => {
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
}
});
app.whenReady().then(async () => {
await recoverFromSafeStorageStore();
await migrateToSafeStorageV2();
// Aufräumen: leerer Fallback-Store aus Modul-Load (falls vorhanden)
try {
const pendingPath = path.join(app.getPath('userData'), 'coremail-config-pending.json');
if (fs.existsSync(pendingPath)) fs.unlinkSync(pendingPath);
} catch (_) {}
initSearchIndex();
createWindow();
// Sync system launcher icons in background (non-blocking)
setTimeout(() => syncSystemIcons(), 3000);
// Logbuch: App-Start protokollieren
addLogEntry('app_start', `CoreMail v${APP_VERSION} gestartet`, `Plattform: ${process.platform}`);
// Zeitversetzt senden: alle 30s prüfen
const scheduledEmailInterval = setInterval(() => processScheduledEmails(), 30000);
// v6.6.0: Snooze-Erinnerungen — gleicher Tick wie scheduledEmails
const snoozeInterval = setInterval(() => processSnoozes(), 30000);
app.on('before-quit', () => {
clearInterval(scheduledEmailInterval);
clearInterval(snoozeInterval);
});
});
// v3.0.3: Refresh Linux system launcher icons from GitHub so the correct icon
// appears in the app drawer after an in-app update (no re-install needed).
function syncSystemIcons() {
if (process.platform !== 'linux') return;
try {
const { execFile } = require('child_process');
const os = require('os');
const home = os.homedir();
const ICON_BASE = 'https://raw.githubusercontent.com/Zenovs/coremail/initial-code/public/icons';
const SIZES = [16, 32, 64, 128, 256, 512];
const APP_VERSION = app.getVersion();
const versionKey = `iconsVersion`;
const storedVersion = store.get(versionKey, '0');
// Only update if app version changed (avoids unnecessary network requests)
if (storedVersion === APP_VERSION) return;
const downloadFile = (url, dest) => new Promise((resolve) => {
const file = fs.createWriteStream(dest);
https.get(url, (res) => {
res.pipe(file);
file.on('finish', () => { file.close(); resolve(); });
}).on('error', () => { file.close(); resolve(); });
});
(async () => {
try {
for (const sz of SIZES) {
const dir = path.join(home, `.local/share/icons/hicolor/${sz}x${sz}/apps`);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
await downloadFile(`${ICON_BASE}/icon-${sz}.png`, path.join(dir, 'coremail.png'));
}
// pixmaps (used as absolute icon path in .desktop file)
const pixDir = path.join(home, '.local/share/pixmaps');
if (!fs.existsSync(pixDir)) fs.mkdirSync(pixDir, { recursive: true });
const pixIconPath = path.join(pixDir, 'coremail.png');
await downloadFile(`${ICON_BASE}/icon-256.png`, pixIconPath);
// Rewrite .desktop file — always create/update after version change
const desktopDir = path.join(home, '.local/share/applications');
if (!fs.existsSync(desktopDir)) fs.mkdirSync(desktopDir, { recursive: true });
const desktopFile = path.join(desktopDir, 'coremail.desktop');
const appImagePath = path.join(home, '.local/bin/coremail-desktop');
// v6.3.6: TMPDIR auf ~/.cache setzen damit AppImage-Extraktion nicht in /tmp landet.
// t2linux/Ubuntu-Kernel blockiert ESRCH für Shared Memory aus /tmp-Prozessen.
const extractTmpDir = path.join(home, '.cache', 'coremail-extract');
try { fs.mkdirSync(extractTmpDir, { recursive: true }); } catch (_) {}
const desktopContent = [
'[Desktop Entry]',
'Version=1.0',
'Type=Application',
'Name=CoreMail Desktop',
'Comment=E-Mail Client für Linux',
`Exec=env APPIMAGE_EXTRACT_AND_RUN=1 TMPDIR=${extractTmpDir} ${appImagePath} --no-sandbox`,
`Icon=${pixIconPath}`,
'Terminal=false',
'Categories=Network;Email;Office;',
'StartupNotify=true',
'StartupWMClass=coremail-desktop',
'Keywords=email;mail;imap;smtp;',
''
].join('\n');
fs.writeFileSync(desktopFile, desktopContent);
try { fs.chmodSync(desktopFile, 0o755); } catch (_) {}
// Refresh caches
execFile('gtk-update-icon-cache', ['-f', path.join(home, '.local/share/icons/hicolor')], () => {});
execFile('update-desktop-database', [path.join(home, '.local/share/applications')], () => {});
store.set(versionKey, APP_VERSION);
console.log('[Icons] System launcher icons updated to v' + APP_VERSION);
} catch (e) {
console.warn('[Icons] Could not update system icons:', e.message);
}
})();
} catch (e) {
console.warn('[Icons] syncSystemIcons error:', e.message);
}
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ============ HELPER FUNCTIONS ============
// Accounts in-memory cachen — getAccountById läuft in praktisch jedem
// IPC-Handler und entschlüsselte sonst jedes Mal die komplette Config.
let accountsCache = null;
function invalidateAccountsCache() { accountsCache = null; }
function getCachedAccounts() {
if (!accountsCache) accountsCache = store.get('accounts', []);
return accountsCache;
}
function getAccountById(accountId) {
return getCachedAccounts().find(acc => acc.id === accountId);
}
// Security helper: returns rejectUnauthorized based on per-account flag.
// Default (flag not set) → true (validates certs).
// Bestehende Konten werden bei load_accounts auf allowInsecureTLS: true migriert,
// damit sich an deren Verhalten nichts ändert.
function shouldRejectUnauthorized(account) {
return !(account?.allowInsecureTLS === true);
}
// List-Unsubscribe (RFC 2369 + RFC 8058) aus Mail-Headern extrahieren.
// Liefert { mailto, http, oneClick } — alles optional. oneClick=true bedeutet
// RFC 8058: ein POST genügt (kein Browser-Tab, keine Bestätigung), wenn der
// Server `List-Unsubscribe-Post: List-Unsubscribe=One-Click` mitsendet.
function extractListUnsubscribe(parsedMail) {
if (!parsedMail) return null;
let raw = null;
try {
if (parsedMail.headers && typeof parsedMail.headers.get === 'function') {
raw = parsedMail.headers.get('list-unsubscribe');
}
} catch (_) {}
if (!raw && parsedMail.headerLines) {
const line = parsedMail.headerLines.find(h => h.key === 'list-unsubscribe');
if (line) raw = line.line.replace(/^list-unsubscribe:\s*/i, '');
}
if (!raw || typeof raw !== 'string') return null;
const items = raw.match(/<([^>]+)>/g) || [];
let mailto = null, http = null;
for (const item of items) {
const v = item.slice(1, -1).trim();
if (v.startsWith('mailto:')) mailto = mailto || v;
else if (v.startsWith('http://') || v.startsWith('https://')) http = http || v;
}
if (!mailto && !http) return null;
let oneClick = false;
try {
const post = parsedMail.headers?.get?.('list-unsubscribe-post');
if (post && /one-click/i.test(String(post))) oneClick = true;
} catch (_) {}
return { mailto, http, oneClick };
}
// v2.0.0: IMAP-Konfiguration für ein Konto erstellen
function getImapConfigForAccount(account) {
return {
imap: {
user: account.imap.username,
password: account.imap.password,
host: account.imap.host,
port: parseInt(account.imap.port) || 993,
tls: account.imap.tls !== false,
authTimeout: 15000,
connTimeout: 30000,
tlsOptions: { rejectUnauthorized: shouldRejectUnauthorized(account) }
}
};
}
// ── IMAP Connection Pool ────────────────────────────────────────────────────
// Keeps one live IMAP connection per account, reconnects transparently on error.
// Avoids the TCP handshake + TLS + auth overhead (typically 1–3s) on every fetch.
const imapPool = new Map(); // accountId → { connection, busy }
const IMAP_IDLE_TTL = 5 * 60 * 1000; // close connections idle for > 5 minutes
const imapPoolSweepInterval = setInterval(() => {
const now = Date.now();
for (const [id, entry] of imapPool) {
if (!entry.busy && (now - entry.lastUsed) > IMAP_IDLE_TTL) {
try { entry.connection.end(); } catch (_) {}
imapPool.delete(id);
console.log(`[IMAPPool] Closed idle connection for ${id}`);
}
}
}, 60_000);
async function getPooledImapConnection(account) {
const entry = imapPool.get(account.id);
if (entry && !entry.busy) {
try {
entry.busy = true;
entry.lastUsed = Date.now();
return entry.connection;
} catch (_) {
imapPool.delete(account.id);
}
}
// Create a new connection and attach an error listener so socket errors
// don't bubble up as uncaught exceptions — the pool will recreate on next use.
const config = getImapConfigForAccount(account);
const connection = await imapSimple.connect(config);
connection.imap.on('error', (err) => {
console.warn(`[IMAPPool] socket error for ${account.id}:`, err?.message);
const e = imapPool.get(account.id);
if (e?.connection === connection) imapPool.delete(account.id);
});
connection.imap.on('close', () => {
const e = imapPool.get(account.id);
if (e?.connection === connection) imapPool.delete(account.id);
});
const current = imapPool.get(account.id);
if (current?.busy) {
// Pool-Slot ist gerade belegt — Überlauf-Verbindung nicht registrieren,
// sonst würde der Release des anderen Aufrufers unsere Verbindung freigeben.
connection.__overflow = true;
} else {
if (current) { try { current.connection.end(); } catch (_) {} }
imapPool.set(account.id, { connection, busy: true, lastUsed: Date.now() });
}
return connection;
}
function releaseImapConnection(accountId, destroy = false, connection = null) {
if (connection?.__overflow) {
try { connection.end(); } catch (_) {}
return;
}
const entry = imapPool.get(accountId);
if (!entry) return;