Skip to content

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

desktop: fix `Invalid filename` error on backup creation

Abdullah Atta643515c6c47a
diff --git a/apps/desktop/src/api/backups.ts b/apps/desktop/src/api/backups.ts
index 230cb0c5b..dee36023a 100644
--- a/apps/desktop/src/api/backups.ts
+++ b/apps/desktop/src/api/backups.ts
@@ -33,17 +33,38 @@ function generateId() {
return Math.random().toString(36).slice(2);
}
+function getStreamOrThrow(id: string, operation: "write" | "close") {
+ const stream = activeStreams.get(id);
+ if (!stream) {
+ throw new Error(
+ `Backup stream not found during ${operation}. The stream may have already been closed or was never opened. Stream id: ${id}`
+ );
+ }
+ return stream;
+}
+
export const backupsRouter = t.router({
open: t.procedure
.input(z.object({ filename: z.string() }))
.mutation(({ input }) => {
const { filename } = input;
+ if (!filename.trim()) {
+ throw new Error("Invalid backup filename: filename cannot be empty.");
+ }
if (filename.includes(path.sep) || filename.includes("\\"))
- throw new Error("Invalid filename");
+ throw new Error(
+ `Invalid backup filename: expected a plain file name without path separators, received "${filename}".`
+ );
const resolvedBackupDir = resolvePath(config.backupDirectory);
const backupPath = path.resolve(resolvedBackupDir, filename);
- if (!backupPath.startsWith(resolvedBackupDir))
- throw new Error("Invalid filename");
+ const relativeBackupPath = path.relative(resolvedBackupDir, backupPath);
+ if (
+ relativeBackupPath.startsWith("..") ||
+ path.isAbsolute(relativeBackupPath)
+ )
+ throw new Error(
+ `Invalid backup filename: resolved path "${backupPath}" is outside the configured backup directory "${resolvedBackupDir}". The configured backup directory may be invalid.`
+ );
mkdirSync(resolvedBackupDir, { recursive: true });
const stream = createWriteStream(backupPath, { encoding: "utf-8" });
@@ -55,8 +76,7 @@ export const backupsRouter = t.router({
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");
+ const stream = getStreamOrThrow(input.id, "write");
return new Promise<void>((resolve, reject) => {
stream.write(Buffer.from(input.chunk, "base64"), (err) =>
err ? reject(err) : resolve()
@@ -67,8 +87,7 @@ export const backupsRouter = t.router({
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");
+ const stream = getStreamOrThrow(input.id, "close");
return new Promise<void>((resolve) => {
stream.end(() => {
activeStreams.delete(input.id);
diff --git a/apps/desktop/src/api/os-integration.ts b/apps/desktop/src/api/os-integration.ts
index 73a3483e7..cd4b3065d 100644
--- a/apps/desktop/src/api/os-integration.ts
+++ b/apps/desktop/src/api/os-integration.ts
@@ -33,7 +33,7 @@ import { config, DesktopIntegration } from "../utils/config";
import { bringToFront } from "../utils/bring-to-front";
import { getTheme, setTheme, Theme } from "../utils/theme";
import { existsSync } from "fs";
-import { resolvePath } from "../utils/resolve-path";
+import { normalizePathString, resolvePath } from "../utils/resolve-path";
import { observable } from "@trpc/server/observable";
import { AssetManager } from "../utils/asset-manager";
import { isFlatpak, isPortable, isSnap } from "../utils";
@@ -60,7 +60,13 @@ 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),
+ backupDirectory: t.procedure.query(() => {
+ const backupDirectory = normalizePathString(config.backupDirectory);
+ if (backupDirectory !== config.backupDirectory) {
+ config.backupDirectory = backupDirectory;
+ }
+ return backupDirectory;
+ }),
zoomFactor: t.procedure.query(() => config.zoomFactor),
setZoomFactor: t.procedure.input(z.number()).mutation(({ input: factor }) => {
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 3ec4905ad..82d6ba858 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -40,6 +40,7 @@ import { disableCustomDns, enableCustomDns } from "./utils/custom-dns";
import { Messages, setI18nGlobal } from "@notesnook/intl";
import { i18n } from "@lingui/core";
import { PATHS } from "./constants";
+import { normalizePathString } from "./utils/resolve-path";
const locale =
process.env.NODE_ENV === "development"
@@ -294,7 +295,7 @@ async function migrateBackupDirectory() {
`localStorage.getItem("backupStorageLocation")`
);
if (!oldPath || oldPath === PATHS.backupsDirectory) return;
- config.backupDirectory = oldPath;
+ config.backupDirectory = normalizePathString(oldPath);
} catch (e) {
console.error("Failed to migrate backup directory", e);
const pressedButton = dialog.showMessageBoxSync(globalThis.window, {
diff --git a/apps/desktop/src/utils/resolve-path.ts b/apps/desktop/src/utils/resolve-path.ts
index 7df819112..bd4372c06 100644
--- a/apps/desktop/src/utils/resolve-path.ts
+++ b/apps/desktop/src/utils/resolve-path.ts
@@ -20,11 +20,30 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { app } from "electron";
import { isAbsolute, join } from "path";
+export function normalizePathString(_path: string) {
+ let normalizedPath = _path.trim();
+
+ try {
+ const parsedPath = JSON.parse(normalizedPath);
+ if (typeof parsedPath === "string") normalizedPath = parsedPath;
+ } catch {
+ // ignore invalid JSON and keep the original path string
+ }
+
+ if (normalizedPath === "~") return app.getPath("home");
+ if (/^~[\\/]/.test(normalizedPath)) {
+ return join(app.getPath("home"), normalizedPath.slice(2));
+ }
+
+ return normalizedPath;
+}
+
export function resolvePath(_path: string) {
- if (isAbsolute(_path)) return _path;
+ const normalizedPath = normalizePathString(_path);
+ if (isAbsolute(normalizedPath)) return normalizedPath;
return join(
- ..._path.split("/").map((segment) => {
+ ...normalizedPath.split("/").map((segment) => {
let resolved = segment;
try {
resolved = app.getPath(resolved as any);