-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfrontend.js
742 lines (633 loc) · 20 KB
/
frontend.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
/*global kjua, bootstrap, bip39Org*/
/**
* @file frontend.js
* @authors:
* Bip39 Org <info@bip39.org>
* @date 2023
* @license MIT LICENSE
* Each function may contain the original source referred by
* and may have a different open-source license from different authors.
*
* Frontend Javascript code to handle DOM Objects
*/
const defaultState = {
backup: false,
darkmode: false
};
let state = {
backup: false,
darkmode: false
};
/**
* Copy text value from the DOM input element
* Use it with `onclick="copy(this)"`
* @see {@link https://www.w3schools.com/howto/howto_js_copy_clipboard.asp}
*/
// eslint-disable-next-line no-unused-vars
const copy = (thisObject) => {
// Find the first input element from the input-group
const inputElement = Array.from(thisObject.parentNode.children).filter(p => (p.nodeName === 'INPUT' || p.nodeName === 'TEXTAREA'))[0];
// Select the text field
inputElement.focus();
inputElement.select();
inputElement.setSelectionRange(0, 99999); // For mobile devices
// Copy value of the input element
navigator.clipboard.writeText(inputElement.value);
const name = inputElement.name + ' ' ?? '';
alert(`Copied ${name}value to clipboard`);
};
/**
* Paste text from the clipboard
* Use it with `onclick="paste(this)"`
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText}
*/
// eslint-disable-next-line no-unused-vars
const paste = async (thisObject) => {
// Find the first input element from the input-group
const inputElement = Array.from(thisObject.parentNode.children).filter(p => (p.nodeName === 'INPUT' || p.nodeName === 'TEXTAREA'))[0];
// Grant permission first
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#using_the_clipboard_api
const permission = await navigator.permissions.query({name: 'clipboard-write'});
if (!['granted', 'prompt'].includes(permission.state)) {
throw new Error('Clipboard permission not granted');
}
const clipboard = await navigator.clipboard.readText();
inputElement.value = clipboard;
};
/**
* Switch password type input to text (Or vice versa)
*/
// eslint-disable-next-line no-unused-vars
const show = (thisObject) => {
// Find the first input element from the input-group
const inputElement = Array.from(thisObject.parentNode.children).filter(p => (p.nodeName === 'INPUT' || p.nodeName === 'TEXTAREA'))[0];
inputElement.type = (inputElement.type === 'password') ? 'text': 'password';
};
/**
* Switch Nav Pages
*/
let currentPage = 'main';
const nav = (page) => {
if (currentPage) {
document.getElementById(`nav-${currentPage}`).classList.remove('active');
document.getElementById(`nav-mobile-${currentPage}`).classList.remove('active');
document.getElementById(currentPage).classList.add('hide');
}
document.getElementById(`nav-${page}`).classList.add('active');
document.getElementById(`nav-mobile-${page}`).classList.add('active');
document.getElementById(page).classList.remove('hide');
currentPage = page;
};
const urlNav = () => {
const pageParams = window.location.href.split('#')[1];
if (pageParams) {
// Parse pageParams from URL excluding the query string
nav(pageParams.split('?')[0]);
}
};
urlNav();
/**
* Dark mode switch for Bootstrap
* https://stackoverflow.com/questions/63082529/how-to-properly-introduce-a-light-dark-mode-in-bootstrap
*/
const applyDarkmode = () => {
const currentMode = document.documentElement.getAttribute('data-bs-theme');
if (state.darkmode && (currentMode === 'auto' || currentMode === 'light')) {
document.documentElement.setAttribute('data-bs-theme', 'dark');
} else if (!state.darkmode && currentMode === 'dark') {
document.documentElement.setAttribute('data-bs-theme', 'light');
}
};
// eslint-disable-next-line no-unused-vars
const settings = () => new bootstrap.Modal('#settings', {}).toggle();
// eslint-disable-next-line no-unused-vars
const resetSettings = () => {
state.backup = defaultState.backup;
state.darkmode = defaultState.darkmode;
document.getElementById('settings-backup').value = `${defaultState.backup}`;
document.getElementById('settings-darkmode').value = `${defaultState.darkmode}`;
applyDarkmode();
};
// eslint-disable-next-line no-unused-vars
const applySettings = () => {
const isBackup = document.getElementById('settings-backup').value === 'true';
const isDarkmode = document.getElementById('settings-darkmode').value === 'true';
state.backup = isBackup;
state.darkmode = isDarkmode;
applyDarkmode();
};
/**
* Clear form input
*/
// eslint-disable-next-line no-unused-vars
const clearInput = (thisObject) => {
const inputs = document.getElementsByClassName(thisObject.parentNode.id);
// Hide generated value
Array.from(document.getElementsByClassName('generated')).forEach(input => {
input.style.display = 'none';
});
// Clear input value
Array.from(inputs).forEach(input => {
if (input.id === 'main-nonce') {
input.value = '0';
return;
}
input.value = '';
});
};
// eslint-disable-next-line no-unused-vars
const qrcode = (thisObject) => {
// Find the first input element from the input-group
const inputElement = Array.from(thisObject.parentNode.children).filter(p => (p.nodeName === 'INPUT' || p.nodeName === 'TEXTAREA'))[0];
const qrBody = document.getElementById('qrcode-body');
// Remove any canvas element if it has already
if (qrBody.children.length !== 0) {
Array.from(qrBody.children).forEach(c => c.remove());
}
const fill = state.darkmode ? '#fff' : undefined;
const back = state.darkmode ? '#212529' : undefined;
// Create QR element
const qrElement = kjua({
text: inputElement.value,
render: 'canvas',
size: 310,
fill,
back,
ecLevel: 'H',
});
// Append to the body
qrBody.append(qrElement);
// Show the modal
new bootstrap.Modal('#qrcode', {}).toggle();
};
const showError = (error) => {
const errMsg = (error instanceof Error && error.message) ? 'Error: ' + error.message : 'Error: ' + error;
const errorElement = document.getElementById('error');
errorElement.innerText = errMsg;
if (errorElement.classList.contains('hide')) {
errorElement.classList.remove('hide');
}
};
const clearError = () => {
const errorElement = document.getElementById('error');
errorElement.innerText = '';
if (!errorElement.classList.contains('hide')) {
errorElement.classList.add('hide');
}
};
const checkInt = (value, param, isOptional = false) => {
// parseInt takes a string and a radix
const parsedValue = parseInt(value);
if (isNaN(parsedValue)) {
if (isOptional) {
return undefined;
}
const errMsg = param
? `Invalid ${param} : ${value} is not a valid number`
: `Invalid param: ${value} is not a valid number.`;
throw new Error(errMsg);
}
return parsedValue;
};
const checkString = (value, param, isOptional = false, stringLength = 0) => {
if (!value || typeof value !== 'string' || value.length <= stringLength) {
if (isOptional) {
return undefined;
}
const errMsg = (value.length <= stringLength && param)
? `Invalid ${param} length: ${value} does not have a required ${stringLength} ${param.toLowerCase()} length`
: param
? `Invalid ${param} : ${value} is not a valid ${param.toLowerCase()} value`
: `Invalid argument: ${value} is not a valid string`;
throw new Error(errMsg);
}
return value;
};
const hexParser = (typedHex) => typedHex.data.slice(2);
const backupButton = (buttonId, backupString) => {
const button = document.getElementById(buttonId);
button.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(backupString));
};
const createEncryptedBackup = async (buttonId, backupTitle, backupObject, backupPassword) => {
// Backup without encryption
if (!backupPassword) {
const backupString = JSON.stringify(
{
title: backupTitle,
...backupObject
},
null,
2
);
backupButton(buttonId, backupString);
return;
}
const encString = await bip39org.encryptString(
JSON.stringify(backupObject),
backupPassword
);
const backupString = JSON.stringify({
title: backupTitle,
encrypted: encString
}, null, 2);
backupButton(buttonId, backupString);
};
// eslint-disable-next-line no-unused-vars
const generateMain = async () => {
try {
clearError();
if (!document.getElementById('main-email').value) {
alert('Email input is required');
throw new Error('Email input is required');
}
if (!document.getElementById('main-password').value) {
alert('Password input is required');
throw new Error('Password input is required');
}
const id = checkString(document.getElementById('main-email').value, 'ID', false, 5);
const password = checkString(document.getElementById('main-password').value, 'Password', false, 8);
let additional = checkString(document.getElementById('main-additional').value, 'Additional', true);
let nonce = checkInt(document.getElementById('main-nonce').value, 'Nonce', true);
const length = checkInt(document.getElementById('main-length').value, 'Length', true);
// Format default value to undefined
if (additional) {
// Replace comma with blank to single comma and split
additional = additional.replaceAll(', ', ',').split(',').filter(a => a);
}
const {
hex,
entropy,
entropy2,
mnemonic,
mnemonic2,
seed,
seed2,
} = await bip39org.generateMnemonicWithId(
id,
password,
additional,
length,
nonce
);
const additionalBackup = additional ? additional.join(',') : undefined;
// Create backup object
await createEncryptedBackup(
'main-backup',
'mnemonic-email-backup',
{
id,
password,
additional: additionalBackup,
nonce,
length,
hex,
entropy,
entropy2,
mnemonic,
mnemonic2,
seed,
seed2,
},
password
);
// Create generated input
document.getElementById('main-entropy1').value = entropy;
document.getElementById('main-mnemonic1').value = mnemonic;
document.getElementById('main-seed1').value = seed;
document.getElementById('main-entropy2').value = entropy2;
document.getElementById('main-mnemonic2').value = mnemonic2;
document.getElementById('main-seed2').value = seed2;
// Show generated input
Array.from(document.getElementsByClassName('generated')).forEach(e => {
e.style.display = 'block';
});
// Save backup file automatically
if (state.backup) {
document.getElementById('main-backup').click();
}
} catch (e) {
showError(e);
throw e;
}
};
/**
* Open the file and read it as a string
* https://stackoverflow.com/questions/16215771/how-to-open-select-file-dialog-via-js
* https://stackoverflow.com/questions/34495796/javascript-promises-with-filereader
*/
const openFile = (type) => new Promise((resolve, reject) => {
const input = document.createElement('input');
input.type = 'file';
input.onchange = (e) => {
// getting a hold of the file reference
const file = e.target.files[0];
// setting up the reader
const reader = new FileReader();
if (type === 'dataURL') {
reader.readAsDataURL(file);
} else {
reader.readAsText(file, 'UTF-8');
}
// here we tell the reader what to do when it's done reading...
reader.onload = (readerEvent) => {
const content = readerEvent.target.result; // this is the content!
resolve(content);
};
reader.onerror = reject;
};
input.click();
});
const askPassword = (throwOnCancel = true) => {
if (!throwOnCancel) {
document.getElementById('password-title').innerText = 'Enter your Backup Password (Optional)';
} else {
document.getElementById('password-title').innerText = 'Enter your Backup Password';
}
document.getElementById('decryption-password').value = '';
const passwordModal = new bootstrap.Modal('#password', {});
passwordModal.toggle();
const form = document.getElementById('password-form');
const submitElement = document.getElementById('password-submit');
const cancelElement = document.getElementById('password-cancel');
return new Promise((resolve, reject) => {
form.addEventListener('submit', () => {
passwordModal.hide();
resolve(document.getElementById('decryption-password').value);
});
submitElement.addEventListener('click', () => {
resolve(document.getElementById('decryption-password').value);
});
cancelElement.addEventListener('click', () => {
if (!throwOnCancel) {
resolve();
return;
}
reject(new Error('User canceled the password prompt'));
});
});
};
const openBackup = async (password) => {
const rawJson = JSON.parse(await openFile());
// Deal with unencrypted case
if (!rawJson.encrypted) {
return rawJson;
}
// Show password prompt if the password is not supplied
if (!password) {
try {
password = await askPassword();
} catch (e) {
alert('Password is required to load encrypted backup');
throw new Error('Password is required to load encrypted backup');
}
}
const decrypted = JSON.parse(await bip39org.decryptString(
rawJson.encrypted,
password
));
return {
title: rawJson.title,
...decrypted
};
};
// eslint-disable-next-line no-unused-vars
const importMain = async () => {
try {
clearError();
let password = checkString(document.getElementById('main-password').value, 'Password', true);
const {
title,
id,
additional,
nonce,
length,
entropy,
entropy2,
mnemonic,
mnemonic2,
seed,
seed2,
} = await openBackup(password);
if (title !== 'mnemonic-email-backup') {
const errMsg = `Wrong backup file ${title}, should be a mnemonic-email-backup json`;
throw new Error(errMsg);
}
// Create generated input
document.getElementById('main-email').value = id;
if (additional) {
document.getElementById('main-additional').value = additional;
}
if (nonce) {
document.getElementById('main-nonce').value = nonce;
}
if (length) {
document.getElementById('main-length').value = length;
}
document.getElementById('main-entropy1').value = entropy;
document.getElementById('main-mnemonic1').value = mnemonic;
document.getElementById('main-seed1').value = seed;
document.getElementById('main-entropy2').value = entropy2;
document.getElementById('main-mnemonic2').value = mnemonic2;
document.getElementById('main-seed2').value = seed2;
// Show generated input
Array.from(document.getElementsByClassName('generated')).forEach(e => {
e.style.display = 'block';
});
} catch (e) {
showError(e);
throw e;
}
};
const saveMnemonic = async (entropy, mnemonic, seed, doBackup = true) => {
// Create backup object
if (doBackup) {
const password = await askPassword(false);
await createEncryptedBackup(
'mnemonic-backup',
'mnemonic-backup',
{
password,
entropy,
mnemonic,
seed,
},
password
);
}
// Create generated input
document.getElementById('mnemonic-entropy').value = entropy;
document.getElementById('mnemonic-mnemonic').value = mnemonic;
document.getElementById('mnemonic-seed').value = seed;
if (doBackup && state.backup) {
// Save the backup file automatically
document.getElementById('mnemonic-backup').click();
}
};
// eslint-disable-next-line no-unused-vars
const random = async () => {
try {
clearError();
let length = checkInt(document.getElementById('mnemonic-length').value, 'Length', true);
const {
entropy,
mnemonic,
seed,
} = await bip39org.getRandomMnemonic(length);
await saveMnemonic(
entropy,
mnemonic,
seed
);
} catch (e) {
showError(e);
throw e;
}
};
// eslint-disable-next-line no-unused-vars
const entropy = async () => {
try {
clearError();
const entropy = checkString(document.getElementById('mnemonic-entropy').value, 'Entropy');
let length = checkInt(document.getElementById('mnemonic-length').value, 'Length', true);
const {
newEntropy,
mnemonic,
seed,
} = await bip39org.getMnemonic(
entropy,
length
);
await saveMnemonic(
newEntropy || entropy,
mnemonic,
seed
);
} catch (e) {
showError(e);
throw e;
}
};
// eslint-disable-next-line no-unused-vars
const mnemonic = async () => {
try {
clearError();
const mnemonic = checkString(document.getElementById('mnemonic-mnemonic').value, 'Mnemonic');
const entropy = bip39org.mnemonicToEntropy(mnemonic);
const seed = (await bip39org.mnemonicToSeed(mnemonic)).toString('hex');
await saveMnemonic(
entropy,
mnemonic,
seed
);
} catch (e) {
showError(e);
throw e;
}
};
// eslint-disable-next-line no-unused-vars
const importMnemonic = async () => {
try {
clearError();
const {
title,
entropy,
mnemonic,
seed,
} = await openBackup();
if (title !== 'mnemonic-backup') {
const errMsg = `Wrong backup file ${title}, should be a mnemonic-backup json`;
throw new Error(errMsg);
}
console.log('Loaded Backup Object:\n\n' + JSON.stringify({
title,
entropy,
mnemonic,
seed,
}, null, 2));
await saveMnemonic(
entropy,
mnemonic,
seed,
false
);
} catch (e) {
showError(e);
throw e;
}
};
// eslint-disable-next-line no-unused-vars
const encrypt = async () => {
try {
clearError();
if (!document.getElementById('encrypt-raw').value) {
alert('Text input is required');
throw new Error('Text input is required');
}
if (!document.getElementById('encrypt-password').value) {
alert('Password input is required');
throw new Error('Password input is required');
}
const raw = checkString(document.getElementById('encrypt-raw').value, 'Plain-text');
const password = checkString(document.getElementById('encrypt-password').value, 'Password');
const encString = await bip39org.encryptString(
raw,
password
);
backupButton('encrypt-backup', encString);
document.getElementById('encrypt-enc').value = encString;
} catch (e) {
showError(e);
throw e;
}
};
// eslint-disable-next-line no-unused-vars
const decrypt = async () => {
try {
clearError();
if (!document.getElementById('encrypt-enc').value) {
alert('Encrypted value is required');
throw new Error('Encrypted value is required');
}
if (!document.getElementById('encrypt-password').value) {
alert('Password input is required');
throw new Error('Password input is required');
}
const enc = checkString(document.getElementById('encrypt-enc').value, 'Encrypted');
const password = checkString(document.getElementById('encrypt-password').value, 'Password');
const decString = await bip39org.decryptString(
enc,
password
);
document.getElementById('encrypt-raw').value = decString;
} catch (e) {
showError(e);
throw e;
}
};
// eslint-disable-next-line no-unused-vars
const importEncrypted = async () => {
try {
clearError();
let password = checkString(document.getElementById('encrypt-password').value, 'Password', true);
const importedText = await openFile();
// Show password prompt if the password is not supplied
if (!password) {
try {
password = await askPassword();
} catch (e) {
alert('Password is required to load encrypted backup');
throw new Error('Password is required to load encrypted backup');
}
}
const decString = await bip39org.decryptString(
importedText,
password
);
document.getElementById('encrypt-raw').value = decString;
document.getElementById('encrypt-enc').value = importedText;
document.getElementById('encrypt-password').value = password;
} catch (e) {
showError(e);
throw e;
}
};