Skip to content

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

desktop: secure desktop app by disabling nodeIntegration & enabling contextIsolation

Abdullah Attabd04427e038e
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 55dd55ed4..186a94cb9 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -21,6 +21,16 @@
"types": "./dist/types/index.d.ts",
"default": "./dist/esm/index.js"
}
+ },
+ "./*": {
+ "require": {
+ "types": "./dist/types/*",
+ "default": "./dist/cjs/*"
+ },
+ "import": {
+ "types": "./dist/types/*",
+ "default": "./dist/esm/*"
+ }
}
},
"homepage": "https://notesnook.com/",
diff --git a/apps/desktop/src/api/backups.ts b/apps/desktop/src/api/backups.ts
new file mode 100644
index 000000000..230cb0c5b
--- /dev/null
+++ b/apps/desktop/src/api/backups.ts
@@ -0,0 +1,89 @@
+/*
+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 { initTRPC } from "@trpc/server";
+import { createWriteStream, mkdirSync } from "node:fs";
+import path from "node:path";
+import { z } from "zod";
+import { config } from "../utils/config";
+import { resolvePath } from "../utils/resolve-path";
+import { app } from "electron";
+
+const t = initTRPC.create();
+
+const activeStreams = new Map<string, NodeJS.WritableStream>();
+
+function generateId() {
+ return Math.random().toString(36).slice(2);
+}
+
+export const backupsRouter = t.router({
+ open: t.procedure
+ .input(z.object({ filename: z.string() }))
+ .mutation(({ input }) => {
+ const { filename } = input;
+ if (filename.includes(path.sep) || filename.includes("\\"))
+ throw new Error("Invalid filename");
+ const resolvedBackupDir = resolvePath(config.backupDirectory);
+ const backupPath = path.resolve(resolvedBackupDir, filename);
+ if (!backupPath.startsWith(resolvedBackupDir))
+ throw new Error("Invalid filename");
+
+ mkdirSync(resolvedBackupDir, { recursive: true });
+ const stream = createWriteStream(backupPath, { encoding: "utf-8" });
+ const id = generateId();
+ activeStreams.set(id, stream);
+ return id;
+ }),
+
+ write: t.procedure
+ .input(z.object({ id: z.string(), chunk: z.string() }))
+ .mutation(({ input }) => {
+ const stream = activeStreams.get(input.id);
+ if (!stream) throw new Error("Stream not found");
+ return new Promise<void>((resolve, reject) => {
+ stream.write(Buffer.from(input.chunk, "base64"), (err) =>
+ err ? reject(err) : resolve()
+ );
+ });
+ }),
+
+ close: t.procedure
+ .input(z.object({ id: z.string() }))
+ .mutation(({ input }) => {
+ const stream = activeStreams.get(input.id);
+ if (!stream) throw new Error("Stream not found");
+ return new Promise<void>((resolve) => {
+ stream.end(() => {
+ activeStreams.delete(input.id);
+ resolve();
+ });
+ });
+ })
+});
+
+app.on("before-quit", () => {
+ try {
+ for (const stream of activeStreams.values()) {
+ stream.end();
+ }
+ } catch {
+ // ignore
+ }
+});
diff --git a/apps/desktop/src/api/index.ts b/apps/desktop/src/api/index.ts
index 4875de6ae..abd7e80b8 100644
--- a/apps/desktop/src/api/index.ts
+++ b/apps/desktop/src/api/index.ts
@@ -25,6 +25,8 @@ import { updaterRouter } from "./updater";
import { bridgeRouter } from "./bridge";
import { safeStorageRouter } from "./safe-storage";
import { windowRouter } from "./window";
+import { sqliteRouter } from "./sqlite-kysely";
+import { backupsRouter } from "./backups";
const t = initTRPC.create();
@@ -35,10 +37,13 @@ export const router = t.router({
updater: updaterRouter,
bridge: bridgeRouter,
safeStorage: safeStorageRouter,
- window: windowRouter
+ window: windowRouter,
+ sqlite: sqliteRouter,
+ backups: backupsRouter
});
-export const api = router.createCaller({});
+const createCaller = t.createCallerFactory(router);
+export const api = createCaller({});
// Export type router type signature,
// NOT the router itself.
diff --git a/apps/desktop/src/api/os-integration.ts b/apps/desktop/src/api/os-integration.ts
index 9ee21b79b..8e2db5936 100644
--- a/apps/desktop/src/api/os-integration.ts
+++ b/apps/desktop/src/api/os-integration.ts
@@ -24,7 +24,6 @@ import {
dialog,
Menu,
MenuItem,
- nativeImage,
nativeTheme,
Notification,
shell
@@ -33,17 +32,16 @@ import { AutoLaunch } from "../utils/autolaunch";
import { config, DesktopIntegration } from "../utils/config";
import { bringToFront } from "../utils/bring-to-front";
import { getTheme, setTheme, Theme } from "../utils/theme";
-import { existsSync, mkdirSync, writeFileSync } from "fs";
-import { dirname } from "path";
+import { existsSync } from "fs";
import { resolvePath } from "../utils/resolve-path";
import { observable } from "@trpc/server/observable";
import { AssetManager } from "../utils/asset-manager";
import { isFlatpak, isPortable, isSnap } from "../utils";
import { setupDesktopIntegration } from "../utils/desktop-integration";
-import { rm } from "fs/promises";
import { disableCustomDns, enableCustomDns } from "../utils/custom-dns";
import type { MenuItem as NNMenuItem } from "@notesnook/ui";
import { platform } from "os";
+import { strings } from "@notesnook/intl";
const t = initTRPC.create();
@@ -62,6 +60,7 @@ export const osIntegrationRouter = t.router({
isFlatpak: t.procedure.query(() => isFlatpak()),
isSnap: t.procedure.query(() => isSnap()),
isPortable: t.procedure.query(() => isPortable()),
+ backupDirectory: t.procedure.query(() => config.backupDirectory),
zoomFactor: t.procedure.query(() => config.zoomFactor),
setZoomFactor: t.procedure.input(z.number()).mutation(({ input: factor }) => {
@@ -118,53 +117,19 @@ export const osIntegrationRouter = t.router({
setupDesktopIntegration(settings);
}),
- selectDirectory: t.procedure
- .input(
- z.object({
- title: z.string().optional(),
- buttonLabel: z.string().optional(),
- defaultPath: z.string().optional()
- })
- )
- .query(async ({ input }) => {
- if (!globalThis.window) return undefined;
-
- const { title, buttonLabel, defaultPath } = input;
-
- const result = await dialog.showOpenDialog(globalThis.window, {
- title,
- buttonLabel,
- properties: ["openDirectory"],
- defaultPath: defaultPath && resolvePath(defaultPath)
- });
- if (result.canceled) return undefined;
-
- return result.filePaths[0];
- }),
-
- saveFile: t.procedure
- .input(z.object({ data: z.string(), filePath: z.string() }))
- .query(({ input }) => {
- const { data, filePath } = input;
- if (!data || !filePath) return;
+ selectBackupDirectory: t.procedure.input(z.undefined()).query(async () => {
+ if (!globalThis.window) return undefined;
- const resolvedPath = resolvePath(filePath);
-
- mkdirSync(dirname(resolvedPath), { recursive: true });
- writeFileSync(resolvedPath, data);
- }),
+ const result = await dialog.showOpenDialog(globalThis.window, {
+ title: strings.selectBackupDir(),
+ buttonLabel: strings.select(),
+ properties: ["openDirectory"],
+ defaultPath: config.backupDirectory && resolvePath(config.backupDirectory)
+ });
+ if (result.canceled) return undefined;
- resolvePath: t.procedure
- .input(z.object({ filePath: z.string() }))
- .query(({ input }) => {
- const { filePath } = input;
- return resolvePath(filePath);
- }),
-
- deleteFile: t.procedure.input(z.string()).query(async ({ input }) => {
- await rm(input);
+ config.backupDirectory = result.filePaths[0];
}),
-
restart: t.procedure.query(() => {
app.relaunch();
app.exit();
diff --git a/apps/desktop/src/api/sqlite-kysely.ts b/apps/desktop/src/api/sqlite-kysely.ts
index c63207ab6..8b2625d18 100644
--- a/apps/desktop/src/api/sqlite-kysely.ts
+++ b/apps/desktop/src/api/sqlite-kysely.ts
@@ -19,6 +19,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import type { Database, Statement } from "better-sqlite3-multiple-ciphers";
import type { QueryResult } from "@streetwriters/kysely";
+import { app } from "electron";
+import path from "node:path";
+import { initTRPC } from "@trpc/server";
type SQLiteCompatibleType =
| number
@@ -28,25 +31,32 @@ type SQLiteCompatibleType =
| bigint
| null;
-export class SQLite {
+class SQLite {
sqlite?: Database;
initialized = false;
preparedStatements: Map<string, Statement<unknown[]>> = new Map();
retryCounter: Record<string, number> = {};
extensionsLoaded = false;
+ private filePath?: string;
constructor() {
console.log("new sqlite worker");
}
- async open(filePath: string) {
+ async open(filename: string) {
if (this.sqlite) {
console.error("Database is already initialized");
return;
}
+ this.filePath =
+ filename === ":memory:"
+ ? filename
+ : path.join(app.getPath("userData"), filename) + ".sql";
+ if (!isPathAllowed(this.filePath))
+ throw new Error("Database path is not allowed: " + this.filePath);
this.sqlite = require("better-sqlite3-multiple-ciphers")(
- filePath
+ this.filePath
).unsafeMode(true);
}
@@ -155,9 +165,11 @@ export class SQLite {
this.sqlite = undefined;
}
- async delete(filePath: string) {
+ async delete() {
+ if (!this.filePath) return;
+
await this.close();
- await require("fs/promises").rm(filePath, {
+ await require("node:fs/promises").rm(this.filePath, {
force: true,
maxRetries: 5,
retryDelay: 500
@@ -221,3 +233,67 @@ function rewriteError(e: Error, message: string) {
error.cause = e.cause;
return error;
}
+
+function isPathAllowed(databasePath: string) {
+ if (databasePath === ":memory:") return true;
+ const base = app.getPath("userData");
+ const resolved = path.resolve(databasePath);
+ return resolved.startsWith(base + path.sep);
+}
+
+const t = initTRPC.create();
+
+const databases: Record<string, SQLite> = {};
+
+export const sqliteRouter = t.router({
+ open: t.procedure
+ .input((v) => v)
+ .mutation(async ({ input }) => {
+ const { filePath } = input as { filePath: string };
+ if (databases[filePath]) return filePath;
+ const sqlite = new SQLite();
+ await sqlite.open(filePath);
+ databases[filePath] = sqlite;
+ return filePath;
+ }),
+ run: t.procedure
+ .input((v) => v)
+ .mutation(async ({ input }) => {
+ const { id, sql, parameters } = input as {
+ id: string;
+ sql: string;
+ parameters?: SQLiteCompatibleType[];
+ };
+ const sqlite = databases[id];
+ if (!sqlite) throw new Error("Database not found for id: " + id);
+ return await sqlite.run(sql, parameters);
+ }),
+ close: t.procedure
+ .input((v) => v)
+ .mutation(async ({ input }) => {
+ const { id } = input as { id: string };
+ const sqlite = databases[id];
+ if (!sqlite) throw new Error("Database not found for id: " + id);
+ await sqlite.close();
+ delete databases[id];
+ }),
+ delete: t.procedure
+ .input((v) => v)
+ .mutation(async ({ input }) => {
+ const { id } = input as { id: string };
+ const sqlite = databases[id];
+ if (!sqlite) throw new Error("Database not found for id: " + id);
+ await sqlite.delete();
+ delete databases[id];
+ })
+});
+
+app.on("before-quit", async () => {
+ for (const db of Object.values(databases)) {
+ try {
+ await db.close();
+ } catch (e) {
+ console.error("Error closing database:", e);
+ }
+ }
+});
diff --git a/apps/desktop/src/index.ts b/apps/desktop/src/index.ts
index 8a582386d..540144d41 100644
--- a/apps/desktop/src/index.ts
+++ b/apps/desktop/src/index.ts
@@ -21,4 +21,3 @@ export { PATHS } from "./constants";
export type { AppRouter } from "./api";
export { type UpdateInfo } from "builder-util-runtime";
export { type DesktopIntegration } from "./utils/config";
-export { SQLite } from "./api/sqlite-kysely.js";
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 9514a1bca..3ec4905ad 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -39,6 +39,7 @@ import { setupDesktopIntegration } from "./utils/desktop-integration";
import { disableCustomDns, enableCustomDns } from "./utils/custom-dns";
import { Messages, setI18nGlobal } from "@notesnook/intl";
import { i18n } from "@lingui/core";
+import { PATHS } from "./constants";
const locale =
process.env.NODE_ENV === "development"
@@ -129,9 +130,6 @@ async function createWindow() {
webPreferences: {
zoomFactor: config.zoomFactor,
- nodeIntegration: true,
- contextIsolation: false,
- nodeIntegrationInWorker: true,
spellcheck: config.isSpellCheckerEnabled,
preload: __dirname + "/preload.js"
}
@@ -225,7 +223,8 @@ app.once("ready", async () => {
if (!isDevelopment()) registerProtocol();
await createWindow();
- configureAutoUpdater();
+ await migrateBackupDirectory();
+ await configureAutoUpdater();
});
app.once("window-all-closed", () => {
@@ -286,3 +285,27 @@ function createURL(options: CLIOptions, path = "/") {
return url;
}
+
+async function migrateBackupDirectory() {
+ if (!globalThis.window) return;
+ try {
+ if (config.backupDirectory !== PATHS.backupsDirectory) return;
+ const oldPath = await globalThis.window?.webContents.executeJavaScript(
+ `localStorage.getItem("backupStorageLocation")`
+ );
+ if (!oldPath || oldPath === PATHS.backupsDirectory) return;
+ config.backupDirectory = oldPath;
+ } catch (e) {
+ console.error("Failed to migrate backup directory", e);
+ const pressedButton = dialog.showMessageBoxSync(globalThis.window, {
+ message:
+ "Failed to migrate backup directory. It has been reset to default.",
+ title: "Backup Directory Migration Failed",
+ type: "error",
+ buttons: ["Set backup directory", "Ignore"]
+ });
+ if (pressedButton === 0) {
+ await api.integration.selectBackupDirectory();
+ }
+ }
+}
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 0e20df525..dcf2a1ca7 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -19,25 +19,21 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
/* eslint-disable no-var */
import { ELECTRON_TRPC_CHANNEL } from "electron-trpc/main";
-// import type { NNCrypto } from "@notesnook/crypto";
-import { ipcRenderer } from "electron";
-import { platform } from "os";
+import { ipcRenderer, contextBridge } from "electron";
declare global {
- var os: () => "mas" | ReturnType<typeof platform>;
+ var os: () => "mas" | typeof process.platform;
var electronTRPC: any;
- // var NativeNNCrypto: (new () => NNCrypto) | undefined;
}
-process.once("loaded", async () => {
- const electronTRPC = {
- sendMessage: (operation: any) =>
- ipcRenderer.send(ELECTRON_TRPC_CHANNEL, operation),
- onMessage: (callback: any) =>
- ipcRenderer.on(ELECTRON_TRPC_CHANNEL, (_event, args) => callback(args))
- };
- globalThis.electronTRPC = electronTRPC;
-});
-
-// globalThis.NativeNNCrypto = require("@notesnook/crypto").NNCrypto;
-globalThis.os = () => (MAC_APP_STORE ? "mas" : platform());
+const electronTRPC = {
+ sendMessage: (operation: any) =>
+ ipcRenderer.send(ELECTRON_TRPC_CHANNEL, operation),
+ onMessage: (callback: any) =>
+ ipcRenderer.on(ELECTRON_TRPC_CHANNEL, (_event, args) => callback(args))
+};
+
+const os = () => (MAC_APP_STORE ? "mas" : process.platform);
+
+contextBridge.exposeInMainWorld("electronTRPC", electronTRPC);
+contextBridge.exposeInMainWorld("os", os);
diff --git a/apps/desktop/src/utils/config.ts b/apps/desktop/src/utils/config.ts
index 2e13a8f30..744b1cd0e 100644
--- a/apps/desktop/src/utils/config.ts
+++ b/apps/desktop/src/utils/config.ts
@@ -21,6 +21,7 @@ import { nativeTheme } from "electron";
import { JSONStorage } from "./json-storage";
import { z } from "zod";
import { autoUpdater } from "electron-updater";
+import { PATHS } from "../constants";
export const DesktopIntegration = z.object({
autoStart: z.boolean().optional(),
@@ -53,7 +54,8 @@ export const config = {
backgroundColor: nativeTheme.themeSource === "dark" ? "#0f0f0f" : "#ffffff",
windowControlsIconColor:
- nativeTheme.themeSource === "dark" ? "#ffffff" : "#000000"
+ nativeTheme.themeSource === "dark" ? "#ffffff" : "#000000",
+ backupDirectory: PATHS.backupsDirectory
};
type ConfigKey = keyof typeof config;
diff --git a/apps/web/src/common/desktop-bridge/index.desktop.ts b/apps/web/src/common/desktop-bridge/index.desktop.ts
index 64d35c7ae..fd7da7184 100644
--- a/apps/web/src/common/desktop-bridge/index.desktop.ts
+++ b/apps/web/src/common/desktop-bridge/index.desktop.ts
@@ -23,7 +23,6 @@ import type { AppRouter } from "@notesnook/desktop";
import { AppEventManager, AppEvents } from "../app-events";
import { TaskScheduler } from "../../utils/task-scheduler";
import { checkForUpdate } from "../../utils/updater";
-import { showToast } from "../../utils/toast";
import { store as settingStore } from "../../stores/setting-store";
export const desktop: ReturnType<typeof createTRPCProxyClient<AppRouter>> =
@@ -65,27 +64,6 @@ function attachListeners() {
attachListener(AppEvents.updateError)
);
- desktop.bridge.onOpenLink.subscribe(
- undefined,
- attachListener(AppEvents.onOpenLink)
- );
-
- desktop.bridge.onCreateItem.subscribe(
- undefined,
- attachListener(AppEvents.onCreateItem)
- );
-
- // desktop.window.onClose.subscribe(undefined, {
- // async onData() {
- // try {
- // await db.sql().destroy();
- // await logManager?.close();
- // } catch {
- // // ignore
- // }
- // }
- // });
-
TaskScheduler.register("updateCheck", "0 0 */12 * * * *", () => {
checkForUpdate(settingStore.get().autoUpdates);
});
@@ -101,23 +79,19 @@ function attachListener(event: string) {
}
export async function createWritableStream(path: string) {
- try {
- const resolvedPath = await desktop.integration.resolvePath.query({
- filePath: path
- });
- if (!resolvedPath) throw new Error("invalid path.");
- const { mkdirSync, createWriteStream }: typeof import("fs") = require("fs");
- const { dirname }: typeof import("path") = require("path");
- const { Writable } = require("stream");
-
- mkdirSync(dirname(resolvedPath), { recursive: true });
- return new WritableStream(
- Writable.toWeb(
- createWriteStream(resolvedPath, { encoding: "utf-8" })
- ).getWriter()
- );
- } catch (ex) {
- console.error(ex);
- if (ex instanceof Error) showToast("error", ex.message);
- }
+ const id = await desktop.backups.open.mutate({ filename: path });
+ return new WritableStream<Uint8Array>({
+ write(chunk) {
+ return desktop.backups.write.mutate({
+ id,
+ chunk: Buffer.from(chunk).toString("base64")
+ });
+ },
+ close() {
+ return desktop.backups.close.mutate({ id });
+ },
+ abort() {
+ return desktop.backups.close.mutate({ id });
+ }
+ });
}
diff --git a/apps/web/src/common/index.ts b/apps/web/src/common/index.ts
index e533df5cc..3d17d28d5 100644
--- a/apps/web/src/common/index.ts
+++ b/apps/web/src/common/index.ts
@@ -37,7 +37,6 @@ import {
import { showToast } from "../utils/toast";
import { readFile, showFilePicker } from "../utils/file-picker";
import { logger } from "../utils/logger";
-import { PATHS } from "@notesnook/desktop";
import { TaskManager } from "./task-manager";
import { EVENTS, parseInternalLink } from "@notesnook/core";
import { createWritableStream } from "./desktop-bridge";
@@ -127,11 +126,8 @@ export async function createBackup(
})}-${new Date().getSeconds()}${mode === "full" ? "-full" : ""}`,
{ replacement: "-" }
);
- const directory = Config.get("backupStorageLocation", PATHS.backupsDirectory);
const ext = "nnbackupz";
- const filePath = IS_DESKTOP_APP
- ? `${directory}/${filename}.${ext}`
- : `${filename}.${ext}`;
+ const filePath = `${filename}.${ext}`;
const encoder = new TextEncoder();
const error = await TaskManager.startTask<Error | void>({
diff --git a/apps/web/src/common/sqlite/index.desktop.ts b/apps/web/src/common/sqlite/index.desktop.ts
index 9397715fc..58781c93e 100644
--- a/apps/web/src/common/sqlite/index.desktop.ts
+++ b/apps/web/src/common/sqlite/index.desktop.ts
@@ -28,24 +28,20 @@ import {
Driver
} from "@streetwriters/kysely";
import { desktop } from "../desktop-bridge";
-import Worker from "./sqlite.worker.desktop.ts?worker";
-import type { SQLiteWorker } from "./sqlite.worker.desktop";
-import { wrap, Remote } from "comlink";
import { Mutex } from "async-mutex";
import { DialectOptions } from ".";
class SqliteDriver implements Driver {
connection?: DatabaseConnection;
private connectionMutex = new Mutex();
- worker: Remote<SQLiteWorker> = wrap<SQLiteWorker>(new Worker());
+ private handle?: string;
constructor(private readonly config: { name: string }) {}
async init(): Promise<void> {
- const path = await desktop!.integration.resolvePath.query({
- filePath: `userData/${this.config.name}.sql`
+ this.handle = await desktop!.sqlite.open.mutate({
+ filePath: this.config.name
});
- await this.worker.open(path);
- this.connection = new SqliteWorkerConnection(this.worker);
+ this.connection = new SqliteWorkerConnection(this.handle);
}
async acquireConnection(): Promise<DatabaseConnection> {
@@ -75,19 +71,18 @@ class SqliteDriver implements Driver {
}
async destroy(): Promise<void> {
- await this.worker.close();
+ if (!this.handle) return;
+ await desktop!.sqlite.close.mutate({ id: this.handle });
}
async delete() {
- const path = await desktop!.integration.resolvePath.query({
- filePath: `userData/${this.config.name}.sql`
- });
- await this.worker.delete(path);
+ if (!this.handle) return;
+ await desktop!.sqlite.delete.mutate({ id: this.handle });
}
}
class SqliteWorkerConnection implements DatabaseConnection {
- constructor(private readonly worker: Remote<SQLiteWorker>) {}
+ constructor(private readonly handle: string) {}
streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {
throw new Error("wasqlite driver doesn't support streaming");
@@ -97,7 +92,11 @@ class SqliteWorkerConnection implements DatabaseConnection {
compiledQuery: CompiledQuery<unknown>
): Promise<QueryResult<R>> {
const { parameters, sql } = compiledQuery;
- return this.worker.run(sql, parameters as any) as unknown as QueryResult<R>;
+ return (await desktop!.sqlite.run.mutate({
+ id: this.handle,
+ sql,
+ parameters: parameters as any
+ })) as unknown as QueryResult<R>;
}
}
diff --git a/apps/web/src/common/sqlite/sqlite.worker.desktop.ts b/apps/web/src/common/sqlite/sqlite.worker.desktop.ts
deleted file mode 100644
index ec9cb3f11..000000000
--- a/apps/web/src/common/sqlite/sqlite.worker.desktop.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-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 { SQLite } from "@notesnook/desktop";
-import { expose } from "comlink";
-
-export type SQLiteWorker = typeof SQLite.prototype;
-const db = new SQLite();
-expose(db);
diff --git a/apps/web/src/dialogs/progress-dialog.tsx b/apps/web/src/dialogs/progress-dialog.tsx
index 33fd3a710..281a09214 100644
--- a/apps/web/src/dialogs/progress-dialog.tsx
+++ b/apps/web/src/dialogs/progress-dialog.tsx
@@ -45,7 +45,7 @@ export const ProgressDialog = DialogManager.register(function ProgressDialog<T>(
try {
props.onClose(await props.action(setProgress));
} catch (e) {
- console.error(e);
+ console.error("FAILED:", e);
props.onClose(e as Error);
}
})();
diff --git a/apps/web/src/dialogs/settings/backup-export-settings.ts b/apps/web/src/dialogs/settings/backup-export-settings.ts
index 358910b2e..2efa6c707 100644
--- a/apps/web/src/dialogs/settings/backup-export-settings.ts
+++ b/apps/web/src/dialogs/settings/backup-export-settings.ts
@@ -26,10 +26,9 @@ import { useStore as useSettingStore } from "../../stores/setting-store";
import { useStore as useAppStore } from "../../stores/app-store";
import { useStore as useUserStore } from "../../stores/user-store";
import { desktop } from "../../common/desktop-bridge";
-import { PATHS } from "@notesnook/desktop";
const getDesktopBackupsDirectoryPath = () =>
- useSettingStore.getState().backupStorageLocation || PATHS.backupsDirectory;
+ useSettingStore.getState().backupStorageLocation;
export const BackupExportSettings: SettingsGroup[] = [
{
@@ -181,15 +180,12 @@ export const BackupExportSettings: SettingsGroup[] = [
(await verifyAccount());
if (!verified) return;
- const backupStorageLocation = getDesktopBackupsDirectoryPath();
- const location = await desktop?.integration.selectDirectory.query(
- {
- title: strings.selectBackupDir(),
- defaultPath: backupStorageLocation
- }
- );
- if (!location) return;
- useSettingStore.getState().setBackupStorageLocation(location);
+ await desktop?.integration.selectBackupDirectory.query();
+
+ useSettingStore.setState({
+ backupStorageLocation:
+ await desktop?.integration.backupDirectory.query()
+ });
},
variant: "secondary"
}
diff --git a/apps/web/src/global.d.ts b/apps/web/src/global.d.ts
index dc0624fec..7a60d5fe5 100644
--- a/apps/web/src/global.d.ts
+++ b/apps/web/src/global.d.ts
@@ -20,8 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import "vite/client";
import "vite-plugin-svgr/client";
-import "@notesnook/desktop/dist/preload";
-import type { Database } from "@notesnook/core";
+import "@notesnook/desktop/preload.d.ts";
declare global {
var PUBLIC_URL: string;
diff --git a/apps/web/src/stores/setting-store.ts b/apps/web/src/stores/setting-store.ts
index c5619be89..47132b1fb 100644
--- a/apps/web/src/stores/setting-store.ts
+++ b/apps/web/src/stores/setting-store.ts
@@ -53,10 +53,7 @@ class SettingStore extends BaseStore<SettingStore> {
encryptBackups = Config.get("encryptBackups", false);
backupReminderOffset = Config.get("backupReminderOffset", 0);
fullBackupReminderOffset = Config.get("fullBackupReminderOffset", 0);
- backupStorageLocation = Config.get(
- "backupStorageLocation",
- PATHS.backupsDirectory
- );
+ backupStorageLocation = PATHS.backupsDirectory;
doubleSpacedParagraphs = Config.get("doubleSpacedLines", true);
markdownShortcuts = Config.get("markdownShortcuts", false);
fontLigatures = Config.get("fontLigatures", false);
@@ -115,7 +112,8 @@ class SettingStore extends BaseStore<SettingStore> {
zoomFactor: await desktop?.integration.zoomFactor.query(),
autoUpdates: await desktop?.updater.autoUpdates.query(),
proxyRules: await desktop?.integration.proxyRules.query(),
- isInboxEnabled: await db.user.hasInboxKeys()
+ isInboxEnabled: await db.user.hasInboxKeys(),
+ backupStorageLocation: await desktop?.integration.backupDirectory.query()
});
};
@@ -222,11 +220,6 @@ class SettingStore extends BaseStore<SettingStore> {
this.set({ fullBackupReminderOffset: offset });
};
- setBackupStorageLocation = (location: string) => {
- Config.set("backupStorageLocation", location);
- this.set({ backupStorageLocation: location });
- };
-
toggleDoubleSpacedParagraphs = () => {
const doubleSpacedParagraphs = this.get().doubleSpacedParagraphs;
this.set(