-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
4292 lines (3830 loc) · 157 KB
/
main.js
File metadata and controls
4292 lines (3830 loc) · 157 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) ============
// Required for AppImage on Ubuntu/GNOME where FUSE sandbox is not available
// Must be called before app.whenReady()
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);
}
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);
const stmt = 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
`);
stmt.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() {
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline' 'unsafe-eval'; " + // 'unsafe-eval' nötig für react-scripts dev; in Production eigentlich nicht
"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')
},
backgroundColor: '#0a0a0a',
icon: getIconPath(),
title: 'CoreMail Desktop'
});
const isDev = process.env.NODE_ENV === 'development';
// 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 (_) {}
}
}
}
app.whenReady().then(async () => {
await recoverFromSafeStorageStore();
// 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 ============
function getAccountById(accountId) {
const accounts = store.get('accounts', []);
return accounts.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
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);
imapPool.delete(account.id);
});
connection.imap.on('close', () => {
const e = imapPool.get(account.id);
if (e?.connection === connection) imapPool.delete(account.id);
});
imapPool.set(account.id, { connection, busy: true, lastUsed: Date.now() });
return connection;
}
function releaseImapConnection(accountId, destroy = false) {
const entry = imapPool.get(accountId);
if (!entry) return;
if (destroy) {
try { entry.connection.end(); } catch (_) {}
imapPool.delete(accountId);
} else {
entry.busy = false;
entry.lastUsed = Date.now();
}
}
// Clean up all pooled connections on quit
app.on('before-quit', () => {
for (const [, entry] of imapPool) {
try { entry.connection.end(); } catch (_) {}
}
imapPool.clear();
});
// v2.8.4: Find the Sent folder by \Sent attribute or common names
async function findSentFolderName(connection) {
try {
const boxes = await connection.getBoxes();
const COMMON_SENT = ['Sent', 'Sent Items', 'Sent Mail', '[Gmail]/Sent Mail',
'INBOX.Sent', 'Gesendet', 'INBOX.Gesendet', 'Gesendete Elemente'];
const search = (boxes, prefix) => {
for (const [name, box] of Object.entries(boxes)) {
const sep = box.delimiter || '/';
const fullName = prefix ? `${prefix}${sep}${name}` : name;
if (box.attribs && (box.attribs.includes('\\Sent') || box.attribs.includes('\\sent')))
return fullName;
if (box.children) {
const found = search(box.children, fullName);
if (found) return found;
}
}
return null;
};
const byAttrib = search(boxes, '');
if (byAttrib) return byAttrib;
// Collect all folder names and try common patterns
const allNames = [];
const collect = (boxes, prefix) => {
for (const [name, box] of Object.entries(boxes)) {
const sep = box.delimiter || '/';
const fullName = prefix ? `${prefix}${sep}${name}` : name;
allNames.push(fullName);
if (box.children) collect(box.children, fullName);
}
};
collect(boxes, '');
for (const common of COMMON_SENT) {
const found = allNames.find(n => n.toLowerCase() === common.toLowerCase());
if (found) return found;
}
return null;
} catch (e) {
console.error('[Sent] findSentFolderName error:', e);
return null;
}
}
// v2.1.0: SMTP-Transporter für ein Konto erstellen (mit Anzeigename-Unterstützung)
function getSmtpTransporterForAccount(account) {
const smtp = account.smtp;
const port = parseInt(smtp.port) || 587;
// Auto-detect secure mode: port 465 = implicit TLS, 587/25 = STARTTLS
// If smtp.secure is explicitly set, respect it; otherwise derive from port.
let secure;
if (smtp.secure !== undefined && smtp.secure !== null) {
secure = smtp.secure !== false;
} else {
secure = port === 465;
}
const transporter = nodemailer.createTransport({
host: smtp.host,
port,
secure,
auth: {
user: smtp.username,
pass: smtp.password
},
tls: { rejectUnauthorized: shouldRejectUnauthorized(account) }, // strict by default, opt-in für self-signed via account.allowInsecureTLS
connectionTimeout: 15000, // 15s to connect
greetingTimeout: 10000, // 10s for SMTP greeting
socketTimeout: 30000, // 30s per socket operation
});
const email = smtp.fromEmail || smtp.username;
const displayName = account.displayName ? account.displayName.replace(/["\\\r\n]/g, '') : '';
const fromEmail = displayName ? `"${displayName}" <${email}>` : email;
return { transporter, fromEmail };
}
// v2.3.0: Improved icon path resolution
function getIconPath() {
if (app.isPackaged) {
// Try multiple locations for packaged app
const locations = [
path.join(process.resourcesPath, 'icon.png'),
path.join(process.resourcesPath, 'app.asar', 'assets', 'icon.png'),
path.join(__dirname, 'assets', 'icon.png')
];
for (const loc of locations) {
if (fs.existsSync(loc)) {
return loc;
}
}
}
return path.join(__dirname, 'assets', 'icon.png');
}
// v2.3.0: Get notification icon (transparent background)
function getNotificationIconPath() {
const iconName = 'notification.png';
if (app.isPackaged) {
const locations = [
path.join(process.resourcesPath, iconName),
path.join(process.resourcesPath, 'app.asar', 'assets', iconName),
path.join(__dirname, 'assets', iconName)
];
for (const loc of locations) {
if (fs.existsSync(loc)) {
return loc;
}
}
}
const devPath = path.join(__dirname, 'assets', iconName);
if (fs.existsSync(devPath)) {
return devPath;
}
// Fallback to regular icon if notification icon not found
return getIconPath();
}
// ============ UPDATE FUNCTIONS ============
// v6.5.0: Plattform-spezifische Asset-Suche im GitHub Release.
// Linux → .AppImage (Arch x86_64/arm64) — In-App-Update mit Hash-Check
// macOS → .dmg (Arch arm64/x64) — wird an Finder übergeben
// Windows → .exe (Arch x64) — wird an NSIS-Installer übergeben
function getPlatformAssetMatcher() {
const platform = process.platform;
if (platform === 'linux') {
return {
ext: '.appimage',
archSuffix: process.arch === 'arm64' ? 'arm64' : 'x86_64',
kind: 'appimage'
};
}
if (platform === 'darwin') {
return {
ext: '.dmg',
archSuffix: process.arch === 'arm64' ? 'arm64' : 'x64',
kind: 'dmg'
};
}
if (platform === 'win32') {
return {
ext: '.exe',
archSuffix: 'x64',
kind: 'exe'
};
}
return null;
}
async function checkForUpdates(silent = false) {
// 15-second hard timeout — raw https.get has no timeout and hangs indefinitely
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const resp = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`, {
headers: { 'User-Agent': 'CoreMail-Desktop', 'Accept': 'application/vnd.github.v3+json' },
signal: controller.signal
});
clearTimeout(timer);
if (!resp.ok) throw new Error(`GitHub API HTTP ${resp.status}`);
const release = await resp.json();
const latestVersion = release.tag_name?.replace('v', '') || '';
const matcher = getPlatformAssetMatcher();
const platformAsset = matcher
? (release.assets || []).find(a => {
const name = (a.name || '').toLowerCase();
return name.endsWith(matcher.ext) &&
name.includes(matcher.archSuffix.toLowerCase()) &&
a.browser_download_url;
})
: null;
const hasUpdate = compareVersions(latestVersion, APP_VERSION) > 0 && !!platformAsset;
const downloadUrl = platformAsset?.browser_download_url || null;
// Security v6.2.0: SHA256SUMS-Manifest aus dem Release fürs Update-Verify
const sumsAsset = (release.assets || []).find(a => a.name === 'SHA256SUMS.txt');
const sumsUrl = sumsAsset?.browser_download_url || null;
const expectedFilename = platformAsset?.name || null;
const releaseUrl = release.html_url || null;
const assetKind = matcher?.kind || null;
if (hasUpdate && !silent && mainWindow) {
mainWindow.webContents.send('update:available', { version: latestVersion, notes: release.body || '', downloadUrl, sumsUrl, expectedFilename, releaseUrl, assetKind });
}
return { success: true, currentVersion: APP_VERSION, latestVersion, hasUpdate, releaseNotes: release.body || '', downloadUrl, sumsUrl, expectedFilename, releaseUrl, assetKind, publishedAt: release.published_at };
} catch (e) {
clearTimeout(timer);
const msg = e.name === 'AbortError' ? 'Timeout — GitHub API nicht erreichbar (>15s)' : e.message;
return { success: false, error: msg, currentVersion: APP_VERSION };
}
}
function compareVersions(v1, v2) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 > p2) return 1;
if (p1 < p2) return -1;
}
return 0;
}
// Security v6.2.0: SHA-256-Manifest des Releases laden und expected hash für eine Datei extrahieren.
// Format SHA256SUMS.txt (eine Zeile pro Datei): <hex64> <filename>
async function fetchExpectedSha256(sumsUrl, expectedFilename) {
if (!sumsUrl || !expectedFilename) return null;
try {
const resp = await fetch(sumsUrl, {
headers: { 'User-Agent': 'CoreMail-Desktop' }
});
if (!resp.ok) return null;
const text = await resp.text();
for (const line of text.split(/\r?\n/)) {
const m = line.match(/^([a-f0-9]{64})\s+\*?(.+)$/i);
if (m && path.basename(m[2].trim()) === expectedFilename) return m[1].toLowerCase();
}
return null;
} catch (e) {
console.warn('[Update] SHA256SUMS-Fetch fehlgeschlagen:', e.message);
return null;
}
}
async function computeFileSha256(filePath) {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
return new Promise((resolve, reject) => {
stream.on('data', d => hash.update(d));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
async function downloadUpdate(downloadUrl, sumsUrl = null, expectedFilename = null) {
const downloadDir = app.getPath('downloads');
// v6.5.0: Dateiname richtet sich nach der erwarteten Asset-Endung —
// damit Mac-Finder die .dmg mountet und Windows-Explorer die .exe als Installer erkennt.
const matcher = getPlatformAssetMatcher();
const ext = matcher?.ext || '.AppImage';
const filename = expectedFilename || `CoreMail-Desktop-update${ext}`;
const filePath = path.join(downloadDir, filename);