trilium/public/javascripts/encryption.js

452 lines
13 KiB
JavaScript
Raw Normal View History

"use strict";
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;
2017-11-09 11:33:08 +08:00
let passwordDerivedKeySalt = null;
2017-11-05 06:18:55 +08:00
let encryptedDataKey = null;
let encryptionSessionTimeout = null;
2017-11-11 11:55:19 +08:00
let protectedSessionId = null;
2017-11-05 06:18:55 +08:00
$.ajax({
url: baseApiUrl + 'settings/all',
type: 'GET',
2017-11-09 11:33:08 +08:00
error: () => showError("Error getting encryption settings.")
}).then(settings => {
2017-11-09 11:33:08 +08:00
passwordDerivedKeySalt = settings.password_derived_key_salt;
encryptionSessionTimeout = settings.encryption_session_timeout;
encryptedDataKey = settings.encrypted_data_key;
});
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) {
2017-11-09 11:33:08 +08:00
// if this is entry point then we need to show the app even before the note is loaded
showAppIfHidden();
2017-11-05 06:18:55 +08:00
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)
2017-11-05 10:18:36 +08:00
treeUtils.getNodeByKey(noteEditor.getCurrentNoteId()).setFocus();
2017-11-05 06:18:55 +08:00
}
}
});
}
else {
dfd.resolve();
}
2017-11-05 06:18:55 +08:00
return dfd.promise();
}
2017-11-09 11:33:08 +08:00
async function getDataKey(password) {
const passwordDerivedKey = await computeScrypt(password, passwordDerivedKeySalt);
2017-11-09 11:33:08 +08:00
const dataKeyAes = getDataKeyAes(passwordDerivedKey);
2017-11-09 11:33:08 +08:00
return decrypt(dataKeyAes, encryptedDataKey);
2017-11-05 06:18:55 +08:00
}
2017-11-09 11:33:08 +08:00
function computeScrypt(password, salt) {
2017-11-05 06:18:55 +08:00
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
return new Promise((resolve, reject) => {
scrypt(passwordBuffer, saltBuffer, N, r, p, dkLen, (error, progress, key) => {
if (error) {
2017-11-09 11:33:08 +08:00
showError(error);
2017-11-09 11:33:08 +08:00
reject(error);
2017-11-05 06:18:55 +08:00
}
else if (key) {
2017-11-09 11:33:08 +08:00
resolve(key);
2017-11-05 06:18:55 +08:00
}
});
});
}
2017-11-05 06:18:55 +08:00
function decryptTreeItems() {
if (!isEncryptionAvailable()) {
return;
}
for (const noteId of glob.allNoteIds) {
2017-11-05 10:18:36 +08:00
const note = treeUtils.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-09 11:33:08 +08:00
async function setupEncryptionSession() {
2017-11-05 06:18:55 +08:00
const password = encryptionPasswordEl.val();
encryptionPasswordEl.val("");
2017-11-11 11:55:19 +08:00
const response = await enterProtectedSession(password);
if (!response.success) {
showError("Wrong password.");
2017-11-09 11:33:08 +08:00
return;
}
2017-09-17 12:18:03 +08:00
2017-11-11 11:55:19 +08:00
protectedSessionId = response.protectedSessionId;
initAjax();
2017-11-11 11:55:19 +08:00
dialogEl.dialog("close");
2017-11-11 11:55:19 +08:00
noteTree.reload();
2017-11-09 11:33:08 +08:00
if (encryptionDeferred !== null) {
encryptionDeferred.resolve();
2017-11-09 11:33:08 +08:00
encryptionDeferred = null;
}
}
2017-11-11 11:55:19 +08:00
async function enterProtectedSession(password) {
return await $.ajax({
url: baseApiUrl + 'login/protected',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
password: password
}),
error: () => showError("Error entering protected session.")
});
}
function getProtectedSessionId() {
return protectedSessionId;
}
2017-11-05 06:18:55 +08:00
function resetEncryptionSession() {
2017-11-11 11:55:19 +08:00
protectedSessionId = null;
initAjax();
// most secure solution - guarantees nothing remained in memory
// since this expires because user doesn't use the app, it shouldn't be disruptive
window.location.reload(true);
}
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-09 11:33:08 +08:00
function getDataKeyAes(passwordDerivedKey) {
return new aesjs.ModeOfOperation.ctr(passwordDerivedKey, new aesjs.Counter(5));
2017-11-05 06:18:55 +08:00
}
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 = Array.from(aesjs.utils.utf8.toBytes(str));
2017-11-05 06:18:55 +08:00
const digest = sha256Array(payload).slice(0, 4);
const digestWithPayload = digest.concat(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 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',
2017-11-09 11:33:08 +08:00
error: () => showError("Error getting note history.")
2017-11-05 06:18:55 +08:00
});
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),
2017-11-09 11:33:08 +08:00
error: () => showError("Error de/encrypting note history.")
2017-11-05 06:18:55 +08:00
});
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-09 11:33:08 +08:00
showMessage("Encryption finished.");
2017-11-05 06:18:55 +08:00
}
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-09 11:33:08 +08:00
showMessage("Decryption finished.");
2017-11-05 06:18:55 +08:00
}
2017-11-05 06:18:55 +08:00
function updateSubTreeRecursively(noteId, updateCallback, successCallback) {
updateNoteSynchronously(noteId, updateCallback, successCallback);
2017-11-05 10:18:36 +08:00
const node = treeUtils.getNodeByKey(noteId);
2017-11-05 06:18:55 +08:00
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);
}
},
2017-11-09 11:33:08 +08:00
error: () => showError("Updating " + noteId + " failed.")
2017-11-05 06:18:55 +08:00
});
},
2017-11-09 11:33:08 +08:00
error: () => showError("Reading " + noteId + " failed.")
2017-11-05 06:18:55 +08:00
});
}
2017-11-09 11:33:08 +08:00
encryptionPasswordFormEl.submit(() => {
setupEncryptionSession();
return false;
});
setInterval(() => {
if (lastEncryptionOperationDate !== null && new Date().getTime() - lastEncryptionOperationDate.getTime() > encryptionSessionTimeout * 1000) {
resetEncryptionSession();
}
}, 5000);
2017-11-05 06:18:55 +08:00
return {
setEncryptedDataKey,
setEncryptionSessionTimeout,
ensureEncryptionIsAvailable,
decryptTreeItems,
resetEncryptionSession,
isEncryptionAvailable,
encryptNoteIfNecessary,
encryptString,
decryptString,
encryptNoteAndSendToServer,
decryptNoteAndSendToServer,
decryptNoteIfNecessary,
encryptSubTree,
2017-11-11 11:55:19 +08:00
decryptSubTree,
getProtectedSessionId
2017-11-05 06:18:55 +08:00
};
})();