-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webmail.js
2787 lines (2531 loc) · 102 KB
/
webmail.js
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
/* Global variables */
var attempted_auth = false;
var authenticated = false;
var capabilities = [];
var authcapabilities = [];
var ws = null;
var ever_session_connected = false;
var session_connected = false;
var checkedNotifyPerm = false;
var folders = null;
var gotlist = false;
var trashFolder = null;
var junkFolder = null;
var viewPreview = true;
var selectedFolder = null;
var pageNumber = 1;
/* Set default page size based on screen size */
var sortOrder = null;
var simpleFilter = null;
var pagesize = window.screen.height > 800 ? 25 : window.screen.height > 600 ? 15 : 10;
var viewRaw = false;
var viewHTML = true;
var allowExternalRequests = false;
var lastMoveTarget = null;
var totalSelected = 0;
var unseenSelected = 0;
var allSelected = false;
var lastNumPages = 0;
var currentUID = 0;
var doingExport = false;
/* For replies */
var lastfrom = null;
var lastto = null;
var lastcc = null;
var lastsubject = null;
var lastbody = null;
var lastsent = null;
var lastmsgid = null;
var references = null;
function resetConnection() {
attempted_auth = false;
authenticated = false;
capabilities = [];
authcapabilities = [];
ws = null;
}
function disconnect() {
console.log("Disconnecting...");
if (ws !== null) {
ws.close();
resetConnection();
}
}
var autoreconnect = null; /* Must be declared for tryAutoReconnect */
function tryAutoReconnect() {
if (!window.navigator.onLine) {
console.warn("Client is offline...");
return;
}
console.log("Attempting autoreconnect");
clearStatus();
setStatus("Attempting reconnect to server...");
/* If this fails, then we give up, we don't retry multiple times. */
tryAutoLogin();
}
function authMethodCompatible(name) {
if (!authcapabilities.includes(name)) {
return false; /* If not offered by server, can't possibly use it */
}
/* If explicitly requested, or using autoselect, good to use */
var requested = document.getElementById('authmethod').value;
return requested === name || requested === "auto";
}
function plainLoginAllowed() {
var requested = document.getElementById('authmethod').value;
return requested === "PLAIN" || requested === "auto";
}
function isAutoLogin() {
var autologin = document.getElementById('autologin');
return autologin && autologin.value == 1;
}
function tryAutoLogin() {
var autologout = document.getElementById('autologout');
if (autologout && autologout.value == 1) {
console.log("Purging old login data");
/* This is a bit odd because logout is handled entirely by the client.
* The server can invalidate client side sessions only by changing the key (so the JWE can no longer validate when decrypted).
* Otherwise, since the expiration in the JWE is fixed, to log out early, the client needs to destroy its cookies (which we trust it will),
* and we should also clear the local storage values since they are now useless anyways.
* (Cookie values contain non-sensitive server connection info + the encrypted encryption key. Once we lose that, we lose the ability to decrypt the encrypted password. */
localStorage.removeItem("webmail-iv"); /* Clear IV used for password encryption/decryption */
localStorage.removeItem("webmail-password"); /* Clear encrypted password */
}
if (isAutoLogin() && localStorage.getItem("webmail-password") && localStorage.getItem("webmail-iv")) {
setStatus("Attempting to login to IMAP server using saved info...");
console.log("Autoconnecting using saved session info");
connect();
}
}
async function tryLogin() {
if (authcapabilities.includes("LOGINDISABLED")) {
setFatalError("Login is disabled on this IMAP server");
return;
}
/* Determine how to authenticate */
var requested = document.getElementById('authmethod').value;
/* Common IMAP authentication capabilities (hard to find a definitive list):
*
* Thunderbird-supported: AUTH=LOGIN, AUTH=PLAIN, AUTH=CRAM-MD5, AUTH=NTLM, AUTH=GSSAPI, AUTH=MSN, AUTH=EXTERNAL, AUTH=XOAUTH2
* Others: AUTH=DIGEST-MD5, AUTH=OAUTHBEARER
*
* A somewhat subjective ranking of these capabilities from most secure (and thus most preferred) to least preferred:
* Partially based on ordering used here:
* - https://github.com/smiley22/S22.Imap/blob/874de537106804fed9cd752b9945c666af6221e2/ImapClient.cs#L305
* - https://doc.dovecot.org/configuration_manual/authentication/authentication_mechanisms/
*
* There are several drawbacks to these schemes, discussed here: https://doc.dovecot.org/configuration_manual/authentication/password_schemes/
*
* The reason we attempt to support these is the webmail server may be operated by a somewhat trusted
* but not entirely trusted intermediary. In particular, we don't want the intermediary to have access
* to the plaintext password at any point. Thus, if the IMAP server supports one of these protocols,
* it is likely preferrable to use a non-plaintext authentication mechanism to plaintext.
* Methods that are largely pertinent to Windows and Active Directory only, e.g. NTLM, GSSAPI (RFC 4752), are omitted here.
* XOAUTH2 and its successor, OAUTHBEARER, require being registered with each service, which
* makes them less practical to use, since all this needs to be done client-side.
*
* - OAUTHBEARER (RFC 6750)
* - SCRAM-SHA-256 (RFC 7677)
* - SCRAM-SHA-1
* - DIGEST-MD5
* - CRAM-MD5
* - PLAIN-CLIENTTOKEN (Gmail-specific, what is this exactly???)
* - PLAIN
*
*/
/* TODO: Add support for all the above. Currently, we just support PLAIN. */
if (requested === "none") {
/* Abort, we're connected to the server so can display capabilities */
setError("Supported IMAP auth methods: " + authcapabilities.join(", "));
return;
}
var pt;
if (document.getElementById('login-password').value !== "") {
pt = document.getElementById('login-password').value;
document.getElementById('login-password').value = ""; /* Clear the plaintext password from the page */
} else {
/* Using the encryption key returned by the server, decrypt the password, stored locally */
var key_base64_encoded = document.getElementById('clientkey');
if (!key_base64_encoded) {
console.error("Can't log in (no key available to decrypt password)");
return;
}
key_base64_encoded = key_base64_encoded.value;
var decoded_key = base64ToArrayBuffer(key_base64_encoded);
var encoded_pw = localStorage.getItem("webmail-password");
if (!encoded_pw) {
console.error("Can't log in (no encrypted password available to decrypt)");
return;
}
var decoded_pw = base64ToArrayBuffer(encoded_pw); /* Get back the ciphertext */
var encoded_iv = localStorage.getItem("webmail-iv");
var decoded_iv = base64ToArrayBuffer(encoded_iv); /* Get back the IV */
pt = await decryptPassword(decoded_pw, decoded_key, decoded_iv); /* Recover the plain text password */
}
if (plainLoginAllowed() && (authMethodCompatible("PLAIN") || authMethodCompatible("LOGIN"))) {
/* All IMAP servers should support AUTH=PLAIN, AUTH=LOGIN, or LOGIN as a last resort */
var payload = {
command: "LOGIN",
/* base64 encode the password purely for obfuscation
* Using plaintext password auth is fundamentally not ideal when going through an intermediary web server,
* this doesn't improve security at all but at least makes it harder for the server admin to accidentally see the password */
password: btoa(pt)
}
payload = JSON.stringify(payload);
attempted_auth = true;
ws.send(payload);
} else {
setError("No mutually supported IMAP authentication methods (server supports " + authcapabilities.join(", ") + ")");
}
}
function enc_encode(m) {
var encoder = new TextEncoder();
return encoder.encode(m);
}
function enc_decode(m, encoding) {
var decoder = new TextDecoder(encoding);
return decoder.decode(m);
}
async function decryptPassword(ciphertext, raw, iv) {
var key = await window.crypto.subtle.importKey("raw", raw, "AES-GCM", true, [ "encrypt", "decrypt" ],);
var decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
key,
ciphertext
);
return enc_decode(decrypted, "utf-8");
}
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa( binary );
}
function base64ToArrayBuffer(base64) {
var binaryString = atob(base64);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
async function newSession(e, tgt) {
if (!window.isSecureContext || window.crypto.subtle === undefined) {
/* By default, this only exists in secure contexts */
setError("Crypto unavailable in insecure contexts: use HTTPS or enable in your browser e.g. chrome://flags/#unsafely-treat-insecure-origin-as-secure");
return;
}
/* Create a cryptographically secure encryption key
* We send this to the server to encrypt and return to us (encrypted by the server) in a JWT.
* The server will also bounce the encryption key back in a header.
* The point of this is neither the raw encryption key nor the plaintext password is stored on the client.
* We need the server to recover these, but the server never has access to the plaintext password,
* and it only has access to the plaintext password through this POST request + the JWT cookie,
* and it doesn't store that at all. This makes offline attacks more difficult. */
/* We need to encrypt the password now, BEFORE the form POSTs, or we'll lose access to the password,
* since we need to store it, in some form, beforehand. */
/* Generate an AES-GCM key */
var aeskey = await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"],
);
/* Encode and encrypt the plaintext password */
var encoded = enc_encode(document.getElementById('login-password').value);
var iv = window.crypto.getRandomValues(new Uint8Array(12)); /* This must never be reused with a given key */
var ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv,
},
aeskey,
encoded
);
/* The ciphertext is only ever stored locally. It never leaves the client.
* The encryption key goes to the server for safekeeping. It'll encrypt it
* and return a scrambled form of it in a JWT, for persistence,
* as well as unscrambled in header responses, for immediate usage. */
var pw_b64_encoded = arrayBufferToBase64(ciphertext);
localStorage.setItem("webmail-password", pw_b64_encoded); /* Yes, this is encrypted */
var raw = await window.crypto.subtle.exportKey("raw", aeskey);
var key_base64_encoded = arrayBufferToBase64(raw);
document.getElementById('enckey').value = key_base64_encoded; /* Siphon off the key to the server, via the form POST */
var iv_encoded = arrayBufferToBase64(iv); /* Save the IV locally */
localStorage.setItem("webmail-iv", iv_encoded);
const enable_sanity_check = true;
if (enable_sanity_check) { /* As a sanity check, make sure we get back the original */
var decoded_key = base64ToArrayBuffer(key_base64_encoded);
var encoded_pw = localStorage.getItem("webmail-password");
console.assert(pw_b64_encoded === encoded_pw);
var decoded_pw = base64ToArrayBuffer(encoded_pw); /* Get back the ciphertext */
/* console.assert(decoded_pw === ciphertext); */ // Doesn't work since === is just like ptr comparison (but these should be equivalent by value, if compared)
var pt = await decryptPassword(decoded_pw, decoded_key, iv);
console.assert(pt === document.getElementById('login-password').value);
/* Sadly, JS doesn't really allow us to (securely) destroy variables */
}
document.getElementById('login-password').value = ""; /* Destroy the password */
tgt.submit();
}
async function authenticate(e) {
/* If we elected to remember connection info, we need to POST
* to the server first (as usual) so we can get the cookie. */
if (document.getElementById('loginlimit').value > 0) {
var tgt = e.currentTarget; /* We need to use this after this event handler returns */
(async () => {
await newSession(e, tgt);
})();
/* Due to the await, we cannot let the form POST as normal,
* since the await needs to complete before we can POST it.
* So that's done inside initKey() */
e.preventDefault();
} else {
e.preventDefault();
/* If this is the first login attempt, open the connection */
if (ws === null) {
connect(); /* tryLogin() will get invoked eventually */
} else {
await tryLogin();
}
}
}
document.getElementById('login').addEventListener('submit', function(e) { authenticate(e); }, true);
function connect() {
var wshost = document.getElementById('websocket-host') ? document.getElementById('websocket-host').value : window.location.host;
var wshttps = document.getElementById('websocket-https') ? document.getElementById('websocket-https').value == 1 : (window.location.protocol === "https:");
var wsport = document.getElementById('websocket-port') ? document.getElementById('websocket-port').value : null;
var wsbaseuri = document.getElementById('websocket-uri') ? document.getElementById('websocket-uri').value : "/webmail";
var wsuri = ((wshttps ? "wss://" : "ws://") + wshost + (wsport ? (":" + wsport) : "") + wsbaseuri);
/* We only include query parameters if it's a direct login w/o Remember Me.
* However, the cookie might not go to the backend if the hostname is different, so to be safe,
* the frontend backend (PHP) also injects all the cookie info into the page, and we set it here.
* Since we don't adjust loginlimit for Remember Me autoconnects, we just require loginlimit === 0,
* but isAutoLogin() will not necessarily hold.
*
* XXX Technically, this workaround is only required if the WebSocket hostname differs from our own,
* if they're identical, then we can rely on the cookie to transmit this info and then
* !isAutoLogin() && document.getElementById('loginlimit').value == 0
* might be a better condition.
*/
if (document.getElementById('loginlimit').value == 0) {
/* If logging in directly, need to pass the connection info via the WebSocket URI since that's the only way to pass data prior to connection being established. */
var server = document.getElementById('server').value;
wsuri += "?server=" + server;
var port = document.getElementById('port').value;
wsuri += "&port=" + port;
var secure = document.getElementById('security-tls').checked;
wsuri += "&secure=" + secure;
/* This is needed for logging in without Remember Me: */
var username = document.getElementById('login-username').value;
if (username !== "") {
wsuri += "&username=" + username;
}
}
console.log("Establishing WebSocket connection to " + wsuri);
ws = new WebSocket(wsuri);
console.debug("Established WebSocket connection to " + wsuri);
ws.onopen = function(e) {
console.log("Websocket connection opened to " + wsuri);
/* Load parameters from URL */
var url = new URL(window.location.href);
const searchParams = new URLSearchParams(url.search);
var folder = searchParams.get("folder");
selectedFolder = folder !== undefined ? folder : "INBOX";
var q;
q = searchParams.get("page");
if (q !== undefined && q !== null) {
pageNumber = q;
}
q = searchParams.get("pagesize");
if (q !== undefined && q !== null) {
pagesize = q;
}
document.getElementById('option-pagesize').selectedIndex = Math.ceil(pagesize / 5) - 1;
q = searchParams.get("sort");
if (q !== undefined && q !== null) {
var sortDropdown = document.getElementById('option-sort');
for (var i = 0; i < sortDropdown.options.length; i++) {
if (sortDropdown.options[i].value === q) {
sortDropdown.selectedIndex = i;
sortOrder = i > 0 ? q : null; /* First one is none (default) */
break;
}
}
}
q = searchParams.get("filter");
if (q !== undefined && q !== null) {
var searchDropdown = document.getElementById('option-filter');
for (var i = 0; i < searchDropdown.options.length; i++) {
if (searchDropdown.options[i].value === q) {
searchDropdown.selectedIndex = i;
simpleFilter = i > 0 ? q : null; /* First one is none (default) */
break;
}
}
}
q = searchParams.get("html");
if (q !== undefined && q !== null) {
viewHTML = q === "yes";
}
document.getElementById("option-html").checked = viewHTML;
q = searchParams.get("extreq");
if (q !== undefined && q !== null) {
allowExternalRequests = q === "yes";
}
document.getElementById("option-extreq").checked = allowExternalRequests;
q = searchParams.get("raw");
if (q !== undefined && q !== null) {
viewRaw = q === "yes";
}
document.getElementById("option-raw").checked = viewRaw;
q = searchParams.get("preview");
if (q !== undefined && q !== null) {
viewPreview = q === "yes";
}
document.getElementById("option-preview").checked = viewPreview;
console.log("Folder: " + selectedFolder + ", page: " + pageNumber + ", page size: " + pagesize);
processSettings();
};
ws.onmessage = function(e) {
handleMessage(e);
}
ws.onclose = function(e) {
console.log("Websocket closed");
if (ever_session_connected) {
setFatalError("The server closed the connection. Please reload the page.");
} else {
setFatalError("The server closed the connection. Please click 'Log in' to reconnect.");
}
resetConnection();
/* If we were able to successfully connect before, give it another shot */
if (getBoolSetting("autoreconnect") && session_connected) {
/* Wait a little bit, then retry to see if we can connect */
console.log("Waiting 25 seconds, then trying to autoreconnect");
setTimeout(function() {
tryAutoReconnect();
}, 25000);
}
session_connected = false;
};
ws.onerror = function(e) {
console.log("Websocket error");
setError("A websocket error occured.");
};
console.debug("Set up WebSocket callbacks");
}
function reloadCurrentMessage() {
if (currentUID > 0) {
commandFetchMessage(currentUID);
}
}
function setPreviewPaneHeight(height) {
document.getElementById('previewpane').style.height = height + 'px';
console.debug("Preview pane height now: " + height);
}
function togglePreview(elem) {
viewPreview = elem.checked;
document.getElementById("option-preview").checked = viewPreview;
setq('preview', viewPreview ? "yes" : "no");
if (!viewPreview) {
/* Hide it if we don't need it */
setPreviewPaneHeight(0);
}
if (viewPreview) {
reloadCurrentMessage();
}
}
function toggleHTML(elem) {
viewHTML = elem.checked;
document.getElementById("option-html").checked = viewHTML;
setq('html', viewHTML ? "yes" : "no");
if (viewPreview) {
reloadCurrentMessage();
}
}
function toggleExternalRequests(elem) {
allowExternalRequests = elem.checked;
document.getElementById("option-extreq").checked = allowExternalRequests;
setq('extreq', allowExternalRequests ? "yes" : "no");
if (viewPreview) {
reloadCurrentMessage();
}
}
function toggleRaw(elem) {
viewRaw = elem.checked;
document.getElementById("option-raw").checked = viewRaw;
setq('raw', viewRaw ? "yes" : "no");
if (viewPreview) {
reloadCurrentMessage();
}
}
function setSort(s) {
sortOrder = s;
setq('sort', s);
/* Do a FETCHLIST again */
var currentPage = getq('page');
commandFetchList(currentPage);
}
function setFilter(s) {
simpleFilter = s;
setq('filter', s);
/* Do a FETCHLIST again */
var currentPage = getq('page');
commandFetchList(currentPage);
}
function setPageSize(pgsz) {
if (pgsz < 1) {
return;
}
pagesize = pgsz;
setq('pagesize', pgsz);
document.getElementById('option-pagesize').selectedIndex = Math.ceil(pagesize / 5) - 1;
/* Do a FETCHLIST again */
var currentPage = getq('page');
commandFetchList(currentPage);
}
function processSettings() {
/* Settings in local storage, rather than in query params */
if (getBoolSetting("forcelabels")) {
document.getElementById('btn-compose').value = "Compose";
document.getElementById('btn-reply').value = "Reply";
document.getElementById('btn-replyall').value = "Reply All";
document.getElementById('btn-forward').value = "Forward";
document.getElementById('btn-markunread').value = "Mark Unread";
document.getElementById('btn-markread').value = "Mark Read";
document.getElementById('btn-flag').value = "Flag";
document.getElementById('btn-unflag').value = "Unflag";
document.getElementById('btn-junk').value = "Junk";
document.getElementById('btn-delete').value = "Delete";
//document.getElementById('option-extreq').value = "Ext Content";
//document.getElementById('btn-download').value = "Download";
}
}
function folderLevel(folder) {
var level = 0;
for (var i = 0; i < folder.name.length; i++) {
if (folder.name.charAt(i) === hierarchyDelimiter) {
level++;
}
}
return level;
}
function addToFolderMenu(details, searchParams, parent, folder) {
var li = document.createElement('li');
li.setAttribute('id', 'folder-link-' + folder.name);
var selected = searchParams.get("folder") === folder.name;
if (selected) {
console.log("Currently selected: " + folder.name);
li.classList.add("folder-current");
}
var dispname = displayFolderName(folder);
var prefix = folder.prefix;
var noselect = !folderExists(folder);
var marked = folder.flags.indexOf("Marked") !== -1;
if (!details) {
/* This is just the preliminary list */
li.innerHTML = "<span class='foldername'>" + prefix + dispname + "</span>";
} else {
var extraClasses = (folder.unseen > 0 ? " folder-hasunread" : "") + (marked ? " folder-marked" : "");
if (noselect) {
li.innerHTML = "<span class='foldername" + extraClasses + "'>" + prefix + dispname + "<span class='folderunread'>" + "</span>" + "</span>";
} else {
/* Since the link has an event listener (commandSelectFolder),
* we don't need an actual link for the hyperlink and '#' works just fine as a target.
* However, it still shows as a link on the page (as it should), and the hyperlink
* value is thus a bit nonsensical, particularly considering that after clicking on it,
* the URL will change to reflect that folder.
* Additionally, using '#' prevents users from right-clicking and opening a mailbox
* in a new tab. So, do set the URL correctly: */
var currentURL = new URL(window.location.href);
currentURL.searchParams.set("folder", folder.name); /* Set the folder query param in the link to this folder */
var linkURL = currentURL.toString();
li.innerHTML = "<span class='foldername" + extraClasses + "'>" + prefix + "<a href='" + linkURL + "' title='" + folder.name + "'>" + dispname + "<span class='folderunread'>" + (folder.unseen > 0 ? " (" + folder.unseen + ")" : "") + "</span></a>" + "</span>";
li.innerHTML += ("<span class='foldercount'>" + folder.messages + "</span><span class='foldersize'>" + formatSize(folder.size, 0) + "</span>");
}
}
if (!noselect) {
/* Allow clicking the entire li to select, since this gives a wider click area */
li.addEventListener('click', function(e) { commandSelectFolder(folder.name, false); return false; }, {passive: true});
li.addEventListener('mouseup', function(e) { clickDragMove(folder.name); }, {passive: true});
li.addEventListener('mouseover', function(e) { folderMouseOver(folder.name, li); }, {passive: true});
li.addEventListener('mouseleave', function(e) { folderMouseLeave(folder.name, li); }, {passive: true});
var a = li.getElementsByTagName("a")[0];
/* However, if somebody does click the link, don't actually follow it.
* preventDefault() is needed to prevent clicking a folder from navigating to the link,
* since the target is a valid link rather than just '#' */
a.addEventListener('click', function(e) { e.preventDefault(); }, {passive: false});
}
parent.appendChild(li);
}
function checkNotificationPermissions() {
/* Can only ask for permission in response to a user gesture. This is probably the first click a user will make. */
checkedNotifyPerm = true;
console.log("Notification permission: " + Notification.permission);
/* Also note that in Chrome icognito mode (starting v49), notifications are not allowed.
* Can work in insecure origins if configured, otherwise. */
if (Notification.permission === "denied") {
console.error("Notification permission denied");
} else if (Notification.permission !== "granted") {
console.log("Requesting notification permission");
Notification.requestPermission();
}
}
var firstSelection = true;
function commandSelectFolder(folder, autoselected) {
if (!firstSelection) {
setq('page', 1); /* Reset to first page of whatever folder was selected */
}
var payload = {
command: "SELECT",
folder: folder,
pagesize: parseInt(pagesize),
sort: sortOrder,
filter: simpleFilter,
}
payload = JSON.stringify(payload);
ws.send(payload);
if (!autoselected && !checkedNotifyPerm) {
checkNotificationPermissions();
}
}
function setq(param, value) {
var url = new URL(window.location.href);
if (param !== null && value !== null) {
url.searchParams.set(param, value);
}
if (window.history.replaceState) {
/* Don't store history */
window.history.replaceState("", document.title, url.toString());
}
}
function getq(param) {
var url = new URL(window.location.href);
const searchParams = new URLSearchParams(url.search);
return searchParams.get(param);
}
function commandFetchList(page) {
pageNumber = page;
setq('page', pageNumber);
var payload = {
command: "FETCHLIST",
page: parseInt(pageNumber),
pagesize: parseInt(pagesize),
sort: sortOrder,
filter: simpleFilter,
}
console.debug(payload);
payload = JSON.stringify(payload);
ws.send(payload);
}
function getSelectedUIDs() {
if (allSelected) {
return "1:*";
}
var uids = new Array();
var checkboxes = document.getElementsByName('msg-sel-uid');
totalSelected = unseenSelected = 0;
for (var checkbox of checkboxes) {
if (checkbox.checked) {
uids.push(parseInt(checkbox.value));
totalSelected++;
/* Is it unread?
* checkbox is an input. Its parent is a td and its parent is a tr.
* If the tr has the class messagelist-unread, it's unseen */
if (checkbox.parentNode.parentNode.classList.contains("messagelist-unread")) {
unseenSelected++;
}
}
}
console.debug(uids);
return uids;
}
function selectMessage(checkbox) {
var uid = checkbox.value;
checkbox.checked = true;
var tr = document.getElementById('msg-uid-' + checkbox.value);
if (!tr.classList.contains("messagelist-selected")) {
tr.classList.add("messagelist-selected");
}
}
function unselectMessage(checkbox) {
var uid = checkbox.value;
checkbox.checked = false;
var tr = document.getElementById('msg-uid-' + checkbox.value);
if (tr.classList.contains("messagelist-selected")) {
tr.classList.remove("messagelist-selected");
}
}
function selectAllUIDs() {
var checkboxes = document.getElementsByName('msg-sel-uid');
for (var checkbox of checkboxes) {
selectMessage(checkbox);
}
}
function unselectAllUIDs() {
/* Reset all checkboxes, and check only this one */
var checkboxes = document.getElementsByName('msg-sel-uid');
for (var checkbox of checkboxes) {
unselectMessage(checkbox);
}
}
function commandFetchMessage(uid) {
if (!(uid > 0)) {
console.error("Invalid UID: " + uid);
return;
}
/* Reset all checkboxes, and check only this one */
var checkboxes = document.getElementsByName('msg-sel-uid');
for (var checkbox of checkboxes) {
var selected = parseInt(checkbox.value) === parseInt(uid);
if (selected) {
selectMessage(checkbox);
} else {
unselectMessage(checkbox);
}
}
console.log("Fetching message " + uid);
var payload = {
command: "FETCH",
uid: parseInt(uid),
html: viewHTML,
raw: viewRaw
}
payload = JSON.stringify(payload);
ws.send(payload);
if (viewRaw) {
/* If we're downloading the entire message, and it's more than a couple KB,
* it could possibly take quite a while, particularly if the client is on
* a slow connection (e.g. dial up).
* Meanwhile, display a status message to let the user know we're processing the request. */
setStatus("Downloading raw message, please wait...");
}
}
function append(data, len) {
console.log("Appending message with size " + len);
var payload = {
command: "APPEND",
message: data,
size: len
/* XXX No date or flags */
}
payload = JSON.stringify(payload);
ws.send(payload);
}
function upload() {
if (selectedFolder === null) {
setError("No mailbox currently active");
return;
}
var file = document.getElementById('btn-upload').files[0];
var size = file.size;
var data = null;
var reader = new FileReader();
reader.onload = (e) => {
data = e.target.result;
if (data === null) {
console.error("No message body?");
}
append(data, size);
};
reader.readAsText(file);
}
function editor(name, from, to, cc, subject, body, inreplyto, references) {
/* Escape any quotes inside attributes */
to = to.replace(/'/g, "'");
cc = cc.replace(/'/g, "'");
subject = subject.replace(/'/g, "'");
var childhtml = "<html><head><title>" + name + "</title><link rel='stylesheet' type='text/css' href='style.css'><link rel='stylesheet' type='text/css' href='form.css'></head><body>";
childhtml += "<div>";
childhtml += "<form id='composer' target='' method='post' enctype='multipart/form-data'>";
childhtml += "<div class='form-table'>";
childhtml += "<div><label for='from'>From</label><input type='text' id='from' name='from' placeholder='" + document.getElementById('fromaddress').value + "' value='" + from + "'></input></div>";
childhtml += "<div><label for='replyto'>Reply To</label><input type='text' id='replyto' name='replyto' placeholder='Same as From'></input></div>";
childhtml += "<div><label for='to'>To</label><input type='text' id='to' name='to' value='" + to + "' required></input></div>";
childhtml += "<div><label for='cc'>Cc</label><input type='text' id='cc' name='cc' value='" + cc + "'></input></div>";
childhtml += "<div><label for='bcc'>Bcc</label><input type='text' id='bcc' name='bcc'></input></div>";
childhtml += "<div><label for='subject'>Subject</label><input type='text' id='subject' name='subject' value='" + subject + "'></input></div>";
childhtml += "<div><label for='priority'>Priority</label><select name='priority'><option value='1'>Highest</option><option value='2'>High</option><option value='3' selected>Normal</option><option value='4'>Low</option><option value='5'>Lowest</option></select></div>";
childhtml += "</div>";
if (inreplyto.length > 0) {
inreplyto = "<" + inreplyto + ">";
}
childhtml += "<input type='hidden' name='inreplyto' value='" + inreplyto + "'>";
childhtml += "<input type='hidden' name='references' value='" + (references.length > 0 ? (references + "\r\n " + inreplyto) : inreplyto) + "'>";
childhtml += "<textarea id='compose-body' name='body'>" + body + "</textarea>";
childhtml += "<input type='submit' id='btn-send' name='send' value='Send'/>";
childhtml += "<input type='submit' name='savedraft' value='Save Draft'/>";
childhtml += "<h4>Attachment(s)</h4>";
childhtml += "<input type='file' id='compose-attachments' name='attachments[]' multiple/>";
childhtml += "</form>";
childhtml += "</div>";
childhtml += "</body>";
childhtml += "<script src='compose.js'></script>";
childhtml += "</html>";
var tab = window.open('about:blank', '_blank');
tab.document.write(childhtml);
tab.document.close(); /* Finish loading page */
if (name === "Compose" || name === "Forward") {
tab.document.getElementById('to').focus(); /* For new messages and forwards, focus the 'To' field since that will generally need to be filled in first */
} else {
tab.document.getElementById('compose-body').focus(); /* For replies, we can just focus the body immediately */
}
}
function compose() {
/* It isn't actually necessary to initialize 'From' explicitly to document.getElementById('fromaddress').value
* (though we do use that as the placeholder).
* smtp.php will use the username (which is what fromaddress is) as the default anyways.
*
* Nonetheless, we do this to make it clearer to the user that this is what will actually be used unless s/he changes it,
* it's not just a suggestion. */
editor("Compose", document.getElementById('fromaddress').value, '', '', '', '', '', '');
}
function doReply(replyto, replycc) {
if (currentUID < 1) {
setError("No message is currently selected!");
return;
}
var replysubject = lastsubject.substring(0, 3) === "Re:" ? lastsubject : ("Re: " + lastsubject); /* Don't prepend Re: if it's already there */
/* Quote each line of the original message */
/* XXX If we fetched the HTML or message source (raw), we should fetch the plain text component to reply to
* XXX Maybe not... for example, Thunderbird-based clients will use the PT or HTML version for replies depending on what was replied to,
* so there may be an advantage to allowing the user to choose... */
var bodyMsg = (lastbody !== undefined ? lastbody.split('\r\n') : "");
var replybody = "";
/* Date should never be abbreviated, even if today, we always include the date.
* Also, the sender's name should not include the email, if a name is present. */
replybody += "On " + formatDateNonabbreviated(0, lastsent) + ", " + formatDisplayName(lastfrom) + " wrote:\r\n"
for (var b in bodyMsg) {
b = bodyMsg[b];
replybody += ">" + b + "\r\n";
}
/* If one of our configured identities was one of the recipients of the message to which we're replying,
* then assume that's us and reply to the message using the same identity.
* This mirrors the identity functionality in Thunderbird-like clients. */
var from = '';
var idents = getArraySetting('identities');
for (i = 0; i < idents.length; i++) {
/* See if any of the identities was any of the recipients of the message to which we're replying. */
var email = idents[i];
var tmp = email.indexOf('<');
if (tmp !== -1) { /* Use just the portion in <>, if specified */
email = email.substring(tmp + 1);
tmp = email.indexOf('>');
email = email.substring(0, tmp);
}
if (replyto.indexOf(email) !== -1) {
from = idents[i]; /* Use the full identity, not just the email portion (on match) */
console.debug("Overriding from identity to " + from);
break;
} else if (replycc.indexOf(email) !== -1) {
from = idents[i];
console.debug("Overriding from identity to " + from);
break;
}
}
/* We use lastmsgid and references to set the In-Reply-To and References headers properly, so we don't break threading
* I really hate mail clients that don't preserve threading... their noncompliance makes everyone miserable... */
editor("Reply", from, replyto, replycc, replysubject, replybody, lastmsgid, lastreferences);
}
function reply(to, cc) {
doReply(lastfrom, '');
}
function replyAll() {
/* Include the Cc.
* Also, in addition to sender, include all the original To recipients, except for ourself, if we are one. */
allfrom = lastfrom;
var addresses = lastto.split(',');
for (var x in addresses) {
x = addresses[x];
/* XXX If one of the "To" or "Cc" recipients is same as our outgoing From address, or any of our identities, skip it. */
/* XXX Should also do for Cc? */
if (x.indexof('"' + document.getElementById('fromaddress').value + '"') === -1) {
allfrom += ", " + x;
} else {
console.debug("Not adding " + x + " to recipient list again");
}
}
doReply(allfrom, lastcc);
}
function forward() {
var fwdbody = "\r\n\r\n\r\n-------- Forwarded Message --------\r\n";
fwdbody += "Subject: \t" + lastsubject + "\r\n";
fwdbody += "Date: \t" + lastsent + "\r\n"; /* XXX Should use the appropriate date format */
fwdbody += "From: " + lastfrom + "\r\n";
fwdbody += "To: \t" + lastto + "\r\n";
fwdbody += "\r\n\r\n\r\n";
fwdbody += lastbody;
editor("Forward", '', '', '', 'Fwd: ' + lastsubject, fwdbody, lastmsgid, lastreferences);
}
function updateFolderCount(f) {
setFolderTitle(f.unseen); /* Update page title with new unread count */
drawFolderMenu(); /* Redraw folder list */
}
function adjustFolderCount(name, difftotal, diffunread) {
console.log("Applying folder adjustment: " + name + " (" + difftotal + "/" + diffunread + ")");
var f = getFolder(selectedFolder);
if (f === null) {
console.error("Couldn't find current folder (" + selectedFolder.name + ") in folder list?");
} else {
f.messages += difftotal;
f.unseen += diffunread;
updateFolderCount(f);
}
}
function implicitSeenUnseen(selected, markread) {
/* Mark seen or unseen locally */
var diffunread = 0;
for (var uididx in selected) {
var uid = selected[uididx];
console.log("Marking message " + (markread ? "read" : "unread") + " locally: " + uid);
var tr = document.getElementById('msg-uid-' + uid);
if (markread) {
if (tr.classList.contains("messagelist-unread")) {
/* Only count if this is a change */
diffunread--;
tr.classList.remove("messagelist-unread");
}
} else {
if (!tr.classList.contains("messagelist-unread")) {
/* Only count if this is a change */
diffunread++;
tr.classList.add("messagelist-unread");
}
}
}
if (diffunread !== 0) {
adjustFolderCount(selectedFolder, 0, diffunread);
} else {
console.debug("No actual change in any counts");