A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: migrate to new streamable-fs
thecodrre035947c1b15
diff --git a/apps/web/public/downloader.html b/apps/web/public/downloader.htmlnew file mode 100644index 000000000..b10ec3e2b--- /dev/null+++ b/apps/web/public/downloader.html@@ -0,0 +1,189 @@+<!--+ mitm.html is the lite "man in the middle"+ This is only meant to signal the opener's messageChannel to+ the service worker - when that is done this mitm can be closed+ but it's better to keep it alive since this also stops the sw+ from restarting+ The service worker is capable of intercepting all request and fork their+ own "fake" response - wish we are going to craft+ when the worker then receives a stream then the worker will tell the opener+ to open up a link that will start the download+-->+<script>+ // This will prevent the sw from restarting+ let keepAlive = () => {+ keepAlive = () => {};+ var ping =+ location.href.substr(0, location.href.lastIndexOf("/")) + "/ping";+ var interval = setInterval(() => {+ if (sw) {+ sw.postMessage("ping");+ } else {+ console.log("SENDING FETCH");+ fetch(ping).then((res) => res.text(!res.ok && clearInterval(interval)));+ }+ }, 10000);+ };++ // message event is the first thing we need to setup a listner for+ // don't want the opener to do a random timeout - instead they can listen for+ // the ready event+ // but since we need to wait for the Service Worker registration, we store the+ // message for later+ let messages = [];+ window.onmessage = (evt) => messages.push(evt);++ let sw = null;+ let scope = "";++ function registerWorker() {+ return navigator.serviceWorker+ .getRegistration("./")+ .then((swReg) => {+ return (+ swReg ||+ navigator.serviceWorker.register("downloader.sw.js", { scope: "./" })+ );+ })+ .then((swReg) => {+ const swRegTmp = swReg.installing || swReg.waiting;++ scope = swReg.scope;++ return (+ (sw = swReg.active) ||+ new Promise((resolve) => {+ swRegTmp.addEventListener(+ "statechange",+ (fn = () => {+ if (swRegTmp.state === "activated") {+ swRegTmp.removeEventListener("statechange", fn);+ sw = swReg.active;+ resolve();+ }+ })+ );+ })+ );+ });+ }++ // Now that we have the Service Worker registered we can process messages+ function onMessage(event) {+ let { data, ports, origin } = event;++ // It's important to have a messageChannel, don't want to interfere+ // with other simultaneous downloads+ if (!ports || !ports.length) {+ throw new TypeError("[StreamSaver] You didn't send a messageChannel");+ }++ if (typeof data !== "object") {+ throw new TypeError("[StreamSaver] You didn't send a object");+ }++ // the default public service worker for StreamSaver is shared among others.+ // so all download links needs to be prefixed to avoid any other conflict+ data.origin = origin;++ // if we ever (in some feature versoin of streamsaver) would like to+ // redirect back to the page of who initiated a http request+ data.referrer = data.referrer || document.referrer || origin;++ // pass along version for possible backwards compatibility in sw.js+ data.streamSaverVersion = new URLSearchParams(location.search).get(+ "version"+ );++ if (data.streamSaverVersion === "1.2.0") {+ console.warn("[StreamSaver] please update streamsaver");+ }++ /** @since v2.0.0 */+ if (!data.headers) {+ console.warn(+ "[StreamSaver] pass `data.headers` that you would like to pass along to the service worker\nit should be a 2D array or a key/val object that fetch's Headers api accepts"+ );+ } else {+ // test if it's correct+ // should thorw a typeError if not+ new Headers(data.headers);+ }++ /** @since v2.0.0 */+ if (typeof data.filename === "string") {+ console.warn(+ "[StreamSaver] You shouldn't send `data.filename` anymore. It should be included in the Content-Disposition header option"+ );+ // Do what File constructor do with fileNames+ data.filename = data.filename.replace(/\//g, ":");+ }++ /** @since v2.0.0 */+ if (data.size) {+ console.warn(+ "[StreamSaver] You shouldn't send `data.size` anymore. It should be included in the content-length header option"+ );+ }++ /** @since v2.0.0 */+ if (data.readableStream) {+ console.warn(+ "[StreamSaver] You should send the readableStream in the messageChannel, not throught mitm"+ );+ }++ /** @since v2.0.0 */+ if (!data.pathname) {+ console.warn(+ "[StreamSaver] Please send `data.pathname` (eg: /pictures/summer.jpg)"+ );+ data.pathname = Math.random().toString().slice(-6) + "/" + data.filename;+ }++ // remove all leading slashes+ data.pathname = data.pathname.replace(/^\/+/g, "");++ // remove protocol+ let org = origin.replace(/(^\w+:|^)\/\//, "");++ // set the absolute pathname to the download url.+ data.url = new URL(`${scope + org}/${data.pathname}`).toString();++ if (!data.url.startsWith(`${scope + org}/`)) {+ throw new TypeError("[StreamSaver] bad `data.pathname`");+ }++ // This sends the message data as well as transferring+ // messageChannel.port2 to the service worker. The service worker can+ // then use the transferred port to reply via postMessage(), which+ // will in turn trigger the onmessage handler on messageChannel.port1.++ const transferable = data.readableStream+ ? [ports[0], data.readableStream]+ : [ports[0]];++ if (!(data.readableStream || data.transferringReadable)) {+ keepAlive();+ }++ return sw.postMessage(data, transferable);+ }++ if (window.opener) {+ // The opener can't listen to onload event, so we need to help em out!+ // (telling them that we are ready to accept postMessage's)+ window.opener.postMessage("StreamSaver::loadedPopup", "*");+ }++ if (navigator.serviceWorker) {+ registerWorker().then(() => {+ window.onmessage = onMessage;+ messages.forEach(window.onmessage);+ });+ } else {+ // FF can ping sw with fetch from a secure hidden iframe+ // shouldn't really be possible?+ keepAlive();+ }+</script>diff --git a/apps/web/public/downloader.sw.js b/apps/web/public/downloader.sw.jsnew file mode 100644index 000000000..549ff3083--- /dev/null+++ b/apps/web/public/downloader.sw.js@@ -0,0 +1,144 @@+/* eslint-disable no-restricted-globals */++self.addEventListener("install", () => {+ self.skipWaiting();+});++self.addEventListener("activate", (event) => {+ event.waitUntil(self.clients.claim());+});++const map = new Map();++// This should be called once per download+// Each event has a dataChannel that the data will be piped through+self.onmessage = (event) => {+ console.log("EVENT", event);+ // We send a heartbeat every x second to keep the+ // service worker alive if a transferable stream is not sent+ if (event.data === "ping") {+ return;+ }++ const data = event.data;+ const downloadUrl =+ data.url ||+ self.registration.scope ++ Math.random() ++ "/" ++ (typeof data === "string" ? data : data.filename);+ const port = event.ports[0];+ const metadata = new Array(3); // [stream, data, port]++ metadata[1] = data;+ metadata[2] = port;++ // Note to self:+ // old streamsaver v1.2.0 might still use `readableStream`...+ // but v2.0.0 will always transfer the stream through MessageChannel #94+ if (event.data.readableStream) {+ metadata[0] = event.data.readableStream;+ } else if (event.data.transferringReadable) {+ port.onmessage = (evt) => {+ port.onmessage = null;+ metadata[0] = evt.data.readableStream;+ };+ } else {+ metadata[0] = createStream(port);+ }++ map.set(downloadUrl, metadata);+ port.postMessage({ download: downloadUrl });+};++function createStream(port) {+ // ReadableStream is only supported by chrome 52+ return new ReadableStream({+ start(controller) {+ // When we receive data on the messageChannel, we write+ port.onmessage = ({ data }) => {+ if (data === "end") {+ return controller.close();+ }++ if (data === "abort") {+ console.log("user aborted");+ controller.error("Aborted the download");+ return;+ }++ controller.enqueue(data);+ };+ },+ cancel() {+ console.log("user aborted");+ },+ });+}++self.onfetch = (event) => {+ const url = event.request.url;++ // this only works for Firefox+ if (url.endsWith("/ping")) {+ return event.respondWith(new Response("pong"));+ }++ const hijacke = map.get(url);++ if (!hijacke) return null;++ const [stream, data, port] = hijacke;+ console.log("Eevnent", stream);++ map.delete(url);++ // Not comfortable letting any user control all headers+ // so we only copy over the length & disposition+ const responseHeaders = new Headers({+ "Content-Type": "application/octet-stream; charset=utf-8",++ // To be on the safe side, The link can be opened in a iframe.+ // but octet-stream should stop it.+ "Content-Security-Policy": "default-src 'none'",+ "X-Content-Security-Policy": "default-src 'none'",+ "X-WebKit-CSP": "default-src 'none'",+ "X-XSS-Protection": "1; mode=block",+ });++ let headers = new Headers(data.headers || {});++ if (headers.has("Content-Length")) {+ responseHeaders.set("Content-Length", headers.get("Content-Length"));+ }++ if (headers.has("Content-Disposition")) {+ responseHeaders.set(+ "Content-Disposition",+ headers.get("Content-Disposition")+ );+ }++ // data, data.filename and size should not be used anymore+ if (data.size) {+ console.warn("Depricated");+ responseHeaders.set("Content-Length", data.size);+ }++ let fileName = typeof data === "string" ? data : data.filename;+ if (fileName) {+ console.warn("Depricated");+ // Make filename RFC5987 compatible+ fileName = encodeURIComponent(fileName)+ .replace(/['()]/g, escape)+ .replace(/\*/g, "%2A");+ responseHeaders.set(+ "Content-Disposition",+ "attachment; filename*=UTF-8''" + fileName+ );+ }++ event.respondWith(new Response(stream, { headers: responseHeaders }));++ port.postMessage({ debug: "Download started" });+};diff --git a/apps/web/src/components/editor/plugins/picker.js b/apps/web/src/components/editor/plugins/picker.jsindex bc3594175..893198a67 100644--- a/apps/web/src/components/editor/plugins/picker.js+++ b/apps/web/src/components/editor/plugins/picker.js@@ -38,23 +38,26 @@ async function pickFile() {const selectedFile = await showFilePicker({ acceptedFileTypes: "*/*" });if (!selectedFile) return;- const generator = fs.writeEncryptedFile(selectedFile, key);+ const reader = selectedFile.stream().getReader();+ const { hash, type: hashType } = await fs.hashStream(reader);+ reader.releaseLock();- let { value: output } = await generator.next();- if (!db.attachments.exists(output.hash)) {- const { value } = await generator.next();- output = value;+ let output = {};+ if (!db.attachments.exists(hash)) {+ output = await fs.writeEncryptedFile(selectedFile, key, hash);}- console.log(output);+await db.attachments.add({...output,- salt: "sda",+ hash,+ hashType,+ salt: key.salt,filename: selectedFile.name,type: selectedFile.type,});return {- hash: output.hash,+ hash: hash,filename: selectedFile.name,type: selectedFile.type,size: selectedFile.size,@@ -67,17 +70,16 @@ async function pickImage() {const selectedImage = await showFilePicker({ acceptedFileTypes: "image/*" });if (!selectedImage) return;- const { dataurl, buffer } = await compressImage(selectedImage, "buffer");- const { hash, type: hashType } = await fs.hashBuffer(Buffer.from(buffer));+ const { dataurl, blob } = await compressImage(selectedImage, "buffer");- const output = db.attachments.exists(hash)- ? {}- : await fs.writeEncrypted(null, {- data: new Uint8Array(buffer),- type: "buffer",- key,- hash,- });+ 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);+ }await db.attachments.add({...output,@@ -97,7 +99,7 @@ async function pickImage() {}async function getEncryptionKey() {- return { password: "helloworld" };+ // return { password: "helloworld" };const key = await db.user.getEncryptionKey();if (!key) throw new Error("No encryption key found. Are you logged in?");return key; // { password: "helloworld" };@@ -125,7 +127,7 @@ function showFilePicker({ acceptedFileTypes }) {** @param {File} file* @param {"base64"|"buffer"} type- * @returns {{ dataurl: string, buffer: ArrayBuffer }}+ * @returns {Promise<Blob>}*/function compressImage(file, type) {return new Promise((resolve, reject) => {@@ -141,7 +143,10 @@ function compressImage(file, type) {async success(result) {const buffer = await result.arrayBuffer();const base64 = Buffer.from(buffer).toString("base64");- resolve({ dataurl: `data:${file.type};base64,${base64}`, buffer });+ resolve({+ dataurl: `data:${file.type};base64,${base64}`,+ blob: result,+ });},error(err) {reject(err);diff --git a/apps/web/src/components/properties/index.js b/apps/web/src/components/properties/index.jsindex a52f39fc2..6c90e8488 100644--- a/apps/web/src/components/properties/index.js+++ b/apps/web/src/components/properties/index.js@@ -9,7 +9,7 @@ import Animated from "../animated";import Toggle from "./toggle";import { navigate } from "../../navigation";import IconTag from "../icon-tag";-import FileSaver from "file-saver";+import FS from "../../interfaces/fs";const tools = [{ key: "pinned", icon: Icon.Pin, label: "Pin" },@@ -286,28 +286,13 @@ function Properties({ noteId }) {attachment.metadata.hash,attachment.metadata.hash);- const data = await db.fs.readEncrypted(- attachment.metadata.hash,- await db.user.getEncryptionKey(),- {- iv: attachment.iv,- salt: attachment.salt,- length: attachment.length,- alg: attachment.alg,- outputType: "uint8array",- }- );- // download(- // attachment.metadata.filename,- // data,- // attachment.metadata.type- // );- FileSaver.saveAs(- new Blob([data], {- type: attachment.metadata.type,- }),- attachment.metadata.filename- );++ await FS.saveFile(attachment.metadata.hash, {+ key: await db.user.getEncryptionKey(),+ iv: attachment.iv,+ name: attachment.metadata.filename,+ size: attachment.length,+ });}}><Icon.Download size={16} />diff --git a/apps/web/src/interfaces/fs.js b/apps/web/src/interfaces/fs.jsindex a96b9f962..831ed1bd7 100644--- a/apps/web/src/interfaces/fs.js+++ b/apps/web/src/interfaces/fs.js@@ -1,46 +1,32 @@+import "web-streams-polyfill/dist/ponyfill";import localforage from "localforage";-import { createXXHash3, xxhash3 } from "hash-wasm";+import { xxhash64, createXXHash64 } from "hash-wasm";import axios from "axios";import { AppEventManager, AppEvents } from "../common";// eslint-disable-next-line import/no-webpack-loader-syntaximport "worker-loader!nncryptoworker/dist/src/worker.js";import { StreamableFS } from "streamablefs";import NNCrypto from "./nncrypto.stub";+import hosts from "notes-core/utils/constants";+import StreamSaver from "streamsaver";+StreamSaver.mitm = "/downloader.html";-const PLACEHOLDER = `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMzUuNDcgMTM1LjQ3Ij48ZyBmaWxsPSJncmF5Ij48cGF0aCBkPSJNNjUuNjMgNjUuODZhNC40OCA0LjQ4IDAgMSAwLS4wMS04Ljk2IDQuNDggNC40OCAwIDAgMCAwIDguOTZ6bTAtNi4zM2ExLjg1IDEuODUgMCAxIDEgMCAzLjcgMS44NSAxLjg1IDAgMCAxIDAtMy43em0wIDAiLz48cGF0aCBkPSJNODguNDkgNDguNTNINDYuOThjLS45IDAtMS42NC43My0xLjY0IDEuNjRWODUuM2MwIC45Ljc0IDEuNjQgMS42NCAxLjY0aDQxLjVjLjkxIDAgMS42NC0uNzQgMS42NC0xLjY0VjUwLjE3YzAtLjktLjczLTEuNjQtMS42My0xLjY0Wm0tLjk5IDIuNjJ2MjAuNzdsLTguMjUtOC4yNWExLjM4IDEuMzggMCAwIDAtMS45NSAwTDY1LjYzIDc1LjM0bC03LjQ2LTcuNDZhMS4zNyAxLjM3IDAgMCAwLTEuOTUgMGwtOC4yNSA4LjI1VjUxLjE1Wk00Ny45NyA4NC4zMXYtNC40N2w5LjIyLTkuMjIgNy40NiA3LjQ1YTEuMzcgMS4zNyAwIDAgMCAxLjk1IDBMNzguMjcgNjYuNGw5LjIzIDkuMjN2OC42OHptMCAwIi8+PC9nPjwvc3ZnPg==`;+const ABYTES = 17;+const CHUNK_SIZE = 5 * 1024 * 1024;+const ENCRYPTED_CHUNK_SIZE = CHUNK_SIZE + ABYTES;const crypto = new NNCrypto("/static/js/bundle.worker.js");const streamablefs = new StreamableFS("streamable-fs");-const fs = localforage.createInstance({- storeName: "notesnook-fs",- name: "NotesnookFS",- driver: [localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE],-});--fs.hasItem = async function (key) {- const keys = await fs.keys();- return keys.includes(key);-};/**- * We perform 4 steps here:- * 1. We convert base64 to Uint8Array (if we get base64, that is)- * 2. We hash the Uint8Array.- * 3. We encrypt the Uint8Array- * 4. We save the encrypted Uint8Array* @param {File} file+ * @param {import("nncrypto/dist/src/types").SerializedKey} key+ * @param {string} hash*/-async function* writeEncryptedFile(file, key) {+async function writeEncryptedFile(file, key, hash) {if (!localforage.supports(localforage.INDEXEDDB))throw new Error("This browser does not support IndexedDB.");- const reader = file.stream().getReader();- const { hash, type: hashType } = await hashStream(reader);- reader.releaseLock();-- yield { hash, hashType };-let offset = 0;- let CHUNK_SIZE = 5 * 1024 * 1024;const fileHandle = await streamablefs.createFile(hash, file.size, file.type);@@ -66,8 +52,6 @@ async function* writeEncryptedFile(file, key) {);return {- hash,- hashType,iv: iv,length: file.size,salt: key.salt,@@ -83,30 +67,13 @@ async function* writeEncryptedFile(file, key) {* 4. We save the encrypted Uint8Array*/async function writeEncrypted(filename, { data, type, key, hash }) {- const saveAsBuffer = localforage.supports(localforage.INDEXEDDB);if (type === "base64") data = new Uint8Array(Buffer.from(data, "base64"));if (!hash) hash = await hashBuffer(data);if (!filename) filename = hash;- if (await fs.hasItem(filename)) return {};-- const output = await crypto.encrypt(- key,- {- data,- format: "uint8array",- },- saveAsBuffer ? "uint8array" : "base64"- );-- await fs.setItem(filename, output.cipher);- return {- iv: output.iv,- length: output.length,- salt: output.salt,- alg: output.alg,- };+ const blob = new Blob([data], { type });+ return await writeEncryptedFile(blob, key, hash);}/**@@ -116,8 +83,8 @@ async function writeEncrypted(filename, { data, type, key, hash }) {*/async function hashBuffer(data) {return {- hash: await xxhash3(data),- type: "xxh3",+ hash: await xxhash64(data),+ type: "xxh64",};}@@ -127,7 +94,7 @@ async function hashBuffer(data) {* @returns*/async function hashStream(reader) {- const hasher = await createXXHash3();+ const hasher = await createXXHash64();hasher.init();while (true) {@@ -136,100 +103,211 @@ async function hashStream(reader) {hasher.update(value);}- return { type: "xxh3", hash: hasher.digest("hex") };+ return { type: "xxh64", hash: hasher.digest("hex") };}async function readEncrypted(filename, key, cipherData) {console.log("Reading encrypted file", filename);-- const readAsBuffer = localforage.supports(localforage.INDEXEDDB);- cipherData.cipher = await fs.getItem(filename);- cipherData.format = readAsBuffer ? "uint8array" : "base64";-- if (!cipherData.cipher) {+ const fileHandle = await streamablefs.readFile(filename);+ if (!fileHandle) {console.error(`File not found. Filename: ${filename}`);return null;}- return await crypto.decrypt(key, cipherData, cipherData.outputType);+ const reader = fileHandle.getReader();+ const plainText = new Uint8Array(+ fileHandle.file.size + fileHandle.file.chunks * ABYTES+ );++ let offset = 0;+ await crypto.decryptStream(+ key,+ cipherData.iv,+ {+ read: async () => {+ const { value } = await reader.read();+ return value;+ },+ write: async (chunk) => {+ if (!chunk) return;++ plainText.set(chunk, offset);+ offset += chunk.length;+ },+ },+ filename+ );++ return cipherData.outputType === "base64"+ ? Buffer.from(plainText).toString("base64")+ : plainText;}async function uploadFile(filename, requestOptions) {console.log("Request to upload file", filename, requestOptions);- const { url, cancellationToken } = requestOptions;- let cipher = await fs.getItem(filename);- if (!cipher) throw new Error(`File not found. Filename: ${filename}`);+ const fileHandle = await streamablefs.readFile(filename);+ if (!fileHandle)+ throw new Error(`File stream not found. Filename: ${filename}`);- const readAsBuffer = localforage.supports(localforage.INDEXEDDB);- if (!readAsBuffer)- cipher = Uint8Array.from(window.atob(cipher), (c) => c.charCodeAt(0));+ let {+ uploadedChunks = [],+ uploadedBytes = 0,+ uploaded = false,+ uploadId = "",+ } = fileHandle.file.additionalData || {};- const response = await axios.request({- url: url,- method: "PUT",- headers: {- "Content-Type": "",- },- cancelToken: cancellationToken,- data: new Blob([cipher.buffer]),- onUploadProgress: (ev) => {- console.log("Uploading file", filename, ev);- AppEventManager.publish(AppEvents.UPDATE_ATTACHMENT_PROGRESS, {+ if (uploaded) return true;++ const { headers, cancellationToken } = requestOptions;++ const initiateMultiPartUpload = await axios.get(+ `${hosts.API_HOST}/s3/multipart?name=${filename}&parts=${fileHandle.file.chunks}&uploadId=${uploadId}`,+ {+ headers,+ cancelToken: cancellationToken,+ }+ );+ if (!isSuccessStatusCode(initiateMultiPartUpload.status))+ throw new Error("Could not initiate multi-part upload.");++ uploadId = initiateMultiPartUpload.data.uploadId;+ const { parts } = initiateMultiPartUpload.data;++ await fileHandle.addAdditionalData("uploadId", uploadId);++ function onUploadProgress(ev) {+ reportProgress(+ {+ total: fileHandle.file.size,+ loaded: uploadedBytes + ev.loaded,+ },+ {type: "upload",hash: filename,- total: ev.total,- loaded: ev.loaded,- });+ }+ );+ }++ for (let i = uploadedChunks.length; i < parts.length; ++i) {+ const url = parts[i];+ const chunk = await fileHandle.readChunk(i);+ if (!chunk) throw new Error(`Chunk at offset ${i} not found.`);++ const response = await axios.request({+ url,+ method: "PUT",+ headers: { "Content-Type": "" },+ cancelToken: cancellationToken,+ data: new Blob([chunk.buffer]),+ onUploadProgress,+ });+ if (!isSuccessStatusCode(response.status) || !response.headers.etag)+ throw new Error(`Failed to upload chunk at offset ${i}.`);++ uploadedBytes += chunk.length;+ uploadedChunks.push({+ PartNumber: i + 1,+ ETag: JSON.parse(response.headers.etag),+ });+ await fileHandle.addAdditionalData("uploadedChunks", uploadedChunks);+ await fileHandle.addAdditionalData("uploadedBytes", uploadedBytes);+ }++ const completeMultiPartUpload = await axios.post(+ `${hosts.API_HOST}/s3/multipart`,+ {+ Key: filename,+ UploadId: uploadId,+ PartETags: uploadedChunks,},- });+ {+ headers,+ cancelToken: cancellationToken,+ }+ );+ if (!isSuccessStatusCode(completeMultiPartUpload.status))+ throw new Error("Could not complete multi-part upload.");- console.log("File uploaded:", filename, response);- return isSuccessStatusCode(response.status);+ await fileHandle.addAdditionalData("uploaded", true);++ return true;+}++function reportProgress(ev, { type, hash }) {+ AppEventManager.publish(AppEvents.UPDATE_ATTACHMENT_PROGRESS, {+ type,+ hash,+ total: ev.total,+ loaded: ev.loaded,+ });}async function downloadFile(filename, requestOptions) {const { url, headers, cancellationToken } = requestOptions;console.log("Request to download file", filename, url, headers);- if (await fs.hasItem(filename)) return true;+ if (await streamablefs.exists(filename)) return true;const response = await axios.get(url, {headers: headers,- responseType: "blob",+ responseType: "arraybuffer",cancelToken: cancellationToken,- onDownloadProgress: (ev) => {- console.log("Downloading file", filename, ev);- AppEventManager.publish(AppEvents.UPDATE_ATTACHMENT_PROGRESS, {- type: "download",- hash: filename,- total: ev.total,- loaded: ev.loaded,- });- },+ onDownloadProgress: (ev) =>+ reportProgress(ev, { type: "download", hash: filename }),});+console.log("File downloaded", filename, url, response);if (!isSuccessStatusCode(response.status)) return false;- const blob = new Blob([response.data]);- await fs.setItem(filename, new Uint8Array(await blob.arrayBuffer()));++ const distributor = new ChunkDistributor(ENCRYPTED_CHUNK_SIZE);+ distributor.fill(new Uint8Array(response.data));+ distributor.close();++ const fileHandle = await streamablefs.createFile(+ filename,+ response.data.byteLength,+ "application/octet-stream"+ );++ for (let chunk of distributor.chunks) {+ fileHandle.write(chunk.data);+ }+return true;}-async function deleteFile(filename, requestOptions) {- const { url, headers, cancellationToken } = requestOptions;- console.log("Request to delete file", filename, url, headers);- if (!(await fs.hasItem(filename))) return true;+function exists(filename) {+ return streamablefs.exists(filename);+}- const response = await axios.delete(url, {- cancelToken: cancellationToken,- headers: headers,+async function saveFile(filename, { key, iv, name, size }) {+ const fileHandle = await streamablefs.readFile(filename);+ if (!fileHandle) return false;++ const writerStream = StreamSaver.createWriteStream(name, {+ size,});- const result = isSuccessStatusCode(response.status);- if (result) await fs.removeItem(filename);- return result;-}-function exists(filename) {- return fs.hasItem(filename);+ const reader = fileHandle.getReader();+ const writer = writerStream.getWriter();+ await writer.ready;++ await crypto.decryptStream(+ key,+ iv,+ {+ read: async () => {+ const { value } = await reader.read();+ return value;+ },+ write: async (chunk) => {+ await writer.ready;+ if (!chunk) writer.close();+ else await writer.write(chunk);+ },+ },+ filename+ );}const FS = {@@ -237,7 +315,7 @@ const FS = {readEncrypted,uploadFile: cancellable(uploadFile),downloadFile: cancellable(downloadFile),- deleteFile,+ saveFile,exists,hashBuffer,hashStream,@@ -255,7 +333,90 @@ function cancellable(operation) {requestOptions.cancellationToken = source.token;return {execute: () => operation(filename, requestOptions),- cancel: (message) => source.cancel(message),+ cancel: (message) => {+ source.cancel(message);+ },};};}++class ChunkDistributor {+ /**+ * @typedef {{length: number, data: Uint8Array, final: boolean}} Chunk+ */++ constructor(chunkSize) {+ this.chunkSize = chunkSize;+ this.chunks = [];+ this.filledCount = 0;+ this.done = false;+ }++ /**+ * @returns {Chunk}+ */+ get lastChunk() {+ return this.chunks[this.chunks.length - 1];+ }++ /**+ * @returns {boolean}+ */+ get isLastChunkFilled() {+ return this.lastChunk.length === this.chunkSize;+ }++ /**+ * @returns {Chunk}+ */+ get firstChunk() {+ const chunk = this.chunks.shift();+ if (chunk.data.length === this.chunkSize) this.filledCount--;+ return chunk;+ }++ close() {+ this.lastChunk.data = this.lastChunk.data.slice(0, this.lastChunk.length);+ this.lastChunk.final = true;+ this.done = true;+ }++ /**+ * @param {Uint8Array} data+ */+ fill(data) {+ if (this.done || !data || !data.length) return;++ const dataLength = data.length;+ const totalBlocks = Math.ceil(dataLength / this.chunkSize);++ for (let i = 0; i < totalBlocks; ++i) {+ const start = i * this.chunkSize;++ if (this.lastChunk && !this.isLastChunkFilled) {+ const needed = this.chunkSize - this.lastChunk.length;+ const end = Math.min(start + needed, dataLength);+ const chunk = data.slice(start, end);++ this.lastChunk.data.set(chunk, this.lastChunk.length);+ this.lastChunk.length += chunk.length;++ if (this.lastChunk.length === this.chunkSize) this.filledCount++;++ if (end !== dataLength) {+ this.fill(data.slice(end));+ break;+ }+ } else {+ const end = Math.min(start + this.chunkSize, dataLength);+ let chunk = data.slice(start, end);++ const buffer = new Uint8Array(this.chunkSize);+ buffer.set(chunk, 0);++ this.chunks.push({ data: buffer, final: false, length: chunk.length });+ if (chunk.length === this.chunkSize) this.filledCount++;+ }+ }+ }+}diff --git a/apps/web/src/interfaces/storage.js b/apps/web/src/interfaces/storage.jsindex 38d6ffe65..6985634b3 100644--- a/apps/web/src/interfaces/storage.js+++ b/apps/web/src/interfaces/storage.js@@ -66,6 +66,7 @@ async function getCryptoKey(name) {}}+const APP_SALT = "oVzKtazBo7d8sb7TBvY9jw";const Storage = {read,readMulti,@@ -75,9 +76,14 @@ const Storage = {getAllKeys,deriveCryptoKey,getCryptoKey,- hash: crypto.hash,- encrypt: crypto.encrypt,- decrypt: crypto.decrypt,+ hash: (password, email) => crypto.hash(password, `${APP_SALT}${email}`),+ encrypt: (key, plainText) =>+ crypto.encrypt(key, { format: "text", data: plainText }, "base64"),+ decrypt: async (key, cipherData) => {+ cipherData.format = "base64";+ const result = await crypto.decrypt(key, cipherData);+ return result.data;+ },};export default Storage;