-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvanill.html
More file actions
963 lines (828 loc) · 29.8 KB
/
svanill.html
File metadata and controls
963 lines (828 loc) · 29.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Svanill</title>
<meta name="description" content="Svanill, an easily auditable tool to manage your sensitive data" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3csvg version='1.1'
viewBox='0 0 14 14' xmlns='http://www.w3.org/2000/svg'%3e%3cg stroke='black'%3e%3ccircle cx='7' cy='7'
r='6.5' fill='%237995c0' stroke-width='.4'/%3e%3ccircle cx='7' cy='4' r='2'/%3e%3cpath d='M5.6 11.7h2.8
L7.8 6%2c6.2 6z'/%3e%3c/g%3e%3c/svg%3e" />
<script id="setup">
// Iteration count for PBKDF2 (the higher the value the longer it will take to derive the key).
const PBKDF2_ITERATIONS = new URLSearchParams(document.location.search).get('iterations') || 100000;
// When decrypting we use the iterations number found in the encrypted box. We set an hard limit to block DoS attacks.
const PBKDF2_MAX_ITERATIONS = PBKDF2_ITERATIONS;
// Url to an optional external service to send/reload encrypted data
const STORE_URL = new URLSearchParams(document.location.search).get('store_url') || 'https://api.svanill.com';
// Prefix you expect in the proposed urls you're given to upload to (use the empty string to allow all).
// End it with slash '/' to block malicious urls (otherwise e.g. 'foo.com' would allow 'foo.comicly.broken')
const TRUSTED_UPLOAD_BASE_URL = new URLSearchParams(document.location.search).get('upload_base_url')
|| 'https://svanill-vault.s3.us-west-2.amazonaws.com/';
const ERRORS_QUEUE = [];
const ENCRYPTED_BOX_FORMAT = new Uint8Array([0]);
</script>
<style>
:root {
--main-bg-color: #141520;
--main-fg-color: #ffffff;
--secondary-bg-color: #354462;
--highlight-color: #7995c0;
--secondary-fg-color: #d3d4dc;
--extra-color: #e3a46c;
--warning-color: #ffcc00;
--error-color: #ff3f00;
--font-default: Verdana, Geneva, Tahoma, sans-serif;
--font-mono: "Andale Mono", AndaleMono, Consolas, Monaco, monospace;
--font-textarea: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
html {
background-color: var(--main-bg-color);
color: var(--main-fg-color);
font-family: var(--font-default);
height: 100%;
}
body {
box-sizing: border-box;
max-width: 1200px;
width: 100%;
padding: 1em;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100%;
}
p {
margin: 0;
}
.main-container {
display: flex;
width: 100%;
flex: 1 0 auto;
flex-wrap: wrap;
}
label {
cursor: pointer;
}
textarea, button {
box-sizing: border-box;
}
.plaintext-container, .ciphertext-container {
box-sizing: border-box;
padding: 0 1em;
display: flex;
flex: 1 1 50%;
flex-direction: column;
min-width: 280px;
margin-top: 1em;
}
#ciphertext:not(:placeholder-shown) {
font-family: var(--font-mono);
/* The rest is to not display newlines (it's just better to see) */
word-break: break-all;
white-space: normal;
word-spacing: -9px;
}
#ciphertext-error-bar:not(:empty) {
color: var(--error-color);
margin-bottom: 5px;
}
span.error:empty:before {
content: "\200b"; /* unicode zero width space character */
}
#download-cleartext {
color: var(--error-color);
}
button {
font-weight:bold;
cursor: pointer;
color: var(--main-bg-color);
}
button:disabled {
opacity: 0.5;
}
textarea {
flex: 1 1 100%;
min-height: 50vh; /* effective on narrow windows when textareas reflow */
background-color: var(--secondary-bg-color);
border-radius: 6px;
border-style: none solid solid none;
border-width: medium 1px 1px medium;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12) inset;
color: var(--main-fg-color);
font-family: var(--font-textarea);
font-size: 1em;
line-height: 1.4em;
padding: 0.5em;
transition: background-color 0.2s ease 0s;
}
textarea:focus {
background-color: var(--secondary-fg-color);
color: var(--main-bg-color);
outline-width: 0;
}
textarea::placeholder {
font-weight: bold;
color: var(--secondary-fg-color);
opacity: 1;
font-family: var(--font-textarea);
}
textarea:focus::placeholder {
color: transparent;
}
#login-form {
display: none;
flex-direction: column;
align-items: center;
width: 300px;
}
.login-text {
margin: 0.5em 0 2em 0;
width: 90%;
}
.require-login .main-container,
.require-login #logout-btn,
.external.action,
#overlay.is-hidden {
display: none;
}
.require-login #login-form {
display: flex;
}
.enable-external-actions .external.action {
display: initial;
}
.actions {
width: 214px;
flex: 0 1 auto;
white-space: nowrap;
}
.action-bar {
width: 100%;
display: flex;
justify-content: space-between;
margin-bottom: 0.5em;
flex-wrap: wrap;
}
button.action {
box-sizing: border-box;
width: 68px;
margin-bottom: 0.2em;
}
.action-bar .title {
font-weight: bold;
color: var(--extra-color);
text-shadow: 0 0 33px var(--main-bg-color);
font-size: 1.3em;
margin: 0 0.2em 0.2em 0;
flex: 1 0 auto;
}
#error-bar {
display: none;
line-height: 1.5em;
background-color: var(--main-fg-color);
color: var(--main-fg-color);
text-align: center;
position: fixed;
top: 0;
width: 100%;
align-items: center;
flex-direction: column;
}
input:focus,
button:focus,
#error-bar:not(:empty):focus {
outline: 2px solid rgb(53, 132, 228);
-moz-outline-radius: 8px;
}
input[type=text], input[type=password] {
border-color: transparent;
border-width: 0 8px;
border-radius: 2px;
padding: 1px;
height: 32px;
}
#error-bar.bump {
display: flex;
transition: background-color 0.5s ease;
background-color: var(--error-color);
}
#overlay {
display: flex;
background-color: rgba(159, 159, 187, 0.56);
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
justify-content: center;
align-items: center;
}
@keyframes spinner-animation {
to {transform: rotate(360deg);}
}
#spinner {
box-sizing: border-box;
width: 4em;
height: 4em;
border-radius: 50%;
border: 2px solid #ccc;
border-top-color: #333;
animation: spinner-animation .6s linear infinite;
}
#about {
position: fixed;
top: 5px;
right: 5px;
}
a { color: #3ca4ff; }
a:visited { color: #81c4f8; }
</style>
</head>
<body spellcheck="false" class="require-login enable-external-actions" onload="onPageLoaded()">
<p id="error-bar" role="alert" aria-atomic="true" tabindex="0">
<span id="error-bar-text"></span>
<button id="error-bar-btn" onClick="discardLatestError()" style="margin-bottom: 3px;">Dismiss</button>
</p>
<form id="login-form" class="page-load" role="form">
<a id="about" href="https://svanill.com/about.html" noopener noreferrer>About</a>
<label class="login-label" for="username">Username
<span title="If you provide one it will enable sync capabilities and do network requests">(?) - optional</span>
</label>
<input id="username" type="text"
title="The optional username allows you to access an external service (to upload/sync your files)"
class="login-text"
autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false"/>
<label class="login-label" for="secret">Password</label>
<input id="secret" type="password"
class="login-text"
required=""
autocomplete="new-password" />
<label class="login-label" for="confirm-secret">Confirm Password</label>
<input id="confirm-secret" type="password"
class="login-text"
required=""
autocomplete="new-password" />
<button id="login-btn" type="submit" disabled="disabled" autocomplete="off" tabindex="0">Unlock</button>
</form>
<button id="logout-btn">Logout</button>
<main class="main-container" role="main">
<div class="plaintext-container">
<p class="action-bar"><label class="title" for="plaintext">Cleartext</label>
<span class="actions">
<button id="download-cleartext" class="action" title="download" aria-label="download">⬇</button>
</span>
</p>
<textarea id="plaintext" class="change-ciphertext" autocomplete="off" placeholder="Click here to type some text to encrypt"></textarea>
</div>
<div class="ciphertext-container">
<p class="action-bar">
<label class="title" for="ciphertext">Ciphertext</label>
<span class="actions">
<button id="reload-ciphertext" class="external action" title="reload" aria-label="reload">⟳</button>
<button id="upload-ciphertext" class="external action" title="upload" aria-label="upload">⬆</button>
<button id="download-ciphertext" class="action" title="download" aria-label="download">⬇</button>
</span>
</p>
<p id="ciphertext-error-bar" role="alert" aria-atomic="true"></p>
<textarea id="ciphertext" autocomplete="off" placeholder="Click here to paste some text to decrypt"></textarea>
</div>
</main>
<div id="overlay" class="is-hidden"><div id="spinner"></div></div>
<a id="download-dialog-anchor" href="" style="display:none"></a>
<script id="the-script">
const $ = id => document.getElementById(id);
const setValueAt = (id, value) => $(id).value = value;
const getValueAt = (id) => $(id).value;
const stringToUint8Array = text => new TextEncoder().encode(text);
const bufferToString = buffer => new TextDecoder().decode(buffer);
function bufToHex(buffer) {
return new Uint8Array(buffer).reduce((a, b) => a + ('0' + b.toString(16)).slice(-2), '');
}
function hexToBuf(text) {
if (!text) { return new Uint8Array(0); }
return new Uint8Array(text.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}
async function willGenerateKey(secret, b_salt, iterations) {
try {
const baseKey = await crypto.subtle.importKey(
'raw',
stringToUint8Array(secret),
{ name: 'PBKDF2' },
false, // whether the key can be extracted or not
[ 'deriveKey' ]
);
return await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: b_salt,
iterations,
hash: 'SHA-256'
},
baseKey,
{ "name": 'AES-GCM', "length": 256 },
false, // whether the key can be extracted or not
[ "encrypt", "decrypt" ]
);
} catch (e) {
throw new GenerateKeyError(e.message || e.name);
}
}
class GenerateKeyError extends Error {};
/**
* Encrypt text using 256 AES in GCM mode, deriving the key with PBKDF2.
*
* @param string plaintext the text to encrypt
* @param string secret the secret to use to derive the key with PBKDF2
* @param arrayBuffer b_salt salt, use it to prevent dictionary attacks
* @param number iterations the number of PBKDF2 iterations to derive the key
* @param arrayBuffer b_iv a nonce to use in AES-GCM
* @return Promise that will resolve to our encrypted box format.
*
* The encrypted box follows this format <iterations>.<iv>.<salt>-<ciphertext>
* where every element is base64 encoded.
*
* >>> willEncryptPlaintext(
* >>> 'the text to encrypt',
* >>> 'your strong password',
* >>> new Uint8Array([0,1,...,15]), // salt, preferably 128 bit
* >>> 60000, // iterations to derive the key
* >>> new Uint8Array([0,1,...,11]) // 96 bit nonce
* >>> ).then(function (result) {
* >>> console.log(result); // iterations.iv.salt-ciphertext
* >>> });
*/
async function willEncryptPlaintext(plaintext, secret, b_salt, iterations, b_iv) {
const derivedKey = await willGenerateKey(secret, b_salt, iterations);
const dv_iterations = new DataView(new ArrayBuffer(4)) // hold up to 4 * 8 (2**32) bit
dv_iterations.setUint32(0, iterations)
const ad = [ENCRYPTED_BOX_FORMAT, dv_iterations.buffer, b_salt].map(bufToHex).join('');
const b_enc = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: b_iv,
additionalData: hexToBuf(ad),
},
derivedKey,
stringToUint8Array(plaintext)
);
return ad + bufToHex(b_iv) + bufToHex(b_enc);
}
function crypto_subtle_decrypt_exceptional(algorithm, key, data) {
return crypto.subtle.decrypt(algorithm, key, data)
.catch(e => { throw new SubtleDecryptError('Password and ciphertext do not match'); });
}
class SubtleDecryptError extends Error {};
/**
* Decrypt data using 256 AES in GCM mode, deriving the key with PBKDF2.
*
* @param string ciphertext the text to decrypt, as produced by willEncryptPlaintext
* @param string secret the secret to use to derive the key with PBKDF2
* @return Promise<string> the plaintext
*/
async function willDecryptCiphertext(encryptedBox, secret) {
encryptedBox = encryptedBox.replace(/\s/g, '') // remove spaces/newlines
const parts = encryptedBox.match(/^(.{2})(.{8})(.{32})(.{24})(.+)/)
if (parts === null) {
throw new SubtleDecryptError('Content is too short');
}
const [b_version, b_iterations, b_salt, b_iv, b_enc] = parts.slice(1).map(hexToBuf);
if (b_version[0] !== 0) {
throw new SubtleDecryptError('Unsupported encryption format (perhaps generated by a newer Svanill version)');
}
const iterations = new DataView(b_iterations.buffer).getUint32();
if (iterations > PBKDF2_MAX_ITERATIONS) {
// Use an hardcoded limit to avoid CPU DoS caused by an adversary
throw new SubtleDecryptError('The decoded iterations number is dangerously high');
}
const derivedKey = await willGenerateKey(secret, b_salt, iterations);
const b_dec = await crypto_subtle_decrypt_exceptional(
{
name: 'AES-GCM',
iv: b_iv,
additionalData: hexToBuf(encryptedBox.slice(0, 42)),
},
derivedKey,
b_enc
);
return bufferToString(b_dec);
}
function willRequestEncryption(plaintext) {
if (!plaintext) return '';
const secret = getValueAt('secret');
const b_iv = window.crypto.getRandomValues(new Uint8Array(12));
const b_salt = window.crypto.getRandomValues(new Uint8Array(16));
const iterations = PBKDF2_ITERATIONS;
return willEncryptPlaintext(plaintext, secret, b_salt, iterations, b_iv);
}
function triggerDownloadDialog(blob, filename) {
const url = window.URL.createObjectURL(blob);
const anchor = $('download-dialog-anchor');
anchor.href = url;
anchor.download = filename;
anchor.click();
window.URL.revokeObjectURL(url);
}
/**
* Format a date as YYYY-MM-DD_HH.MM.SS, using the browser's locale timezone
*/
function makeDateTimePrefix(date) {
return new Intl.DateTimeFormat('sv-SE', { // sv-SE has a practical format
year:'numeric', month:'2-digit', day:'2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
}).format(date).replace(/\s+/g, '_').replace(/:/g, '.')
}
const pushErrorToDisplayQueue = (e) => {
const errorMessage = e.message || e.name || 'Unknown error';
if (errorMessage != ERRORS_QUEUE.slice(-1)[0]) {
ERRORS_QUEUE.push(errorMessage);
}
displayErrorBanner();
};
const discardLatestError = () => {
ERRORS_QUEUE.pop();
displayErrorBanner();
};
const displayErrorBanner = () => {
$('error-bar').classList.remove('bump');
$('error-bar-text').innerText = ERRORS_QUEUE.slice(-1)[0] || '';
$('error-bar-text').innerText && window.requestAnimationFrame(() => $('error-bar').classList.add('bump'));
};
const toggleOverlay = (isVisible) => {
$('overlay').classList.toggle('is-hidden', !isVisible);
};
const ciphertextHasError = () => $('ciphertext').classList.contains('has-error');
const setCiphertextError = (errorMessage) => {
const hasError = Boolean(errorMessage.trim());
$('ciphertext').classList.toggle('has-error', hasError);
$('ciphertext-error-bar').innerText = errorMessage;
};
const encryptPlaintextAndSetCiphertext = async function() {
try {
let ciphertext = await willRequestEncryption(getValueAt('plaintext'));
ciphertext = ciphertext.replace(/(.{1,78})/g,'$1\n').trim(); // add a newline every 78 chars
setValueAt('ciphertext', ciphertext);
setCiphertextError('');
} catch (e) {
pushErrorToDisplayQueue(e);
}
};
async function updatePlaintextFromCiphertext() {
setCiphertextError('');
try {
const secret = getValueAt('secret');
const ciphertext = getValueAt('ciphertext');
let plaintext = '';
if (ciphertext) {
plaintext = await willDecryptCiphertext(ciphertext, secret);
}
setValueAt('plaintext', plaintext);
} catch (e) {
if (!(e instanceof SubtleDecryptError)) {
console.error(e);
}
setCiphertextError(`${e.message}, cannot decrypt. Focus the cleartext to refresh the ciphertext`);
};
}
function onDownloadCiphertextButtonClicked(ev) {
ev.preventDefault();
const blob = new Blob([getValueAt('ciphertext')], {type: "plain/text"});
const filename = makeDateTimePrefix(new Date()) + '_encrypted_svanill.txt';
triggerDownloadDialog(blob, filename);
}
function onDownloadCleartextButtonClicked(ev) {
ev.preventDefault();
const blob = new Blob([getValueAt('plaintext')], {type: "plain/text"});
const filename = makeDateTimePrefix(new Date()) + '_cleartext_svanill.txt';
triggerDownloadDialog(blob, filename);
}
async function onReloadCiphertextButtonClicked(ev) {
ev.preventDefault();
toggleOverlay(true);
try { await reloadFile(); }
catch (e) { pushErrorToDisplayQueue(e); }
toggleOverlay(false);
}
async function _willGetAuthToken(username, secret) {
try {
const challenge = (await willRequestChallenge(username)).content.challenge;
return (await willAnswerChallenge(username, secret, challenge)).content.token;
} catch (e) {
if (e instanceof UserDoesNotExistError || e instanceof SubtleDecryptError) {
throw new Error('Not authorized. Check username and password');
} else {
throw e;
}
}
}
/**
* Retrieve an authorization token.
*
* The token is cached unless the option {refresh: true} is provided.
* Use fetchJSONWithRetryOnAuthExpired() to automatically refresh it.
*/
const willGetAuthToken = (() => {
let token = null;
return async function(options) {
if (!token || (options || {}).refresh) {
token = await _willGetAuthToken(getValueAt('username'), getValueAt('secret'));
}
return token;
};
})();
async function willRequestChallenge(username) {
const url = new URL(STORE_URL + '/auth/request-challenge');
url.searchParams.append('username', username);
const parsedResponse = await fetchJSON(url.href);
if (parsedResponse.error) {
if (parsedResponse.error.code === 1005) {
throw new UserDoesNotExistError();
}
throw new CannotRequestChallengeError(parsedResponse.error);
}
return parsedResponse;
}
class UserDoesNotExistError extends Error {}
async function willAnswerChallenge(username, secret, challenge) {
const answer = await willDecryptCiphertext(challenge, secret);
const url = new URL(STORE_URL + '/auth/answer-challenge');
const parsedResponse = await fetchJSONWithRetryOnAuthExpired(url.href, {
method: 'POST',
body: JSON.stringify({ username, answer }),
});
if (parsedResponse.error) {
throw new CannotAnswerChallengeError(parsedResponse.error);
}
return parsedResponse;
}
class CannotRequestChallengeError extends Error {
constructor(jsonError) {
super(`Couldn't start authentication. Server response was: ` +
`[${jsonError.code}] ${jsonError.message}`);
}
}
class CannotAnswerChallengeError extends Error {
constructor(jsonError) {
super(`Couldn't authenticate. Server response was: ` +
`[${jsonError.code}] ${jsonError.message}`);
}
}
function getRandomLowercaseString(length) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return bufferToString(array.map(x => x % 25 + 97))
}
const getFilenameOrDefault = (() => {
let _filename = null;
return ((defaultFilename) => {
_filename = _filename || defaultFilename || getRandomLowercaseString(32);
return _filename;
});
})();
async function onUploadCiphertextButtonClicked(ev) {
ev.preventDefault();
// XXX this is ok as long as we support just a single file
const filename = getFilenameOrDefault();
toggleOverlay(true);
try {
const ciphertext = getValueAt('ciphertext'); // Make a copy to prevent changes
const { uploadUrl, uploadFormData, retrieveUrl } = await willRequestUploadUrl(filename);
if ((uploadUrl + '/').slice(0, TRUSTED_UPLOAD_BASE_URL.length) !== TRUSTED_UPLOAD_BASE_URL) {
throw new UploadCiphertextError('The server proposed to upload the file to an untrusted url!');
}
await willUploadCiphertext(uploadUrl, uploadFormData, ciphertext);
const uploadedContent = await willDownload(retrieveUrl);
if (uploadedContent !== ciphertext) {
throw new UploadCiphertextError('The uploaded file does not match the original file');
}
console.log('Cool, the file was uploaded correctly!');
} catch (e) {
if (e instanceof UploadCiphertextError || e instanceof CannotRequestUploadUrlError) {
pushErrorToDisplayQueue(e);
} else {
console.error('Error uploading the ciphertext', e);
pushErrorToDisplayQueue(new Error('Error uploading the ciphertext'));
}
}
toggleOverlay(false);
};
async function reloadFile() {
try {
const files = await willGetFilesList();
let ciphertext = '';
if (files.length > 0) {
getFilenameOrDefault(files[0].content.filename);
ciphertext = await willDownload(files[0].links.read.href);
}
setValueAt('ciphertext', ciphertext);
updatePlaintextFromCiphertext();
} catch (e) {
if (e instanceof CannotRetrieveFilesListError || e instanceof DownloadError) {
throw e;
} else {
console.error(e);
throw new Error('An error occurred while reloading the ciphertext');
}
}
}
async function willRequestUploadUrl(filename) {
const href = STORE_URL + '/files/request-upload-url';
const token = await willGetAuthToken();
const parsedResponse = await fetchJSONWithRetryOnAuthExpired(href, {
method: 'POST',
body: JSON.stringify({
filename: filename,
}),
headers: {
Authorization: `Bearer ${token}`,
},
});
if (parsedResponse.error) {
throw new CannotRequestUploadUrlError(parsedResponse.error);
}
return {
uploadUrl: parsedResponse.links.upload_url.href,
uploadFormData: parsedResponse.links.upload_url.form_data,
retrieveUrl: parsedResponse.links.retrieve_url.href,
};
}
class CannotRequestUploadUrlError extends Error {
constructor(jsonError) {
super(`Cannot get the url to upload to. Server response was: ` +
`[${jsonError.code}] ${jsonError.message}`);
}
}
async function willUploadCiphertext(uploadUrl, uploadFormData, ciphertext) {
try {
const formData = new FormData();
for (let [key, value] of Object.entries(uploadFormData)) {
formData.append(key, value);
}
const blob = new Blob([ciphertext], { type: "text/plain"});
formData.append("file", blob);
const response = await fetchOrThrow(uploadUrl, {
headers: {
'Cache-Control': 'None',
'Expect': '100-continue',
'Content-Encoding': 'utf-8',
// XXX ... no md5 in crypto subtle, so we can't rely on it.
// We'll have to download the file and verify his content later
// 'Content-MD5': 'application/json',
},
method: 'POST',
body: formData,
});
if (!response.ok) {
const responseContent = await response.text();
const errorDoc = (new window.DOMParser()).parseFromString(responseContent, "application/xml");
const errorMessageElem = errorDoc.querySelector('Error > Message');
const errorMessage = errorMessageElem === null ? responseContent : errorMessageElem.textContent;
throw new UploadCiphertextError('Couldn\'t upload the ciphertext, response was: ' + `${errorMessage}`);
}
return response;
} catch (e) {
if (e instanceof FetchUnexpectedError || e instanceof FetchRequestTimedOutError) {
throw new UploadCiphertextError(e.message);
} else {
throw e;
}
}
}
class UploadCiphertextError extends Error {};
async function willDownload(href) {
const response = await fetchOrThrow(href, {
mode: 'cors',
cache: 'no-store',
referrerPolicy: 'no-referrer',
});
if (response.ok) {
return response.text();
} else {
throw new DownloadError(response.statusText);
}
}
class DownloadError extends Error {
constructor(statusText) {
super(`Couldn't download the file. Server response was: ${statusText}`);
}
}
async function willGetFilesList() {
const href = STORE_URL + '/files/';
const token = await willGetAuthToken();
const jsonResponse = await fetchJSONWithRetryOnAuthExpired(href, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (jsonResponse.error) { throw new CannotRetrieveFilesListError(jsonResponse.error); }
return jsonResponse.content;
}
async function fetchJSONWithRetryOnAuthExpired(href, options) {
let response = await fetchJSON(href, options);
if (response.error && response.error.code === 1007) {
// 1007 means "token expired"
await willGetAuthToken({refresh: true});
response = await fetchJSON(href, options);
}
return response;
}
class FetchUnexpectedError extends Error {
constructor(e) {
console.error(e)
super("Cannot fetch an external resource: check your internet connection or configuration");
}
}
class FetchRequestTimedOutError extends Error {
constructor() {
super("The request is taking too long to complete");
}
}
class FetchUnexpectedFormat extends Error {}
class CannotRetrieveFilesListError extends Error {
constructor(jsonError) {
super(`Cannot retrieve the files' list. Server response was: ` +
`[${jsonError.code}] ${jsonError.message}`);
}
}
async function fetchOrThrow(href, options) {
const request = fetch(href, options)
.catch (e => { throw new FetchUnexpectedError(e); });
const timeout = new Promise((resolve, reject) => {
// XXX we should abort the request on timeout
setTimeout(() => reject(new FetchRequestTimedOutError()), 15000);
});
return Promise.race([timeout, request]);
}
async function fetchJSON(href, options = {}) {
options = {
mode: 'cors',
cache: 'no-store',
referrerPolicy: 'no-referrer',
...options,
headers: {
...options.headers,
'Content-Type': 'application/json',
},
};
const response = await fetchOrThrow(href, options);
if (response.headers.get('Content-Type').startsWith('application/json')) {
return response.json();
} else {
throw new FetchUnexpectedFormat(response.statusText);
}
}
async function attemptLogin() {
if (!Boolean(getValueAt('username')) && getValueAt('confirm-secret') !== getValueAt('secret')) {
window.alert('The passwords don\'t match');
} else {
toggleOverlay(true);
try {
if (getValueAt('username')) {
const token = await willGetAuthToken();
await reloadFile();
} else {
document.body.classList.remove('enable-external-actions');
}
document.body.classList.remove('require-login');
} catch (e) {
pushErrorToDisplayQueue(e);
}
toggleOverlay(false);
}
}
function debounce(func, wait) {
let timeoutId = undefined;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), wait || 50);
};
}
function onPageLoaded() {
// Encrypt on focus, but only if there are errors, to avoid updating the ciphertext unnecessarily.
$('plaintext').addEventListener('focus', ev => {
if (ciphertextHasError()) { encryptPlaintextAndSetCiphertext(); }
});
// Redo encryption if any of the fields used to encrypt has changed.
document.querySelectorAll('.change-ciphertext').forEach(elem => {
elem.addEventListener('input', debounce(ev => encryptPlaintextAndSetCiphertext()));
});
// Redo decryption if the ciphertext has changed (or may have changed).
$('ciphertext').addEventListener('input', debounce(ev => updatePlaintextFromCiphertext()));
$('ciphertext').addEventListener('focus', debounce(ev => updatePlaintextFromCiphertext()));
$('download-ciphertext').addEventListener('click', onDownloadCiphertextButtonClicked);
$('download-cleartext').addEventListener('click', onDownloadCleartextButtonClicked);
$('reload-ciphertext').addEventListener('click', onReloadCiphertextButtonClicked);
$('upload-ciphertext').addEventListener('click', onUploadCiphertextButtonClicked);
const isSecretConfirmed = () => getValueAt('confirm-secret') === getValueAt('secret') && getValueAt('secret');
$('confirm-secret').addEventListener('input', () => { $('login-btn').disabled = !isSecretConfirmed() ; });
$('secret' ).addEventListener('input', () => { $('login-btn').disabled = !Boolean(getValueAt('username')) && !isSecretConfirmed(); });
$('username' ).addEventListener('input', () => { $('confirm-secret').disabled = Boolean(getValueAt('username')); });
$('login-form').addEventListener('submit', ev => ev.preventDefault() || attemptLogin());
$('logout-btn').addEventListener('click', () => { document.location.reload(); });
}
</script>
</body>
</html>