trilium/public/javascripts/encryption.js

455 lines
13 KiB
JavaScript
Raw Normal View History

2017-11-05 06:18:55 +08:00
const encryption = (function() {
const dialogEl = $("#encryption-password-dialog");
const encryptionPasswordFormEl = $("#encryption-password-form");
const encryptionPasswordEl = $("#encryption-password");
let encryptionDeferred = null;
let dataKey = null;
let lastEncryptionOperationDate = null;
let encryptionSalt = null;
let encryptedDataKey = null;
let encryptionSessionTimeout = null;
function setEncryptionSalt(encSalt) {
encryptionSalt = encSalt;
}
2017-11-05 06:18:55 +08:00
function setEncryptedDataKey(encDataKey) {
encryptedDataKey = encDataKey;
}
2017-11-05 06:18:55 +08:00
function setEncryptionSessionTimeout(encSessTimeout) {
encryptionSessionTimeout = encSessTimeout;
}
2017-11-05 06:18:55 +08:00
function ensureEncryptionIsAvailable(requireEncryption, modal) {
const dfd = $.Deferred();
2017-11-05 06:18:55 +08:00
if (requireEncryption && dataKey === null) {
encryptionDeferred = dfd;
2017-11-05 06:18:55 +08:00
dialogEl.dialog({
modal: modal,
width: 400,
open: () => {
if (!modal) {
// dialog steals focus for itself, which is not what we want for non-modal (viewing)
getNodeByKey(noteEditor.getCurrentNoteId()).setFocus();
}
}
});
}
else {
dfd.resolve();
}
2017-11-05 06:18:55 +08:00
return dfd.promise();
}
2017-11-05 06:18:55 +08:00
function getDataKey(password) {
return computeScrypt(password, encryptionSalt, (key, resolve, reject) => {
const dataKeyAes = getDataKeyAes(key);
2017-11-05 06:18:55 +08:00
const decryptedDataKey = decrypt(dataKeyAes, encryptedDataKey);
2017-11-05 06:18:55 +08:00
if (decryptedDataKey === false) {
reject("Wrong password.");
}
2017-11-05 06:18:55 +08:00
resolve(decryptedDataKey);
});
}
2017-11-05 06:18:55 +08:00
function computeScrypt(password, salt, callback) {
const normalizedPassword = password.normalize('NFKC');
const passwordBuffer = new buffer.SlowBuffer(normalizedPassword);
const saltBuffer = new buffer.SlowBuffer(salt);
2017-11-05 06:18:55 +08:00
// this settings take ~500ms on my laptop
const N = 16384, r = 8, p = 1;
// 32 byte key - AES 256
const dkLen = 32;
2017-11-05 06:18:55 +08:00
const startedDate = new Date();
2017-11-05 06:18:55 +08:00
return new Promise((resolve, reject) => {
scrypt(passwordBuffer, saltBuffer, N, r, p, dkLen, (error, progress, key) => {
if (error) {
console.log("Error: " + error);
2017-11-05 06:18:55 +08:00
reject();
}
else if (key) {
console.log("Computation took " + (new Date().getTime() - startedDate.getTime()) + "ms");
callback(key, resolve, reject);
}
else {
// update UI with progress complete
}
});
});
}
2017-11-05 06:18:55 +08:00
function decryptTreeItems() {
if (!isEncryptionAvailable()) {
return;
}
for (const noteId of glob.allNoteIds) {
const note = getNodeByKey(noteId);
2017-11-05 06:18:55 +08:00
if (note.data.encryption > 0) {
const title = decryptString(note.data.note_title);
2017-11-05 06:18:55 +08:00
note.setTitle(title);
}
}
}
2017-11-05 06:18:55 +08:00
encryptionPasswordFormEl.submit(() => {
const password = encryptionPasswordEl.val();
encryptionPasswordEl.val("");
2017-11-05 06:18:55 +08:00
getDataKey(password).then(key => {
dialogEl.dialog("close");
2017-11-05 06:18:55 +08:00
dataKey = key;
2017-09-17 12:18:03 +08:00
2017-11-05 06:18:55 +08:00
decryptTreeItems();
2017-11-05 06:18:55 +08:00
if (encryptionDeferred !== null) {
encryptionDeferred.resolve();
2017-11-05 06:18:55 +08:00
encryptionDeferred = null;
}
})
.catch(reason => {
console.log(reason);
2017-11-05 06:18:55 +08:00
error(reason);
});
2017-11-05 06:18:55 +08:00
return false;
});
2017-11-05 06:18:55 +08:00
function resetEncryptionSession() {
dataKey = null;
2017-11-05 06:18:55 +08:00
if (noteEditor.getCurrentNote().detail.encryption > 0) {
noteEditor.loadNoteToEditor(noteEditor.getCurrentNoteId());
2017-11-05 06:18:55 +08:00
for (const noteId of glob.allNoteIds) {
const note = getNodeByKey(noteId);
2017-11-05 06:18:55 +08:00
if (note.data.encryption > 0) {
note.setTitle("[encrypted]");
}
}
}
}
2017-11-05 06:18:55 +08:00
setInterval(() => {
if (lastEncryptionOperationDate !== null && new Date().getTime() - lastEncryptionOperationDate.getTime() > encryptionSessionTimeout * 1000) {
resetEncryptionSession();
}
}, 5000);
2017-11-05 06:18:55 +08:00
function isEncryptionAvailable() {
return dataKey !== null;
}
2017-11-05 06:18:55 +08:00
function getDataAes() {
lastEncryptionOperationDate = new Date();
2017-11-05 06:18:55 +08:00
return new aesjs.ModeOfOperation.ctr(dataKey, new aesjs.Counter(5));
}
2017-11-05 06:18:55 +08:00
function getDataKeyAes(key) {
return new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
}
2017-11-05 06:18:55 +08:00
function encryptNoteIfNecessary(note) {
if (note.detail.encryption === 0) {
return note;
}
else {
return encryptNote(note);
}
}
2017-11-05 06:18:55 +08:00
function encryptString(str) {
return encrypt(getDataAes(), str);
}
2017-11-05 06:18:55 +08:00
function encrypt(aes, str) {
const payload = aesjs.utils.utf8.toBytes(str);
const digest = sha256Array(payload).slice(0, 4);
2017-11-05 06:18:55 +08:00
const digestWithPayload = concat(digest, payload);
2017-11-05 06:18:55 +08:00
const encryptedBytes = aes.encrypt(digestWithPayload);
2017-11-05 06:18:55 +08:00
return uint8ToBase64(encryptedBytes);
}
2017-11-05 06:18:55 +08:00
function decryptString(encryptedBase64) {
const decryptedBytes = decrypt(getDataAes(), encryptedBase64);
2017-11-05 06:18:55 +08:00
return aesjs.utils.utf8.fromBytes(decryptedBytes);
}
2017-11-05 06:18:55 +08:00
function decrypt(aes, encryptedBase64) {
const encryptedBytes = base64ToUint8Array(encryptedBase64);
2017-11-05 06:18:55 +08:00
const decryptedBytes = aes.decrypt(encryptedBytes);
2017-11-05 06:18:55 +08:00
const digest = decryptedBytes.slice(0, 4);
const payload = decryptedBytes.slice(4);
2017-11-05 06:18:55 +08:00
const hashArray = sha256Array(payload);
2017-11-05 06:18:55 +08:00
const computedDigest = hashArray.slice(0, 4);
2017-11-05 06:18:55 +08:00
if (!arraysIdentical(digest, computedDigest)) {
return false;
}
2017-11-05 06:18:55 +08:00
return payload;
}
2017-11-05 06:18:55 +08:00
function concat(a, b) {
const result = [];
for (let key in a) {
result.push(a[key]);
}
for (let key in b) {
result.push(b[key]);
}
2017-11-05 06:18:55 +08:00
return result;
}
2017-11-05 06:18:55 +08:00
function sha256Array(content) {
const hash = sha256.create();
hash.update(content);
return hash.array();
}
2017-11-05 06:18:55 +08:00
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;
}
2017-11-05 06:18:55 +08:00
function encryptNote(note) {
note.detail.note_title = encryptString(note.detail.note_title);
note.detail.note_text = encryptString(note.detail.note_text);
2017-11-05 06:18:55 +08:00
note.detail.encryption = 1;
2017-11-05 06:18:55 +08:00
return note;
}
2017-11-05 06:18:55 +08:00
async function encryptNoteAndSendToServer() {
await ensureEncryptionIsAvailable(true, true);
2017-11-05 06:18:55 +08:00
const note = noteEditor.getCurrentNote();
2017-11-05 06:18:55 +08:00
noteEditor.updateNoteFromInputs(note);
2017-11-05 06:18:55 +08:00
encryptNote(note);
2017-11-05 06:18:55 +08:00
await noteEditor.saveNoteToServer(note);
2017-11-05 06:18:55 +08:00
await changeEncryptionOnNoteHistory(note.detail.note_id, true);
2017-11-05 06:18:55 +08:00
noteEditor.setNoteBackgroundIfEncrypted(note);
}
2017-11-05 06:18:55 +08:00
async function changeEncryptionOnNoteHistory(noteId, encrypt) {
const result = await $.ajax({
url: baseApiUrl + 'notes-history/' + noteId + "?encryption=" + (encrypt ? 0 : 1),
type: 'GET',
error: () => error("Error getting note history.")
});
2017-11-05 06:18:55 +08:00
for (const row of result) {
if (encrypt) {
row.note_title = encryptString(row.note_title);
row.note_text = encryptString(row.note_text);
}
else {
row.note_title = decryptString(row.note_title);
row.note_text = decryptString(row.note_text);
}
2017-11-05 06:18:55 +08:00
row.encryption = encrypt ? 1 : 0;
2017-11-05 06:18:55 +08:00
await $.ajax({
url: baseApiUrl + 'notes-history',
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify(row),
error: () => error("Error de/encrypting note history.")
});
2017-11-05 06:18:55 +08:00
console.log('Note history ' + row.note_history_id + ' de/encrypted');
}
2017-11-05 06:18:55 +08:00
}
2017-11-05 06:18:55 +08:00
async function decryptNoteAndSendToServer() {
await ensureEncryptionIsAvailable(true, true);
2017-11-05 06:18:55 +08:00
const note = noteEditor.getCurrentNote();
2017-11-05 06:18:55 +08:00
noteEditor.updateNoteFromInputs(note);
2017-11-05 06:18:55 +08:00
note.detail.encryption = 0;
2017-11-05 06:18:55 +08:00
await noteEditor.saveNoteToServer(note);
2017-11-05 06:18:55 +08:00
await changeEncryptionOnNoteHistory(note.detail.note_id, false);
2017-11-05 06:18:55 +08:00
noteEditor.setNoteBackgroundIfEncrypted(note);
}
2017-11-05 06:18:55 +08:00
function decryptNoteIfNecessary(note) {
if (note.detail.encryption > 0) {
decryptNote(note);
}
}
2017-11-05 06:18:55 +08:00
function decryptNote(note) {
note.detail.note_title = decryptString(note.detail.note_title);
note.detail.note_text = decryptString(note.detail.note_text);
}
2017-11-05 06:18:55 +08:00
async function encryptSubTree(noteId) {
await ensureEncryptionIsAvailable(true, true);
2017-11-05 06:18:55 +08:00
updateSubTreeRecursively(noteId, note => {
if (note.detail.encryption === null || note.detail.encryption === 0) {
encryptNote(note);
2017-11-05 06:18:55 +08:00
note.detail.encryption = 1;
2017-11-05 06:18:55 +08:00
return true;
}
else {
return false;
}
},
note => {
if (note.detail.note_id === noteEditor.getCurrentNoteId()) {
noteEditor.loadNoteToEditor(note.detail.note_id);
}
else {
noteEditor.setTreeBasedOnEncryption(note);
}
});
2017-11-05 06:18:55 +08:00
message("Encryption finished.");
}
2017-11-05 06:18:55 +08:00
async function decryptSubTree(noteId) {
await ensureEncryptionIsAvailable(true, true);
2017-11-05 06:18:55 +08:00
updateSubTreeRecursively(noteId, note => {
if (note.detail.encryption === 1) {
decryptNote(note);
2017-11-05 06:18:55 +08:00
note.detail.encryption = 0;
2017-11-05 06:18:55 +08:00
return true;
}
else {
return false;
}
},
note => {
if (note.detail.note_id === noteEditor.getCurrentNoteId()) {
noteEditor.loadNoteToEditor(note.detail.note_id);
}
else {
noteEditor.setTreeBasedOnEncryption(note);
}
});
2017-11-05 06:18:55 +08:00
message("Decryption finished.");
}
2017-11-05 06:18:55 +08:00
function updateSubTreeRecursively(noteId, updateCallback, successCallback) {
updateNoteSynchronously(noteId, updateCallback, successCallback);
2017-11-05 06:18:55 +08:00
const node = getNodeByKey(noteId);
if (!node || !node.getChildren()) {
return;
}
2017-11-05 06:18:55 +08:00
for (const child of node.getChildren()) {
updateSubTreeRecursively(child.key, updateCallback, successCallback);
}
}
2017-11-05 06:18:55 +08:00
function updateNoteSynchronously(noteId, updateCallback, successCallback) {
$.ajax({
url: baseApiUrl + 'notes/' + noteId,
type: 'GET',
async: false,
success: note => {
const needSave = updateCallback(note);
2017-11-05 06:18:55 +08:00
if (!needSave) {
return;
}
2017-11-05 06:18:55 +08:00
for (const link of note.links) {
delete link.type;
}
2017-11-05 06:18:55 +08:00
$.ajax({
url: baseApiUrl + 'notes/' + noteId,
type: 'PUT',
data: JSON.stringify(note),
contentType: "application/json",
async: false,
success: () => {
if (successCallback) {
successCallback(note);
}
},
error: () => {
console.log("Updating " + noteId + " failed.");
}
});
},
error: () => {
console.log("Reading " + noteId + " failed.");
}
2017-11-05 06:18:55 +08:00
});
}
2017-11-05 06:18:55 +08:00
return {
setEncryptionSalt,
setEncryptedDataKey,
setEncryptionSessionTimeout,
ensureEncryptionIsAvailable,
decryptTreeItems,
resetEncryptionSession,
isEncryptionAvailable,
encryptNoteIfNecessary,
encryptString,
decryptString,
encryptNoteAndSendToServer,
decryptNoteAndSendToServer,
decryptNoteIfNecessary,
encryptSubTree,
decryptSubTree
};
})();