Skip to content

Build your personal knowledge base with Trilium Notes

client/options/database: implement a delete button for anonymized databases

Adorian Doranee3bb9f1a9fa
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 4f18027b6d..1b7bd1a338 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -364,6 +364,11 @@ button.custom-title-bar-button {
border-color: var(--button-border-color);
}
+/* An action that takes something away, marked as such the way destructive menu items are. */
+.icon-action.destructive-action-icon {
+ color: var(--dropdown-item-icon-destructive-color);
+}
+
.icon-action.disabled {
color: var(--muted-text-color) !important;
cursor: not-allowed;
diff --git a/apps/client/src/stylesheets/theme-next/forms.css b/apps/client/src/stylesheets/theme-next/forms.css
index c9b2f4c5d4..b73b8109f9 100644
--- a/apps/client/src/stylesheets/theme-next/forms.css
+++ b/apps/client/src/stylesheets/theme-next/forms.css
@@ -146,6 +146,14 @@ button.tn-low-profile:hover {
margin-inline-start: 4px !important;
}
+/* An action that takes something away, marked as such the way destructive menu items are. Given as
+ the button's own colors rather than as a `color`, which the rules above and the hover one below
+ would both out-specify. */
+:root .icon-action.destructive-action-icon {
+ --icon-button-color: var(--dropdown-item-icon-destructive-color);
+ --icon-button-hover-color: var(--dropdown-item-icon-destructive-color);
+}
+
/* The "x" icon button */
:root .icon-action.bx-x,
:root .tn-tool-button.bx-x {
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index b321a00d9b..ed22249673 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1716,6 +1716,7 @@
"existing_anonymized_databases": "Existing anonymized databases",
"anonymized_databases_location": "Anonymized databases are stored in {{- anonymizedFolder}}.",
"download": "Download",
+ "delete_confirmation": "Delete the anonymized database {{fileName}}? The original database is not affected.",
"creating_fully_anonymized_database": "Creating fully anonymized database...",
"creating_lightly_anonymized_database": "Creating lightly anonymized database...",
"error_creating_anonymized_database": "Could not create anonymized database, check backend logs for details",
@@ -2131,6 +2132,7 @@
"encrypted": "Encrypted"
},
"database_file_list": {
+ "delete": "Delete",
"size_on_disk": "{{size}} on disk",
"invalid_backup": "Invalid backup file",
"unsupported_version": "Unsupported backup file format version"
diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
index 8013a5e2df..b25d455a79 100644
--- a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
@@ -4,6 +4,7 @@ import { ComponentChildren } from "preact";
import { useMemo } from "preact/hooks";
import { type DatabaseFile, describeDatabaseFile } from "../../../../services/database_files";
+import { t } from "../../../../services/i18n";
import open from "../../../../services/open";
import ActionButton from "../../../react/ActionButton";
import { Card, CardOption, CardSection } from "../../../react/Card";
@@ -21,6 +22,14 @@ interface DatabaseFileListProps<T extends DatabaseFile> {
/** Endpoint the per-file download links point to; the file path is appended as a query parameter. */
downloadEndpoint: string;
downloadText: string;
+ /**
+ * Offers to remove a file, beside the download of it. Left out where the files are not the
+ * user's to remove — the backups, which the schedule that made them also clears out.
+ *
+ * The caller confirms and deletes: only it knows what the file is, and the list is redrawn from
+ * whatever it fetches afterwards.
+ */
+ onDelete?: (file: T) => void;
emptyIcon: string;
emptyText: string;
/** Labels individual files, for the ones that need telling apart — e.g. one kept somewhere else. */
@@ -30,7 +39,7 @@ interface DatabaseFileListProps<T extends DatabaseFile> {
}
export default function DatabaseFileList<T extends DatabaseFile>(props: DatabaseFileListProps<T>) {
- const { title, description, files, downloadEndpoint, downloadText } = props;
+ const { title, description, files, downloadEndpoint, downloadText, onDelete } = props;
const { emptyIcon, emptyText, fileBadges, children } = props;
const sortedFiles = useMemo(() => [...files].sort((a, b) => {
@@ -59,6 +68,17 @@ export default function DatabaseFileList<T extends DatabaseFile>(props: Database
text={downloadText}
onClick={() => downloadFile(downloadEndpoint, file.filePath)}
/>
+
+ {/* Labelled from the shared catalogue rather than per list: removing a
+ file is the same act whichever list it is in. */}
+ {onDelete && (
+ <ActionButton
+ className="destructive-action-icon"
+ icon="bx bx-trash"
+ text={t("database_file_list.delete")}
+ onClick={() => onDelete(file)}
+ />
+ )}
</CardOption>
))
) : (
diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
index 66a246ace0..4045609f36 100644
--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
@@ -30,6 +30,13 @@ const failing = vi.hoisted(() => ({ info: false }));
/** What the backup page would list; emptied by the test about a database never backed up. */
let BACKUPS: { mtime: Date }[] = [];
+const ANONYMIZED_COPY = {
+ fileName: "anonymized-light-2026-01-02.db",
+ filePath: "/data/anonymized/anonymized-light-2026-01-02.db",
+ mtime: new Date("2026-01-02T10:00:00Z"),
+ fileSize: 4096
+};
+
// The info, maintenance and anonymization cards call the backend as they render and as they are used.
const server = vi.hoisted(() => ({
get: vi.fn(async (url: string) => {
@@ -44,17 +51,22 @@ const server = vi.hoisted(() => ({
case "database/check-integrity":
return { results: [{ integrity_check: "ok" }] };
case "database/anonymized-databases":
- return { databases: [], anonymizedFolderPath: "/data/anonymized" };
+ return { databases: [ ANONYMIZED_COPY ], anonymizedFolderPath: "/data/anonymized" };
// Whatever the page's own imports ask for while they load, e.g. keyboard actions.
default:
return [];
}
}),
post: vi.fn(async () => ({ success: true, anonymizedFilePath: "/data/anonymized/copy.db" })),
- postWithTimeout: vi.fn(async () => ({}))
+ postWithTimeout: vi.fn(async () => ({})),
+ remove: vi.fn(async () => ({}))
}));
vi.mock("../../../services/server", () => ({ default: server }));
+/** Deleting is asked about first; the answer is the test's to give. */
+const dialog = vi.hoisted(() => ({ confirm: vi.fn(async () => true) }));
+vi.mock("../../../services/dialog", () => ({ default: dialog }));
+
const toast = vi.hoisted(() => ({
showMessage: vi.fn(),
showError: vi.fn()
@@ -114,6 +126,8 @@ beforeEach(() => {
server.get.mockClear();
server.post.mockClear();
server.postWithTimeout.mockClear();
+ server.remove.mockClear();
+ dialog.confirm.mockReset().mockResolvedValue(true);
toast.showMessage.mockClear();
toast.showError.mockClear();
});
@@ -252,6 +266,30 @@ describe("anonymized copies", () => {
expect(server.get.mock.calls.filter(([url]) => url === "database/anonymized-databases")).toHaveLength(2);
});
+ it("throws a copy away once asked about, and lists what is left", async () => {
+ renderPage();
+ await settle();
+
+ container.querySelector<HTMLButtonElement>(".database-file-list button.bx-trash")?.click();
+ await settle();
+
+ expect(dialog.confirm).toHaveBeenCalled();
+ expect(server.remove).toHaveBeenCalledWith(
+ `database/anonymized?filePath=${encodeURIComponent(ANONYMIZED_COPY.filePath)}`);
+ expect(server.get.mock.calls.filter(([ url ]) => url === "database/anonymized-databases")).toHaveLength(2);
+ });
+
+ it("keeps the copy where the question was answered no", async () => {
+ dialog.confirm.mockResolvedValue(false);
+ renderPage();
+ await settle();
+
+ container.querySelector<HTMLButtonElement>(".database-file-list button.bx-trash")?.click();
+ await settle();
+
+ expect(server.remove).not.toHaveBeenCalled();
+ });
+
it("says so when the copy could not be made, and asks the list for nothing", async () => {
server.post.mockResolvedValueOnce({ success: false, anonymizedFilePath: "" });
renderPage();
diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsx
index 8cc06f5da9..12effb4fd0 100644
--- a/apps/client/src/widgets/type_widgets/options/database.tsx
+++ b/apps/client/src/widgets/type_widgets/options/database.tsx
@@ -11,6 +11,7 @@ import {
import { useCallback, useEffect, useState } from "preact/hooks";
import { summarizeBackups } from "../../../services/database_files";
+import dialogService from "../../../services/dialog";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import {
@@ -310,6 +311,20 @@ function AnonymizationOptions() {
}
}
+ /**
+ * A copy is made to be handed out, and is of no further use once it has been: it is the one
+ * thing on this page that can be thrown away without losing anything, and the only way to do so
+ * short of the file manager.
+ */
+ async function remove(file: AnonymizedDbResponse) {
+ if (!await dialogService.confirm(t("database_anonymization.delete_confirmation", { fileName: file.fileName }))) {
+ return;
+ }
+
+ await server.remove(`database/anonymized?filePath=${encodeURIComponent(file.filePath)}`);
+ refreshAnonymizedDatabases();
+ }
+
return (
<>
<div className="options-section database-anonymization">
@@ -357,6 +372,7 @@ function AnonymizationOptions() {
files={databases}
downloadEndpoint="api/database/anonymized/download"
downloadText={t("database_anonymization.download")}
+ onDelete={remove}
emptyIcon="bx bx-glasses"
emptyText={t("database_anonymization.no_anonymized_database_yet")}
/>
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
index a1a8987299..2568810ec4 100644
--- a/apps/server/src/routes/api/database.spec.ts
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -175,4 +175,27 @@ describe("Database API", () => {
}
});
});
+
+ describe("deleteAnonymizedDatabase", () => {
+ it("removes a copy, and takes a second attempt at a gone one for done", () => {
+ const filePath = path.join(dataDir.ANONYMIZED_DB_DIR, "anonymized-full-spec.db");
+ fs.mkdirSync(dataDir.ANONYMIZED_DB_DIR, { recursive: true });
+ fs.writeFileSync(filePath, "anonymized-bytes");
+
+ databaseRoute.deleteAnonymizedDatabase({ query: { filePath } } as unknown as Request);
+ expect(fs.existsSync(filePath)).toBe(false);
+
+ // The listing the path came from is a moment old by the time it is acted on, and what
+ // the caller asked for has happened either way.
+ expect(() => databaseRoute.deleteAnonymizedDatabase({ query: { filePath } } as unknown as Request))
+ .not.toThrow();
+ });
+
+ it("refuses a path outside the anonymized-db directory, backups included", () => {
+ for (const filePath of [ path.join(dataDir.BACKUP_DIR, "backup-now.db"), dataDir.DOCUMENT_PATH, "" ]) {
+ expect(() => databaseRoute.deleteAnonymizedDatabase({ query: { filePath } } as unknown as Request))
+ .toThrow(ValidationError);
+ }
+ });
+ });
});
diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.ts
index 178b471266..1a97eed1a6 100644
--- a/apps/server/src/routes/api/database.ts
+++ b/apps/server/src/routes/api/database.ts
@@ -118,6 +118,24 @@ async function anonymize(req: Request) {
return await anonymizationService.createAnonymizedCopy(req.params.type);
}
+/**
+ * Removes one anonymized copy, named by the path the listing gave out.
+ *
+ * Confined to the directory those copies are written to, exactly as the download of one is: the path
+ * arrives from the client, and what follows it is an unguarded file deletion. A file already gone is
+ * not an error — the listing is a moment old by the time it is acted on, and the caller asked for it
+ * to be absent, which it is.
+ */
+function deleteAnonymizedDatabase(req: Request) {
+ const filePath = resolveInsideDirectory(String(req.query.filePath ?? ""), dataDir.ANONYMIZED_DB_DIR);
+
+ if (!filePath) {
+ throw new ValidationError("Not an anonymized database.");
+ }
+
+ fs.rmSync(filePath, { force: true });
+}
+
function checkIntegrity() {
const results = sql.getRows<{ integrity_check: string }>("PRAGMA integrity_check");
@@ -146,11 +164,23 @@ export default {
rebuildIntegrationTestDatabase,
getExistingAnonymizedDatabases,
anonymize,
+ deleteAnonymizedDatabase,
checkIntegrity,
downloadBackup,
downloadAnonymizedDatabase
};
+/**
+ * The path resolved, or null where it does not land inside the directory it has to be in. Every
+ * route acting on a file the client named goes through here: the paths come from a listing this
+ * server gave out, but nothing about the request says so.
+ */
+function resolveInsideDirectory(filePath: string, allowedDir: string): string | null {
+ const resolvedPath = path.resolve(filePath);
+
+ return resolvedPath.startsWith(path.resolve(allowedDir) + path.sep) ? resolvedPath : null;
+}
+
function downloadDatabaseFile(req: Request, res: Response, allowedDir: string, notFoundMessage: string) {
const filePath = req.query.filePath as string;
if (!filePath) {
@@ -158,8 +188,8 @@ function downloadDatabaseFile(req: Request, res: Response, allowedDir: string, n
return;
}
- const resolvedPath = path.resolve(filePath);
- if (!resolvedPath.startsWith(path.resolve(allowedDir) + path.sep)) {
+ const resolvedPath = resolveInsideDirectory(filePath, allowedDir);
+ if (!resolvedPath) {
res.status(403).send("Access denied");
return;
}
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index a01f1ba7b5..7c999f22c3 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -147,6 +147,7 @@ function register(app: express.Application) {
asyncRoute(PST, "/api/database/anonymize/:type", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler);
apiRoute(GET, "/api/database/anonymized-databases", databaseRoute.getExistingAnonymizedDatabases);
route(GET, "/api/database/anonymized/download", [auth.checkApiAuthOrElectron], databaseRoute.downloadAnonymizedDatabase);
+ apiRoute(DEL, "/api/database/anonymized", databaseRoute.deleteAnonymizedDatabase);
if (process.env.TRILIUM_INTEGRATION_TEST === "memory") {
asyncRoute(PST, "/api/database/rebuild/", [auth.checkApiAuthOrElectron], databaseRoute.rebuildIntegrationTestDatabase, apiResultHandler);