Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: add support for 3-layer attachment encryption

thecodrr657416478e57
diff --git a/apps/web/packages/nncrypto/index.ts b/apps/web/packages/nncrypto/index.ts
index a1e2bdf4f..e2275bc77 100644
--- a/apps/web/packages/nncrypto/index.ts
+++ b/apps/web/packages/nncrypto/index.ts
@@ -44,12 +44,12 @@ export class NNCrypto implements INNCrypto {
return Password.hash(password, salt);
}
- async deriveKey(password: string, salt: string): Promise<EncryptionKey> {
+ async deriveKey(password: string, salt?: string): Promise<EncryptionKey> {
await this.init();
return KeyUtils.deriveKey(password, salt);
}
- async exportKey(password: string, salt: string): Promise<string> {
+ async exportKey(password: string, salt?: string): Promise<SerializedKey> {
await this.init();
return KeyUtils.exportKey(password, salt);
}
diff --git a/apps/web/packages/nncrypto/src/decryption.ts b/apps/web/packages/nncrypto/src/decryption.ts
index cebc06bab..0c9ba3bfb 100644
--- a/apps/web/packages/nncrypto/src/decryption.ts
+++ b/apps/web/packages/nncrypto/src/decryption.ts
@@ -7,6 +7,7 @@ import {
base64_variants,
StateAddress,
to_string,
+ from_hex,
} from "libsodium-wrappers";
import KeyUtils from "./keyutils";
import {
@@ -18,15 +19,8 @@ import {
} from "./types";
export default class Decryption {
- static decrypt(
- key: SerializedKey,
- cipherData: Cipher,
- outputFormat: OutputFormat = "text"
- ): Plaintext {
- if (!key.salt && cipherData.salt) key.salt = cipherData.salt;
-
- const encryptionKey = KeyUtils.transform(key);
- let input: Uint8Array = cipherData.cipher as Uint8Array;
+ private static transformInput(cipherData: Cipher): Uint8Array {
+ let input: Uint8Array | null = null;
if (
typeof cipherData.cipher === "string" &&
cipherData.format === "base64"
@@ -35,8 +29,27 @@ export default class Decryption {
cipherData.cipher,
base64_variants.URLSAFE_NO_PADDING
);
+ } else if (
+ typeof cipherData.cipher === "string" &&
+ cipherData.format === "hex"
+ ) {
+ input = from_hex(cipherData.cipher);
+ } else if (cipherData.cipher instanceof Uint8Array) {
+ input = cipherData.cipher;
}
+ if (!input) throw new Error("Data cannot be null.");
+ return input;
+ }
+
+ static decrypt(
+ key: SerializedKey,
+ cipherData: Cipher,
+ outputFormat: OutputFormat = "text"
+ ): Plaintext {
+ if (!key.salt && cipherData.salt) key.salt = cipherData.salt;
+ const encryptionKey = KeyUtils.transform(key);
+ const input = this.transformInput(cipherData);
const plaintext = crypto_aead_xchacha20poly1305_ietf_decrypt(
null,
input,
diff --git a/apps/web/packages/nncrypto/src/encryption.ts b/apps/web/packages/nncrypto/src/encryption.ts
index 38c77674e..04a218ec1 100644
--- a/apps/web/packages/nncrypto/src/encryption.ts
+++ b/apps/web/packages/nncrypto/src/encryption.ts
@@ -21,24 +21,28 @@ import {
SerializedKey,
} from "./types";
+const encoder = new TextEncoder();
export default class Encryption {
- static encrypt(
- key: SerializedKey,
- plaintext: Plaintext,
- outputFormat: OutputFormat = "uint8array"
- ): Cipher {
- const encryptionKey = KeyUtils.transform(key);
-
+ private static transformInput(plaintext: Plaintext): Uint8Array {
let data: Uint8Array | null = null;
if (typeof plaintext.data === "string" && plaintext.format === "base64") {
data = from_base64(plaintext.data, base64_variants.ORIGINAL);
} else if (typeof plaintext.data === "string") {
- data = from_string(plaintext.data);
+ data = encoder.encode(plaintext.data);
} else if (plaintext.data instanceof Uint8Array) {
data = plaintext.data;
}
-
if (!data) throw new Error("Data cannot be null.");
+ return data;
+ }
+
+ static encrypt(
+ key: SerializedKey,
+ plaintext: Plaintext,
+ outputFormat: OutputFormat = "uint8array"
+ ): Cipher {
+ const encryptionKey = KeyUtils.transform(key);
+ const data = this.transformInput(plaintext);
const nonce = randombytes_buf(crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
diff --git a/apps/web/packages/nncrypto/src/interfaces.ts b/apps/web/packages/nncrypto/src/interfaces.ts
index 8b76487f5..44bbddaf6 100644
--- a/apps/web/packages/nncrypto/src/interfaces.ts
+++ b/apps/web/packages/nncrypto/src/interfaces.ts
@@ -27,9 +27,9 @@ export interface INNCrypto {
hash(password: string, salt: string): Promise<string>;
- deriveKey(password: string, salt: string): Promise<EncryptionKey>;
+ deriveKey(password: string, salt?: string): Promise<EncryptionKey>;
- exportKey(password: string, salt: string): Promise<string>;
+ exportKey(password: string, salt?: string): Promise<SerializedKey>;
encryptStream(
key: SerializedKey,
diff --git a/apps/web/packages/nncrypto/src/keyutils.ts b/apps/web/packages/nncrypto/src/keyutils.ts
index 60756b9c5..ba24cf319 100644
--- a/apps/web/packages/nncrypto/src/keyutils.ts
+++ b/apps/web/packages/nncrypto/src/keyutils.ts
@@ -35,9 +35,9 @@ export default class KeyUtils {
};
}
- static exportKey(password: string, salt: string): string {
- const { key } = this.deriveKey(password, salt);
- return to_base64(key);
+ static exportKey(password: string, salt?: string): SerializedKey {
+ const { key, salt: keySalt } = this.deriveKey(password, salt);
+ return { key: to_base64(key), salt: keySalt };
}
/**
diff --git a/apps/web/packages/nncryptoworker/index.ts b/apps/web/packages/nncryptoworker/index.ts
index ddf29ea7c..9d67bdc30 100644
--- a/apps/web/packages/nncryptoworker/index.ts
+++ b/apps/web/packages/nncryptoworker/index.ts
@@ -59,14 +59,14 @@ export class NNCryptoWorker implements INNCrypto {
return this.workermodule.hash(password, salt);
}
- async deriveKey(password: string, salt: string): Promise<EncryptionKey> {
+ async deriveKey(password: string, salt?: string): Promise<EncryptionKey> {
await this.init();
if (!this.workermodule) throw new Error("Worker module is not ready.");
return this.workermodule.deriveKey(password, salt);
}
- async exportKey(password: string, salt: string): Promise<string> {
+ async exportKey(password: string, salt?: string): Promise<SerializedKey> {
await this.init();
if (!this.workermodule) throw new Error("Worker module is not ready.");
diff --git a/apps/web/packages/nncryptoworker/src/worker.ts b/apps/web/packages/nncryptoworker/src/worker.ts
index 0e2a9e6d8..2100986d6 100644
--- a/apps/web/packages/nncryptoworker/src/worker.ts
+++ b/apps/web/packages/nncryptoworker/src/worker.ts
@@ -16,11 +16,11 @@ async function loadNNCrypto(): Promise<NNCrypto> {
}
const module = {
- exportKey: async function (password: string, salt: string) {
+ exportKey: async function (password: string, salt?: string) {
const crypto = await loadNNCrypto();
return crypto.exportKey(password, salt);
},
- deriveKey: async function (password: string, salt: string) {
+ deriveKey: async function (password: string, salt?: string) {
const crypto = await loadNNCrypto();
return crypto.deriveKey(password, salt);
},
diff --git a/apps/web/src/components/editor/plugins/picker.js b/apps/web/src/components/editor/plugins/picker.js
index 54c65062f..6de69820a 100644
--- a/apps/web/src/components/editor/plugins/picker.js
+++ b/apps/web/src/components/editor/plugins/picker.js
@@ -4,6 +4,7 @@ import { db } from "../../../common/db";
import { showProgressDialog } from "../../../common/dialog-controller";
import fs from "../../../interfaces/fs";
import { formatBytes } from "../../../utils/filename";
+import { showToast } from "../../../utils/toast";
function register(editor) {
editor.ui.registry.addButton("attachment", {
@@ -36,99 +37,115 @@ async function insertFile(editor) {
})();
async function pickFile() {
- const key = await getEncryptionKey();
-
- const selectedFile = await showFilePicker({ acceptedFileTypes: "*/*" });
- if (!selectedFile) return;
-
- const result = await showProgressDialog({
- title: `Encrypting attachment`,
- subtitle: "Please wait while we encrypt this attachment for upload.",
- message: selectedFile.name,
- total: formatBytes(selectedFile.size, 0),
- setProgress: (set) => {
- const event = AppEventManager.subscribe(
- AppEvents.UPDATE_ATTACHMENT_PROGRESS,
- ({ type, total, loaded }) => {
- if (type !== "encrypt") return;
-
- const percent = Math.round((loaded / total) * 100);
- set({ loaded: formatBytes(loaded, 0), progress: percent });
+ try {
+ const selectedFile = await showFilePicker({ acceptedFileTypes: "*/*" });
+ if (!selectedFile) return;
+
+ const result = await showProgressDialog({
+ title: `Encrypting attachment`,
+ subtitle: "Please wait while we encrypt this attachment for upload.",
+ message: selectedFile.name,
+ total: formatBytes(selectedFile.size, 0),
+ setProgress: (set) => {
+ const event = AppEventManager.subscribe(
+ AppEvents.UPDATE_ATTACHMENT_PROGRESS,
+ ({ type, total, loaded }) => {
+ if (type !== "encrypt") return;
+
+ const percent = Math.round((loaded / total) * 100);
+ set({ loaded: formatBytes(loaded, 0), progress: percent });
+ }
+ );
+ return () => {
+ event.unsubscribe();
+ };
+ },
+ action: async () => {
+ const key = await getEncryptionKey();
+
+ const reader = selectedFile.stream().getReader();
+ const { hash, type: hashType } = await fs.hashStream(reader);
+ reader.releaseLock();
+
+ let output = {};
+ if (!db.attachments.exists(hash)) {
+ output = await fs.writeEncryptedFile(selectedFile, key, hash);
}
- );
- return () => {
- event.unsubscribe();
- };
- },
- action: async () => {
- const reader = selectedFile.stream().getReader();
- const { hash, type: hashType } = await fs.hashStream(reader);
- reader.releaseLock();
-
- let output = {};
- if (!db.attachments.exists(hash)) {
- output = await fs.writeEncryptedFile(selectedFile, key, hash);
- }
-
- await db.attachments.add({
- ...output,
- hash,
- hashType,
- salt: "helloworld",
- filename: selectedFile.name,
- type: selectedFile.type,
- });
-
- return {
- hash: hash,
- filename: selectedFile.name,
- type: selectedFile.type,
- size: selectedFile.size,
- };
- },
- });
- if (!result.hash) throw new Error("Could not add attachment.");
- return result;
+ await db.attachments.add({
+ ...output,
+ hash,
+ hashType,
+ filename: selectedFile.name,
+ type: selectedFile.type,
+ key,
+ });
+
+ return {
+ hash: hash,
+ filename: selectedFile.name,
+ type: selectedFile.type,
+ size: selectedFile.size,
+ };
+ },
+ });
+ if (!result.hash) throw new Error("Could not add attachment.");
+ return result;
+ } catch (e) {
+ showToast(
+ "error",
+ `${e.message} You need internet access to attach a file.`
+ );
+ }
}
async function pickImage() {
- const key = await getEncryptionKey();
+ try {
+ const selectedImage = await showFilePicker({
+ acceptedFileTypes: "image/*",
+ });
+ if (!selectedImage) return;
- const selectedImage = await showFilePicker({ acceptedFileTypes: "image/*" });
- if (!selectedImage) return;
+ const key = await getEncryptionKey();
- const { dataurl, blob } = await compressImage(selectedImage, "buffer");
+ const { dataurl, blob } = await compressImage(selectedImage, "buffer");
- const reader = blob.stream().getReader();
- const { hash, type: hashType } = await fs.hashStream(reader);
- reader.releaseLock();
+ const reader = blob.stream().getReader();
+ const { hash, type: hashType } = await fs.hashStream(reader);
+ reader.releaseLock();
- var output = {};
- if (!db.attachments.exists(hash)) {
- output = await fs.writeEncryptedFile(blob, key, hash);
- }
+ var output = {};
+ if (!db.attachments.exists(hash)) {
+ output = await fs.writeEncryptedFile(blob, key, hash);
+ }
- await db.attachments.add({
- ...output,
- hash,
- hashType,
- filename: selectedImage.name,
- type: selectedImage.type,
- });
+ await db.attachments.add({
+ ...output,
+ key,
+ hash,
+ hashType,
+ filename: selectedImage.name,
+ type: selectedImage.type,
+ });
- return {
- hash,
- filename: selectedImage.name,
- type: selectedImage.type,
- size: selectedImage.size,
- dataurl,
- };
+ return {
+ hash,
+ filename: selectedImage.name,
+ type: selectedImage.type,
+ size: selectedImage.size,
+ dataurl,
+ };
+ } catch (e) {
+ showToast(
+ "error",
+ `${e.message} You need internet access to attach an image.`
+ );
+ }
}
async function getEncryptionKey() {
- const key = await db.user.getEncryptionKey();
- if (!key) throw new Error("No encryption key found. Are you logged in?");
+ const key = await db.attachments.generateKey();
+ if (!key) throw new Error("Could not generate a new encryption key.");
return key; // { password: "helloworld" };
}
diff --git a/apps/web/src/components/editor/tinymce.js b/apps/web/src/components/editor/tinymce.js
index 4dbe327bb..2b0e9ef6b 100644
--- a/apps/web/src/components/editor/tinymce.js
+++ b/apps/web/src/components/editor/tinymce.js
@@ -245,8 +245,9 @@ function TinyMCE(props) {
const attachment = db.attachments.attachment(hash);
if (!attachment) return;
await db.fs.downloadFile(hash, hash);
+ const key = await db.attachments.decryptKey(attachment.key);
await FS.saveFile(hash, {
- key: await db.user.getEncryptionKey(),
+ key,
iv: attachment.iv,
name: attachment.metadata.filename,
type: attachment.metadata.type,
diff --git a/apps/web/src/components/properties/index.js b/apps/web/src/components/properties/index.js
index 52f009d49..f6ee483b8 100644
--- a/apps/web/src/components/properties/index.js
+++ b/apps/web/src/components/properties/index.js
@@ -307,8 +307,11 @@ function Properties({ noteId }) {
attachment.metadata.hash
)
) {
+ const key = await db.attachments.decryptKey(
+ attachment.key
+ );
await FS.saveFile(attachment.metadata.hash, {
- key: await db.user.getEncryptionKey(),
+ key,
iv: attachment.iv,
name: attachment.metadata.filename,
type: attachment.metadata.type,
diff --git a/apps/web/src/interfaces/fs.js b/apps/web/src/interfaces/fs.js
index ad1f4990d..5e090cf44 100644
--- a/apps/web/src/interfaces/fs.js
+++ b/apps/web/src/interfaces/fs.js
@@ -323,11 +323,26 @@ async function saveFile(filename, { key, iv, name, type }) {
await streamablefs.deleteFile(filename);
}
+async function deleteFile(filename, requestOptions) {
+ if (!requestOptions) return await streamablefs.deleteFile(filename);
+
+ const { url, headers } = requestOptions;
+ if (!(await streamablefs.exists(filename))) return true;
+
+ const response = await axios.delete(url, {
+ headers: headers,
+ });
+ const result = isSuccessStatusCode(response.status);
+ if (result) await streamablefs.deleteFile(filename);
+ return result;
+}
+
const FS = {
writeEncrypted,
readEncrypted,
uploadFile: cancellable(uploadFile),
downloadFile: cancellable(downloadFile),
+ deleteFile,
saveFile,
exists,
hashBuffer,
diff --git a/apps/web/src/interfaces/storage.js b/apps/web/src/interfaces/storage.js
index f8d7ae4d5..3c6c71365 100644
--- a/apps/web/src/interfaces/storage.js
+++ b/apps/web/src/interfaces/storage.js
@@ -45,10 +45,10 @@ async function deriveCryptoKey(name, data) {
if (isIndexedDBSupported() && window?.crypto?.subtle) {
const pbkdfKey = await derivePBKDF2Key(password);
await write(name, pbkdfKey);
- const cipheredKey = await aesEncrypt(pbkdfKey, keyData);
+ const cipheredKey = await aesEncrypt(pbkdfKey, keyData.key);
await write(`${name}@_k`, cipheredKey);
} else {
- await write(`${name}@_k`, keyData);
+ await write(`${name}@_k`, keyData.key);
}
}
@@ -68,6 +68,12 @@ function isIndexedDBSupported() {
return localforage.driver() === "asyncStorage";
}
+async function generateCryptoKey(password, salt = false) {
+ if (!password) throw new Error("Invalid data provided to generateCryptoKey.");
+ const crypto = await getNNCrypto();
+ return await crypto.exportKey(password, salt);
+}
+
const APP_SALT = "oVzKtazBo7d8sb7TBvY9jw";
const Storage = {
read,
@@ -76,6 +82,7 @@ const Storage = {
remove,
clear,
getAllKeys,
+ generateCryptoKey,
deriveCryptoKey,
getCryptoKey,
hash: async function (password, email) {