encryption converted to module

This commit is contained in:
azivner 2017-11-04 18:18:55 -04:00
parent b44c685f23
commit e7f0187b29
9 changed files with 428 additions and 396 deletions

View File

@ -60,10 +60,10 @@ const contextMenuSetup = {
noteEditor.createNote(node, node.key, 'into');
}
else if (ui.cmd === "encryptSubTree") {
encryptSubTree(node.key);
encryption.encryptSubTree(node.key);
}
else if (ui.cmd === "decryptSubTree") {
decryptSubTree(node.key);
encryption.decryptSubTree(node.key);
}
else if (ui.cmd === "cut") {
cut(node);

View File

@ -57,8 +57,8 @@ const noteHistory = (function() {
let noteText = historyItem.note_text;
if (historyItem.encryption > 0) {
noteTitle = decryptString(noteTitle);
noteText = decryptString(noteText);
noteTitle = encryption.decryptString(noteTitle);
noteText = encryption.decryptString(noteText);
}
titleEl.html(noteTitle);

View File

@ -86,19 +86,17 @@ settings.addModule((function() {
success: result => {
if (result.success) {
// encryption password changed so current encryption session is invalid and needs to be cleared
resetEncryptionSession();
encryption.resetEncryptionSession();
glob.encryptedDataKey = result.new_encrypted_data_key;
encryption.setEncryptedDataKey(result.new_encrypted_data_key);
alert("Password has been changed.");
$("#settings-dialog").dialog('close');
message("Password has been changed.");
}
else {
alert(result.message);
message(result.message);
}
},
error: () => alert("Error occurred during changing password.")
error: () => error("Error occurred during changing password.")
});
return false;
@ -122,7 +120,7 @@ settings.addModule((function() {
const encryptionTimeout = encryptionTimeoutEl.val();
settings.saveSettings(settingName, encryptionTimeout).then(() => {
glob.encryptionSessionTimeout = encryptionTimeout;
encryption.setEncryptionSessionTimeout(encryptionTimeout);
});
return false;

View File

@ -1,12 +1,34 @@
glob.encryptionDeferred = null;
const encryption = (function() {
const dialogEl = $("#encryption-password-dialog");
const encryptionPasswordFormEl = $("#encryption-password-form");
const encryptionPasswordEl = $("#encryption-password");
function handleEncryption(requireEncryption, modal) {
let encryptionDeferred = null;
let dataKey = null;
let lastEncryptionOperationDate = null;
let encryptionSalt = null;
let encryptedDataKey = null;
let encryptionSessionTimeout = null;
function setEncryptionSalt(encSalt) {
encryptionSalt = encSalt;
}
function setEncryptedDataKey(encDataKey) {
encryptedDataKey = encDataKey;
}
function setEncryptionSessionTimeout(encSessTimeout) {
encryptionSessionTimeout = encSessTimeout;
}
function ensureEncryptionIsAvailable(requireEncryption, modal) {
const dfd = $.Deferred();
if (requireEncryption && glob.dataKey === null) {
glob.encryptionDeferred = dfd;
if (requireEncryption && dataKey === null) {
encryptionDeferred = dfd;
$("#encryption-password-dialog").dialog({
dialogEl.dialog({
modal: modal,
width: 400,
open: () => {
@ -22,16 +44,13 @@ function handleEncryption(requireEncryption, modal) {
}
return dfd.promise();
}
}
glob.dataKey = null;
glob.lastEncryptionOperationDate = null;
function getDataKey(password) {
return computeScrypt(password, glob.encryptionSalt, (key, resolve, reject) => {
function getDataKey(password) {
return computeScrypt(password, encryptionSalt, (key, resolve, reject) => {
const dataKeyAes = getDataKeyAes(key);
const decryptedDataKey = decrypt(dataKeyAes, glob.encryptedDataKey);
const decryptedDataKey = decrypt(dataKeyAes, encryptedDataKey);
if (decryptedDataKey === false) {
reject("Wrong password.");
@ -39,9 +58,9 @@ function getDataKey(password) {
resolve(decryptedDataKey);
});
}
}
function computeScrypt(password, salt, callback) {
function computeScrypt(password, salt, callback) {
const normalizedPassword = password.normalize('NFKC');
const passwordBuffer = new buffer.SlowBuffer(normalizedPassword);
const saltBuffer = new buffer.SlowBuffer(salt);
@ -70,9 +89,9 @@ function computeScrypt(password, salt, callback) {
}
});
});
}
}
function decryptTreeItems() {
function decryptTreeItems() {
if (!isEncryptionAvailable()) {
return;
}
@ -86,23 +105,23 @@ function decryptTreeItems() {
note.setTitle(title);
}
}
}
}
$("#encryption-password-form").submit(() => {
const password = $("#encryption-password").val();
$("#encryption-password").val("");
encryptionPasswordFormEl.submit(() => {
const password = encryptionPasswordEl.val();
encryptionPasswordEl.val("");
getDataKey(password).then(key => {
$("#encryption-password-dialog").dialog("close");
dialogEl.dialog("close");
glob.dataKey = key;
dataKey = key;
decryptTreeItems();
if (glob.encryptionDeferred !== null) {
glob.encryptionDeferred.resolve();
if (encryptionDeferred !== null) {
encryptionDeferred.resolve();
glob.encryptionDeferred = null;
encryptionDeferred = null;
}
})
.catch(reason => {
@ -112,10 +131,10 @@ $("#encryption-password-form").submit(() => {
});
return false;
});
});
function resetEncryptionSession() {
glob.dataKey = null;
function resetEncryptionSession() {
dataKey = null;
if (noteEditor.getCurrentNote().detail.encryption > 0) {
noteEditor.loadNoteToEditor(noteEditor.getCurrentNoteId());
@ -128,42 +147,42 @@ function resetEncryptionSession() {
}
}
}
}
}
setInterval(() => {
if (glob.lastEncryptionOperationDate !== null && new Date().getTime() - glob.lastEncryptionOperationDate.getTime() > glob.encryptionSessionTimeout * 1000) {
setInterval(() => {
if (lastEncryptionOperationDate !== null && new Date().getTime() - lastEncryptionOperationDate.getTime() > encryptionSessionTimeout * 1000) {
resetEncryptionSession();
}
}, 5000);
}, 5000);
function isEncryptionAvailable() {
return glob.dataKey !== null;
}
function isEncryptionAvailable() {
return dataKey !== null;
}
function getDataAes() {
glob.lastEncryptionOperationDate = new Date();
function getDataAes() {
lastEncryptionOperationDate = new Date();
return new aesjs.ModeOfOperation.ctr(glob.dataKey, new aesjs.Counter(5));
}
return new aesjs.ModeOfOperation.ctr(dataKey, new aesjs.Counter(5));
}
function getDataKeyAes(key) {
function getDataKeyAes(key) {
return new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
}
}
function encryptNoteIfNecessary(note) {
function encryptNoteIfNecessary(note) {
if (note.detail.encryption === 0) {
return note;
}
else {
return encryptNote(note);
}
}
}
function encryptString(str) {
function encryptString(str) {
return encrypt(getDataAes(), str);
}
}
function encrypt(aes, str) {
function encrypt(aes, str) {
const payload = aesjs.utils.utf8.toBytes(str);
const digest = sha256Array(payload).slice(0, 4);
@ -172,15 +191,15 @@ function encrypt(aes, str) {
const encryptedBytes = aes.encrypt(digestWithPayload);
return uint8ToBase64(encryptedBytes);
}
}
function decryptString(encryptedBase64) {
function decryptString(encryptedBase64) {
const decryptedBytes = decrypt(getDataAes(), encryptedBase64);
return aesjs.utils.utf8.fromBytes(decryptedBytes);
}
}
function decrypt(aes, encryptedBase64) {
function decrypt(aes, encryptedBase64) {
const encryptedBytes = base64ToUint8Array(encryptedBase64);
const decryptedBytes = aes.decrypt(encryptedBytes);
@ -197,9 +216,9 @@ function decrypt(aes, encryptedBase64) {
}
return payload;
}
}
function concat(a, b) {
function concat(a, b) {
const result = [];
for (let key in a) {
@ -211,34 +230,34 @@ function concat(a, b) {
}
return result;
}
}
function sha256Array(content) {
function sha256Array(content) {
const hash = sha256.create();
hash.update(content);
return hash.array();
}
}
function arraysIdentical(a, b) {
function arraysIdentical(a, b) {
let i = a.length;
if (i !== b.length) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
}
}
function encryptNote(note) {
function encryptNote(note) {
note.detail.note_title = encryptString(note.detail.note_title);
note.detail.note_text = encryptString(note.detail.note_text);
note.detail.encryption = 1;
return note;
}
}
async function encryptNoteAndSendToServer() {
await handleEncryption(true, true);
async function encryptNoteAndSendToServer() {
await ensureEncryptionIsAvailable(true, true);
const note = noteEditor.getCurrentNote();
@ -251,9 +270,9 @@ async function encryptNoteAndSendToServer() {
await changeEncryptionOnNoteHistory(note.detail.note_id, true);
noteEditor.setNoteBackgroundIfEncrypted(note);
}
}
async function changeEncryptionOnNoteHistory(noteId, encrypt) {
async function changeEncryptionOnNoteHistory(noteId, encrypt) {
const result = await $.ajax({
url: baseApiUrl + 'notes-history/' + noteId + "?encryption=" + (encrypt ? 0 : 1),
type: 'GET',
@ -282,10 +301,10 @@ async function changeEncryptionOnNoteHistory(noteId, encrypt) {
console.log('Note history ' + row.note_history_id + ' de/encrypted');
}
}
}
async function decryptNoteAndSendToServer() {
await handleEncryption(true, true);
async function decryptNoteAndSendToServer() {
await ensureEncryptionIsAvailable(true, true);
const note = noteEditor.getCurrentNote();
@ -298,21 +317,21 @@ async function decryptNoteAndSendToServer() {
await changeEncryptionOnNoteHistory(note.detail.note_id, false);
noteEditor.setNoteBackgroundIfEncrypted(note);
}
}
function decryptNoteIfNecessary(note) {
function decryptNoteIfNecessary(note) {
if (note.detail.encryption > 0) {
decryptNote(note);
}
}
}
function decryptNote(note) {
function decryptNote(note) {
note.detail.note_title = decryptString(note.detail.note_title);
note.detail.note_text = decryptString(note.detail.note_text);
}
}
async function encryptSubTree(noteId) {
await handleEncryption(true, true);
async function encryptSubTree(noteId) {
await ensureEncryptionIsAvailable(true, true);
updateSubTreeRecursively(noteId, note => {
if (note.detail.encryption === null || note.detail.encryption === 0) {
@ -336,10 +355,10 @@ async function encryptSubTree(noteId) {
});
message("Encryption finished.");
}
}
async function decryptSubTree(noteId) {
await handleEncryption(true, true);
async function decryptSubTree(noteId) {
await ensureEncryptionIsAvailable(true, true);
updateSubTreeRecursively(noteId, note => {
if (note.detail.encryption === 1) {
@ -363,9 +382,9 @@ async function decryptSubTree(noteId) {
});
message("Decryption finished.");
}
}
function updateSubTreeRecursively(noteId, updateCallback, successCallback) {
function updateSubTreeRecursively(noteId, updateCallback, successCallback) {
updateNoteSynchronously(noteId, updateCallback, successCallback);
const node = getNodeByKey(noteId);
@ -376,9 +395,9 @@ function updateSubTreeRecursively(noteId, updateCallback, successCallback) {
for (const child of node.getChildren()) {
updateSubTreeRecursively(child.key, updateCallback, successCallback);
}
}
}
function updateNoteSynchronously(noteId, updateCallback, successCallback) {
function updateNoteSynchronously(noteId, updateCallback, successCallback) {
$.ajax({
url: baseApiUrl + 'notes/' + noteId,
type: 'GET',
@ -414,4 +433,23 @@ function updateNoteSynchronously(noteId, updateCallback, successCallback) {
console.log("Reading " + noteId + " failed.");
}
});
}
}
return {
setEncryptionSalt,
setEncryptedDataKey,
setEncryptionSessionTimeout,
ensureEncryptionIsAvailable,
decryptTreeItems,
resetEncryptionSession,
isEncryptionAvailable,
encryptNoteIfNecessary,
encryptString,
decryptString,
encryptNoteAndSendToServer,
decryptNoteAndSendToServer,
decryptNoteIfNecessary,
encryptSubTree,
decryptSubTree
};
})();

View File

@ -1,7 +1,6 @@
const noteEditor = (function() {
const noteTitleEl = $("#note-title");
const noteDetailEl = $('#note-detail');
const noteEditableEl = $(".note-editable");
const encryptButton = $("#encrypt-button");
const decryptButton = $("#decrypt-button");
const noteDetailWrapperEl = $("#note-detail-wrapper");
@ -44,7 +43,7 @@ const noteEditor = (function() {
updateNoteFromInputs(note);
encryptNoteIfNecessary(note);
encryption.encryptNoteIfNecessary(note);
await saveNoteToServer(note);
}
@ -112,12 +111,12 @@ const noteEditor = (function() {
async function createNote(node, parentKey, target, encryption) {
// if encryption isn't available (user didn't enter password yet), then note is created as unencrypted
// but this is quite weird since user doesn't see where the note is being created so it shouldn't occur often
if (!encryption || !isEncryptionAvailable()) {
if (!encryption || !encryption.isEncryptionAvailable()) {
encryption = 0;
}
const newNoteName = "new note";
const newNoteNameEncryptedIfNecessary = encryption > 0 ? encryptString(newNoteName) : newNoteName;
const newNoteNameEncryptedIfNecessary = encryption > 0 ? encryption.encryptString(newNoteName) : newNoteName;
const result = await $.ajax({
url: baseApiUrl + 'notes/' + parentKey + '/children' ,
@ -163,12 +162,12 @@ const noteEditor = (function() {
function setNoteBackgroundIfEncrypted(note) {
if (note.detail.encryption > 0) {
noteEditableEl.addClass("encrypted");
$(".note-editable").addClass("encrypted");
encryptButton.hide();
decryptButton.show();
}
else {
noteEditableEl.removeClass("encrypted");
$(".note-editable").removeClass("encrypted");
encryptButton.show();
decryptButton.hide();
}
@ -187,7 +186,7 @@ const noteEditor = (function() {
noteTitleEl.focus().select();
}
await handleEncryption(note.detail.encryption > 0, false);
await encryption.ensureEncryptionIsAvailable(note.detail.encryption > 0, false);
noteDetailWrapperEl.show();
@ -199,7 +198,7 @@ const noteEditor = (function() {
encryptionPasswordEl.val('');
decryptNoteIfNecessary(note);
encryption.decryptNoteIfNecessary(note);
noteTitleEl.val(note.detail.note_title);
@ -222,11 +221,11 @@ const noteEditor = (function() {
async function loadNote(noteId) {
const note = await $.get(baseApiUrl + 'notes/' + noteId);
if (note.detail.encryption > 0 && !isEncryptionAvailable()) {
if (note.detail.encryption > 0 && !encryption.isEncryptionAvailable()) {
return;
}
decryptNoteIfNecessary(note);
encryption.decryptNoteIfNecessary(note);
return note;
}
@ -245,7 +244,7 @@ const noteEditor = (function() {
});
// so that tab jumps from note title (which has tabindex 1)
noteEditableEl.attr("tabindex", 2);
$(".note-editable").attr("tabindex", 2);
});
setInterval(saveNoteIfChanged, 5000);

View File

@ -29,7 +29,7 @@ async function checkStatus() {
// this will also reload the note content
await glob.tree.fancytree('getTree').reload(treeResp.notes);
decryptTreeItems();
encryption.decryptTreeItems();
}
$("#changesToPushCount").html(resp.changesToPushCount);

View File

@ -81,9 +81,6 @@ function setExpandedToServer(note_id, is_expanded) {
});
}
glob.encryptionSalt;
glob.encryptionSessionTimeout;
glob.encryptedDataKey;
glob.treeLoadTime;
function initFancyTree(notes, startNoteId) {
@ -181,9 +178,9 @@ function loadTree() {
return $.get(baseApiUrl + 'tree').then(resp => {
const notes = resp.notes;
let startNoteId = resp.start_note_id;
glob.encryptionSalt = resp.password_derived_key_salt;
glob.encryptionSessionTimeout = resp.encryption_session_timeout;
glob.encryptedDataKey = resp.encrypted_data_key;
encryption.setEncryptionSalt(resp.password_derived_key_salt);
encryption.setEncryptionSessionTimeout(resp.encryption_session_timeout);
encryption.setEncryptedDataKey(resp.encrypted_data_key);
glob.treeLoadTime = resp.tree_load_time;
// add browser ID header to all AJAX requests

View File

@ -40,7 +40,7 @@ function getFullName(noteId) {
const path = [];
while (note) {
if (note.data.encryption > 0 && !isEncryptionAvailable()) {
if (note.data.encryption > 0 && !encryption.isEncryptionAvailable()) {
path.push("[encrypted]");
}
else {

View File

@ -64,7 +64,7 @@
<div class="hide-toggle" style="grid-area: title;">
<div style="display: flex; align-items: center;">
<a onclick="encryptNoteAndSendToServer()"
<a onclick="encryption.encryptNoteAndSendToServer()"
title="Encrypt the note so that password will be required to view the note"
class="icon-action"
id="encrypt-button"
@ -72,7 +72,7 @@
<img src="images/icons/lock.png" alt="Encrypt note"/>
</a>
<a onclick="decryptNoteAndSendToServer()"
<a onclick="encryption.decryptNoteAndSendToServer()"
title="Decrypt note permamently so that password will not be required to access this note in the future"
class="icon-action"
id="decrypt-button"