-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
685 lines (631 loc) · 22.6 KB
/
app.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
const secretfileVersion = 1; // Version of the secretfile format
const appVersion = "1.2"; // Version of the app
let entryCounter = 0;
function updateEditor() {
document.querySelectorAll(".alertEmpty").forEach((alert) => {
if (entryCounter === 0) {
alert.style.display = "block";
} else {
alert.style.display = "none";
}
});
const fileLoadInput = document.getElementById("secretfile-load-file");
fileLoadInput.value = "";
}
function clearInputs() {
document.querySelectorAll("input").forEach((input) => {
input.value = "";
});
}
function clearSecretfile() {
swal
.fire({
title: "Are you sure?",
text: "This will clear all entries from the currently open secretfile!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, clear it!",
confirmButtonColor: "#d33",
})
.then((result) => {
if (result.isConfirmed) {
clearAllEntries();
swal.fire({
icon: "success",
title: "File Cleared!",
text: "The currenty open file has been cleared.",
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
toast: true,
position: "bottom-start",
});
}
});
updateEditor();
}
function addEntry(entry, passphrase) {
// This function adds a new entry to the editor. If an entry is passed, it will be used to populate the fields.
// If a passphrase is passed, it will be used to decrypt the sensitive data of the entry.
entryCounter++;
let accountName = entry
? passphrase
? decryptString(entry.accountName, passphrase)
: entry.accountName
: "";
let accountLogin = entry
? passphrase
? decryptString(entry.accountLogin, passphrase)
: entry.accountLogin
: "";
let otpSecret = entry
? passphrase
? decryptString(entry.otpSecret, passphrase)
: entry.otpSecret
: "";
let otpDigits = entry ? entry.otpDigits : 6;
let otpTime = entry ? entry.otpTime : 30;
let newEditorEntry = document.createElement("div");
newEditorEntry.className = "secretfileEditorEntry";
newEditorEntry.id = `secretfileEditorEntry-${entryCounter}`;
newEditorEntry.innerHTML = `
<div class="card entry">
<h3 class="card-header">Entry ${entryCounter}</h3>
<div class ="form-group card-body">
<label for="secretfileEditorEntry-name">Account Name <i class="fa-solid fa-circle-question help" onclick="showHelp('accountName')"></i></label>
<input type="text" class="form-control" id="secretfileEditorEntry-accountName" placeholder="Google Account" value="${accountName}">
<label for="secretfileEditorEntry-login">Login/Email Address <i class="fa-solid fa-circle-question help" onclick="showHelp('accountLogin')"></i></label>
<input type="text" class="form-control" id="secretfileEditorEntry-accountLogin" placeholder="example@example.com" value="${accountLogin}">
<label for="secretfileEditorEntry-secret">Secret <i class="fa-solid fa-circle-question help" onclick="showHelp('otpSecret')"></i></label>
<input type="text" class="form-control" id="secretfileEditorEntry-otpSecret" placeholder="JBSWY3DPEHPK3PXP" value="${otpSecret}">
<label for="secretfileEditorEntry-otpDigits">Number of digits <i class="fa-solid fa-circle-question help" onclick="showHelp('otpDigits')"></i></label>
<input type="number" class="form-control" id="secretfileEditorEntry-otpDigits" placeholder="6" value="${otpDigits}">
<label for="secretfileEditorEntry-otpTime">OTP expiry time (In seconds) <i class="fa-solid fa-circle-question help" onclick="showHelp('otpTime')"></i></label>
<input type="number" class="form-control" id="secretfileEditorEntry-otpTime" placeholder="30" value="${otpTime}">
<br>
<button class="btn btn-danger entry-delete" onclick="deleteEntry(${entryCounter})"><i class="fa-solid fa-trash-can"></i> Delete entry</button>
<button class="btn btn-primary" onclick="verifyEntry(${entryCounter})"><i class="fa-solid fa-key"></i> Generate OTP</button>
</div>
</div>
`;
document.getElementById("editor-entries").appendChild(newEditorEntry);
updateEditor();
}
function addEntryToViewer(entry, passphrase, entryId) {
let accountName = entry
? passphrase
? decryptString(entry.accountName, passphrase)
: entry.accountName
: "";
let accountLogin = entry
? passphrase
? decryptString(entry.accountLogin, passphrase)
: entry.accountLogin
: "";
let otpSecret = entry
? passphrase
? decryptString(entry.otpSecret, passphrase)
: entry.otpSecret
: "";
let otpDigits = entry ? entry.otpDigits : 6;
let otpTime = entry ? entry.otpTime : 30;
let otpAuthURI = `otpauth://totp/${accountName}:${accountLogin}?secret=${otpSecret}&digits=${otpDigits}&period=${otpTime}`;
let newViewerEntry = document.createElement("div");
newViewerEntry.className = "secretfileViewerEntry";
newViewerEntry.id = `secretfileViewerEntry-${entryCounter}`;
newViewerEntry.innerHTML = `
<div class="card entry">
<h3 class="card-header">Entry ${entryId ? entryId : entryCounter}</h3>
<div class="card-body row align-items-start">
<div class="col">
<div class="print-show" style="margin-top:10px;"></div>
<p><b>Account Name:</b> ${accountName} <a class="copyBtn" onclick="copyToClip('${accountName}')"><i class="fa-solid fa-copy fa-fw"></i></a></p>
<p><b>Login/Email Address:</b> ${accountLogin} <a class="copyBtn" onclick="copyToClip('${accountLogin}')"><i class="fa-solid fa-copy fa-fw"></i></a></p>
<p><b>Secret:</b> ${otpSecret} <a class="copyBtn" onclick="copyToClip('${otpSecret}')"><i class="fa-solid fa-copy fa-fw"></i></a></p>
<p><b>Number of digits:</b> ${otpDigits} <a class="copyBtn" onclick="copyToClip('${otpDigits}')"><i class="fa-solid fa-copy fa-fw"></i></a></p>
<p><b>OTP expiry time (In seconds):</b> ${otpTime} <a class="copyBtn" onclick="copyToClip('${otpTime}')"><i class="fa-solid fa-copy fa-fw"></i></a></p>
<button class="btn btn-primary" onclick="verifyEntry(${entryCounter})"><i class="fa-solid fa-key"></i> Generate OTP</button>
</div>
<div class="col text-end">
<div class="qrcode float-end"></div>
</div>
</div>
</div>
`;
let qrcode = new QRCode(newViewerEntry.querySelector(".qrcode"), {
text: otpAuthURI,
width: 220,
height: 220,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.L,
});
document.getElementById("viewer-entries").appendChild(newViewerEntry);
}
function verifyEntry(entryId) {
// Verifies fields of the entry and generates an OTP if everything is correct
let entry = document.querySelector(`#secretfileEditorEntry-${entryId}`);
let otpSecret = entry.querySelector(`#secretfileEditorEntry-otpSecret`).value;
let otpDigits = entry.querySelector(`#secretfileEditorEntry-otpDigits`).value;
let otpTime = entry.querySelector(`#secretfileEditorEntry-otpTime`).value;
if (!otpSecret || !otpDigits || !otpTime) {
Swal.fire({
title: "Missing settings!",
text: "Make sure all required fields are filled out",
icon: "error",
confirmButtonText: "Close",
});
return;
}
try {
let totp = new jsOTP.totp(otpTime, otpDigits);
let generatedOTP = totp.getOtp(otpSecret);
Swal.fire({
title: "Here's your OTP",
text: `OTP: ${generatedOTP}`,
icon: "success",
footer:
"Compare this OTP with your authenticator app. If the OTP doesn't match, make sure your configuration is correct and your system time is accurate.",
confirmButtonText: "Close",
});
} catch (e) {
Swal.fire({
title: "Something went wrong!",
text: e,
icon: "error",
confirmButtonText: "Close",
});
}
}
function deleteEntry(entryId) {
// Deletes an entry from the editor and updates the IDs of the remaining entries
const entries = document.getElementById("editor-entries");
let entry = document.getElementById(`secretfileEditorEntry-${entryId}`);
entry.remove();
entryCounter--;
entries.querySelectorAll(".secretfileEditorEntry").forEach((entry, i) => {
entry.id = `secretfileEditorEntry-${i + 1}`;
entry.querySelector("h3").innerHTML = `Entry ${i + 1}`;
entry
.querySelector(".entry-delete")
.setAttribute("onclick", `deleteEntry(${i + 1})`);
});
updateEditor();
}
function loadFile(droppedFile) {
let file = document.getElementById("secretfile-load-file").files[0];
// if a drag and dropped file is passed, use that instead of the file input
if (droppedFile) {
file = droppedFile;
}
if (
file.name.split(".").pop() != "json" &&
file.name.split(".").pop() != "secretfile"
) {
swal.fire({
icon: "error",
title: "Invalid Secretfile",
text: "Please select a valid .secretfile.json file",
});
return;
}
let reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = (readerEvent) => {
// Parse the file, and check if it's data is encrypted
let fileContent = JSON.parse(readerEvent.target.result);
let isEncrypted = fileContent.encrypted;
let passphrase;
if (isEncrypted && !droppedFile) {
passphrase = document.getElementById("secretfile-load-passphrase").value;
loadEntriesFromFile(fileContent, passphrase);
} else if (isEncrypted && droppedFile) {
swal
.fire({
title: "Passphrase required",
text: "This file is encryped, please enter the passphrase to decrypt it.",
input: "password",
showCancelButton: true,
confirmButtonText: "Decrypt",
cancelButtonText: "Cancel",
})
.then((result) => {
if (result.isConfirmed) {
passphrase = result.value;
loadEntriesFromFile(fileContent, passphrase);
} else {
return;
}
});
} else {
loadEntriesFromFile(fileContent, null);
}
};
}
function loadEntriesFromFile(fileContent, passphrase) {
clearAllEntries();
let entries = fileContent.entries;
let metadata = fileContent.metadata;
// The metadata object is optional, and doesn't exist in files created with editor version < 1.2
if (metadata) {
document.getElementById("editorMetadata-owner").value = metadata.owner;
document.getElementById("editorMetadata-description").value =
metadata.description;
document.getElementById("viewerMetadata-owner").innerHTML = metadata.owner;
document.getElementById("viewerMetadata-description").innerHTML =
metadata.description;
}
try {
entries.forEach((entry) => {
addEntry(entry, passphrase);
addEntryToViewer(entry, passphrase);
});
swal.fire({
icon: "success",
title: "Success!",
text: "Secretfile loaded successfully!",
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
toast: true,
position: "bottom-start",
});
} catch (e) {
swal.fire({
icon: "error",
title: "Failed to load secretfile",
text: "The passphrase you entered is incorrect, or the secretfile is corrupted. Please make sure you entered the correct passphrase and try again.",
});
}
updateEditor();
}
function saveFile() {
let passphrase = document.getElementById("secretfile-save-passphrase").value;
let entries = document.getElementById("editor-entries");
if (!passphrase) {
swal
.fire({
icon: "warning",
title: "Are you sure?",
text: "You haven't entered an encryption passphrase. This means your secretfile will be saved in plain text! Are you sure you want to continue?",
showCancelButton: true,
confirmButtonText: "Yes, save in plain text",
cancelButtonText: "No, cancel",
})
.then((result) => {
if (result.isConfirmed) {
generateFileContent(entries);
}
});
} else {
generateFileContent(entries, passphrase);
}
}
function updateViewerFromEditor() {
let entries = document.getElementById("editor-entries");
document.querySelectorAll(".secretfileViewerEntry").forEach((entry) => {
entry.remove();
});
let updateEntryCounter = 1;
let editorMetadata = {
owner: document.querySelector("#editorMetadata-owner").value,
description: document.querySelector("#editorMetadata-description").value
}
document.querySelector("#viewerMetadata-owner").innerHTML = editorMetadata.owner;
document.querySelector("#viewerMetadata-description").innerHTML = editorMetadata.description;
entries.querySelectorAll(".secretfileEditorEntry").forEach((entry) => {
let accountName = entry.querySelector(`#secretfileEditorEntry-accountName`);
let accountLogin = entry.querySelector(
`#secretfileEditorEntry-accountLogin`
);
let otpSecret = entry.querySelector(`#secretfileEditorEntry-otpSecret`);
let otpDigits = entry.querySelector(`#secretfileEditorEntry-otpDigits`);
let otpTime = entry.querySelector(`#secretfileEditorEntry-otpTime`);
addEntryToViewer(
{
accountName: accountName.value,
accountLogin: accountLogin.value,
otpSecret: otpSecret.value,
otpDigits: otpDigits.value,
otpTime: otpTime.value,
},
null,
updateEntryCounter
);
updateEntryCounter++;
});
}
function generateFileContent(entries, passphrase) {
let metadataOwner = document.getElementById("editorMetadata-owner").value;
let metadataDescription = document.getElementById(
"editorMetadata-description"
).value;
try {
let secretFileContent = `{
"version": ${secretfileVersion},
"encrypted": ${passphrase ? true : false},
"metadata": {
"owner": "${metadataOwner}",
"description": "${metadataDescription}"
},
"entries": [`;
entries.querySelectorAll(".secretfileEditorEntry").forEach((entry, i) => {
secretFileContent += `
{
"entryId": ${i + 1},
"accountName": "${
passphrase
? encryptString(
entry.querySelector(`#secretfileEditorEntry-accountName`).value,
passphrase
)
: entry.querySelector(`#secretfileEditorEntry-accountName`).value
}",
"accountLogin": "${
passphrase
? encryptString(
entry.querySelector(`#secretfileEditorEntry-accountLogin`).value,
passphrase
)
: entry.querySelector(`#secretfileEditorEntry-accountLogin`).value
}",
"otpSecret": "${
passphrase
? encryptString(
entry.querySelector(`#secretfileEditorEntry-otpSecret`).value,
passphrase
)
: entry.querySelector(`#secretfileEditorEntry-otpSecret`).value
}",
"otpDigits": ${
entry.querySelector(`#secretfileEditorEntry-otpDigits`).value
},
"otpTime": ${entry.querySelector(`#secretfileEditorEntry-otpTime`).value}
}`;
if (i !== entries.querySelectorAll(".secretfileEditorEntry").length - 1) {
secretFileContent += `,`;
}
});
secretFileContent += `
]
}`;
let filename = document.getElementById("secretfile-save-filename").value;
downloadFile(
secretFileContent,
`${filename}.secretfile.json`,
"application/json"
);
swal.fire({
icon: "success",
title: "Success!",
text: "Secretfile saved successfully!",
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
toast: true,
position: "bottom-start",
});
} catch (e) {
Swal.fire({
title: "Something went wrong!",
text: e,
icon: "error",
confirmButtonText: "Close",
});
console.error("An error occured: " + e);
}
}
function encryptString(string, passphrase) {
let output = CryptoJS.AES.encrypt(string, passphrase);
return output.toString();
}
function decryptString(string, passphrase) {
let output = CryptoJS.AES.decrypt(string, passphrase);
return output.toString(CryptoJS.enc.Utf8);
}
function downloadFile(data, filename, type) {
let file = new Blob([data], {
type: type,
});
if (window.navigator.msSaveOrOpenBlob)
window.navigator.msSaveOrOpenBlob(file, filename);
else {
let a = document.createElement("a");
let url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
function copyToClip(string) {
navigator.clipboard.writeText(string).then(
function () {
swal.fire({
icon: "success",
title: "Copied!",
text: "Data copied to clipboard!",
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
toast: true,
position: "bottom-start",
});
},
function (err) {
console.error("Error: Could not copy text: ", err);
Swal.fire({
title: "Something went wrong!",
text: err,
icon: "error",
confirmButtonText: "Close",
});
}
);
}
function clearAllEntries() {
document.querySelectorAll(".secretfileEditorEntry").forEach((entry) => {
entry.remove();
entryCounter--;
});
document.querySelectorAll(".secretfileViewerEntry").forEach((entry) => {
entry.remove();
});
document.querySelectorAll(".secretfileMetadataField").forEach((field) => {
field.value = "";
});
document.getElementById("viewerMetadata-owner").innerHTML = "";
document.getElementById("viewerMetadata-description").innerHTML = "";
updateEditor();
}
function showHelp(helpId) {
let defaultHelpIcon = "info";
let defaultHelpConfirmText = "Close";
switch (helpId) {
case "accountName":
Swal.fire({
title: "Account Name",
text: "The name of the account. This is used to identify the account provider (e.g. Google or Facebook).",
icon: defaultHelpIcon,
confirmButtonText: defaultHelpConfirmText,
});
break;
case "accountLogin":
Swal.fire({
title: "Login/Email Address",
text: "The login or email address associated with the account. This is used to identify the exact account for which the OTP will be generated.",
icon: defaultHelpIcon,
confirmButtonText: defaultHelpConfirmText,
});
break;
case "otpSecret":
Swal.fire({
title: "Secret",
text: "The secret value used to generate the OTP. This is usually a string of random characters.",
icon: defaultHelpIcon,
confirmButtonText: defaultHelpConfirmText,
});
break;
case "otpDigits":
Swal.fire({
title: "Number of digits",
text: "The number of digits in the generated OTP. This is usually 6, or (in rare cases) 8. If you are unsure, leave this at the default value.",
icon: defaultHelpIcon,
confirmButtonText: defaultHelpConfirmText,
});
break;
case "otpTime":
Swal.fire({
title: "OTP expiry time",
text: "The time in seconds for which the OTP will be valid. This is usually 30. If you are unsure, leave this at the default value.",
icon: defaultHelpIcon,
confirmButtonText: defaultHelpConfirmText,
});
break;
default:
showErrorMessage("invalidHelpId", helpId);
break;
}
}
function showErrorMessage(errorId, errorData) {
let defaultErrorIcon = "error";
let defaultErrorCancelText = "Close";
let defaultErrorConfirmText = "Report issue";
let defaultBugtrackerLink =
"https://github.com/hexandcube/secretfile-editor/issues/new";
switch (errorId) {
case "invalidHelpId":
Swal.fire({
title: "Something went wrong!",
text: "A help box with the specified ID could not be found. Please report this issue on GitHub.",
icon: defaultErrorIcon,
footer: `HelpId: ${errorData}`,
showCancelButton: true,
cancelButtonText: defaultErrorCancelText,
confirmButtonText: defaultErrorConfirmText,
focusCancel: true,
}).then((result) => {
if (result.isConfirmed) {
window.open(defaultBugtrackerLink);
}
});
break;
default:
Swal.fire({
title: "Something went wrong!",
text: "An unknown error occured. Please report this issue on GitHub.",
icon: defaultErrorIcon,
footer: `ErrorId: ${errorId}, ErrorData: ${errorData}`,
showCancelButton: true,
cancelButtonText: defaultErrorCancelText,
confirmButtonText: defaultErrorConfirmText,
focusCancel: true,
}).then((result) => {
if (result.isConfirmed) {
window.open(defaultBugtrackerLink);
}
});
break;
}
}
let dropArea = document.getElementById("drop-area");
let dropAreaOverlay = document.getElementById("drop-area-overlay");
function showDropArea(e) {
dropAreaOverlay.classList.remove("invisible");
}
function hideDropArea(e) {
dropAreaOverlay.classList.add("invisible");
}
function handleDrop(e) {
let dt = e.dataTransfer;
let files = dt.files;
handleDroppedFiles(files);
}
function handleDroppedFiles(files) {
[...files].forEach(loadFile);
}
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
window.onload = function () {
document.getElementById("secretfile-load-file").onchange = function (e) {
// Check if the file selected by the user is encrypted, and if so, show the passphrase input
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = (readerEvent) => {
let fileContent = readerEvent.target.result;
if (JSON.parse(fileContent).encrypted) {
document
.getElementById("secretfile-load-passphrase-div")
.classList.remove("hidden");
} else {
document
.getElementById("secretfile-load-passphrase-div")
.classList.add("hidden");
}
// Enable the load button once the user has selected a file
document
.getElementById("secretfile-load-confirmbtn")
.classList.remove("disabled");
};
};
dropArea.addEventListener("drop", handleDrop, false);
["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
dropArea.addEventListener(eventName, preventDefaults, false);
});
["dragenter", "dragover"].forEach((eventName) => {
dropArea.addEventListener(eventName, showDropArea, false);
});
["dragleave", "drop"].forEach((eventName) => {
dropArea.addEventListener(eventName, hideDropArea, false);
});
clearInputs();
updateEditor();
document.getElementById("version").innerHTML = `v${appVersion}`;
};