Skip to content

Commit

Permalink
crypto: remove crypto-worker & simplify crypto interface
Browse files Browse the repository at this point in the history
  • Loading branch information
thecodrr committed Sep 4, 2023
1 parent 6554f90 commit fac788d
Show file tree
Hide file tree
Showing 18 changed files with 1,342 additions and 788 deletions.
1,426 changes: 1,177 additions & 249 deletions apps/web/package-lock.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"@notesnook/common": "file:../../packages/common",
"@notesnook/core": "file:../../packages/core",
"@notesnook/crypto": "file:../../packages/crypto",
"@notesnook/crypto-worker": "file:../../packages/crypto-worker",
"@notesnook/desktop": "file:../desktop",
"@notesnook/editor": "file:../../packages/editor",
"@notesnook/logger": "file:../../packages/logger",
Expand Down
18 changes: 7 additions & 11 deletions apps/web/src/interfaces/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { xxhash64, createXXHash64 } from "hash-wasm";
import axios, { AxiosProgressEvent } from "axios";
import { AppEventManager, AppEvents } from "../common/app-events";
import { StreamableFS } from "@notesnook/streamable-fs";
import { getNNCrypto } from "./nncrypto.stub";
import { NNCrypto } from "./nncrypto";
import hosts from "@notesnook/core/dist/utils/constants";
import { sendAttachmentsProgressEvent } from "@notesnook/core/dist/common";
import { saveAs } from "file-saver";
Expand All @@ -34,7 +34,7 @@ import { ProgressStream } from "../utils/streams/progress-stream";
import { consumeReadableStream } from "../utils/stream";
import { Base64DecoderStream } from "../utils/streams/base64-decoder-stream";
import { toBlob } from "@notesnook-importer/core/dist/src/utils/stream";
import { Cipher, OutputFormat, SerializedKey } from "@notesnook/crypto";
import { Cipher, DataFormat, SerializedKey } from "@notesnook/crypto";
import { IDataType } from "hash-wasm/dist/lib/util";
import { IndexedDBKVStore } from "./key-value";
import FileHandle from "@notesnook/streamable-fs/dist/src/filehandle";
Expand All @@ -53,8 +53,6 @@ async function writeEncryptedFile(
key: SerializedKey,
hash: string
) {
const crypto = await getNNCrypto();

if (!IndexedDBKVStore.isIndexedDBSupported())
throw new Error("This browser does not support IndexedDB.");

Expand All @@ -65,7 +63,7 @@ async function writeEncryptedFile(
const fileHandle = await streamablefs.createFile(hash, file.size, file.type);
sendAttachmentsProgressEvent("encrypt", hash, 1, 0);

const { iv, stream } = await crypto.createEncryptionStream(key);
const { iv, stream } = await NNCrypto.createEncryptionStream(key);
await file
.stream()
.pipeThrough(new ChunkedStream(CHUNK_SIZE))
Expand All @@ -84,7 +82,7 @@ async function writeEncryptedFile(
)
.pipeTo(fileHandle.writeable);

sendAttachmentsProgressEvent("encrypt", hash, 1);
sendAttachmentsProgressEvent("encrypt", hash, 1, 1);

return {
chunkSize: CHUNK_SIZE,
Expand Down Expand Up @@ -155,15 +153,14 @@ async function hashStream(reader: ReadableStreamDefaultReader<Uint8Array>) {
async function readEncrypted(
filename: string,
key: SerializedKey,
cipherData: Cipher & { outputType: OutputFormat }
cipherData: Cipher<DataFormat> & { outputType: DataFormat }
) {
const fileHandle = await streamablefs.readFile(filename);
if (!fileHandle) {
console.error(`File not found. (File hash: ${filename})`);
return null;
}
const crypto = await getNNCrypto();
const decryptionStream = await crypto.createDecryptionStream(
const decryptionStream = await NNCrypto.createDecryptionStream(
key,
cipherData.iv
);
Expand Down Expand Up @@ -527,8 +524,7 @@ export async function decryptFile(

const { key, iv } = fileMetadata;

const crypto = await getNNCrypto();
const decryptionStream = await crypto.createDecryptionStream(key, iv);
const decryptionStream = await NNCrypto.createDecryptionStream(key, iv);
return await toBlob(fileHandle.readable.pipeThrough(decryptionStream));
}

Expand Down
67 changes: 0 additions & 67 deletions apps/web/src/interfaces/nncrypto.stub.ts

This file was deleted.

24 changes: 24 additions & 0 deletions apps/web/src/interfaces/nncrypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { INNCrypto } from "@notesnook/crypto";
import CryptoWorker from "./crypto.worker?worker";
import { wrap } from "comlink";

export const NNCrypto = wrap<INNCrypto>(new CryptoWorker()) as INNCrypto;
40 changes: 40 additions & 0 deletions apps/web/src/interfaces/nncrypto.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { NNCrypto, Chunk, SerializedKey } from "@notesnook/crypto";
import { expose, transfer } from "comlink";

class NNCryptoWorker extends NNCrypto {
override async createDecryptionStream(
key: SerializedKey,
iv: string
): Promise<TransformStream<Uint8Array, Uint8Array>> {
const stream = await super.createDecryptionStream(key, iv);
return transfer(stream, [stream]);
}

override async createEncryptionStream(
key: SerializedKey
): Promise<{ iv: string; stream: TransformStream<Chunk, Uint8Array> }> {
const result = await super.createEncryptionStream(key);
return transfer(result, [result.stream]);
}
}

expose(new NNCryptoWorker());
63 changes: 20 additions & 43 deletions apps/web/src/interfaces/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
MemoryKVStore,
IKVStore
} from "./key-value";
import { getNNCrypto } from "./nncrypto.stub";
import { NNCrypto } from "./nncrypto";
import type { Cipher, SerializedKey } from "@notesnook/crypto/dist/src/types";

type EncryptedKey = { iv: Uint8Array; cipher: BufferSource };
Expand Down Expand Up @@ -82,8 +82,7 @@ export class NNStorage {
const { password, salt } = credentials;
if (!password) throw new Error("Invalid data provided to deriveCryptoKey.");

const crypto = await getNNCrypto();
const keyData = await crypto.exportKey(password, salt);
const keyData = await NNCrypto.exportKey(password, salt);

if (
(await IndexedDBKVStore.isIndexedDBSupported()) &&
Expand Down Expand Up @@ -124,41 +123,39 @@ export class NNStorage {
): Promise<SerializedKey> {
if (!password)
throw new Error("Invalid data provided to generateCryptoKey.");
const crypto = await getNNCrypto();
return await crypto.exportKey(password, salt);

return await NNCrypto.exportKey(password, salt);
}

async hash(password: string, email: string): Promise<string> {
const crypto = await getNNCrypto();
return await crypto.hash(password, `${APP_SALT}${email}`);
return await NNCrypto.hash(password, `${APP_SALT}${email}`);
}

encrypt(key: SerializedKey, plainText: string): Promise<Cipher<"base64">> {
return NNCrypto.encrypt(key, plainText, "text", "base64");
}

async encrypt(key: SerializedKey, plainText: string): Promise<Cipher> {
const crypto = await getNNCrypto();
return await crypto.encrypt(
key,
{ format: "text", data: plainText },
"base64"
);
encryptMulti(
key: SerializedKey,
items: string[]
): Promise<Cipher<"base64">[]> {
return NNCrypto.encryptMulti(key, items, "text", "base64");
}

async decrypt(
decrypt(
key: SerializedKey,
cipherData: Cipher
cipherData: Cipher<"base64">
): Promise<string | undefined> {
const crypto = await getNNCrypto();
cipherData.format = "base64";
return await crypto.decrypt(key, cipherData, "text");
return NNCrypto.decrypt(key, cipherData, "text");
}

async decryptMulti(
decryptMulti(
key: SerializedKey,
items: Cipher[]
items: Cipher<"base64">[]
): Promise<string[] | undefined> {
const crypto = await getNNCrypto();

items.forEach((c) => (c.format = "base64"));
return await crypto.decryptMulti(key, items, "text");
return NNCrypto.decryptMulti(key, items, "text");
}
}

Expand Down Expand Up @@ -226,23 +223,3 @@ async function aesDecrypt(
);
return dec.decode(plainText);
}

// async function main() {
// const nncrypto = await getNNCrypto();
// const electronNNCrypto = new NNCryptoElectron();

// console.time("nncrypto");
// for (let i = 0; i < 100; ++i) {
// await nncrypto.hash("mypassword", APP_SALT);
// }
// console.timeEnd("nncrypto");

// console.time("electron");
// for (let i = 0; i < 100; ++i) {
// await electronNNCrypto.hash("mypassword", APP_SALT);
// }
// console.timeEnd("electron");
// }

// main();
// setTimeout(main, 10000);
Empty file removed packages/crypto-worker/README.md
Empty file.
Loading

0 comments on commit fac788d

Please sign in to comment.