Skip to content

Build your personal knowledge base with Trilium Notes

feat(options/advanced): improve layout of anonymized databases

Elian Doran99bef0883584
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 4f411b5177..9fd4a8fd24 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1267,6 +1267,8 @@
"choose_anonymization": "You can decide yourself if you want to provide a fully or lightly anonymized database. Even fully anonymized DB is very useful, however in some cases lightly anonymized database can speed up the process of bug identification and fixing.",
"save_lightly_anonymized_database": "Save lightly anonymized database",
"existing_anonymized_databases": "Existing anonymized databases",
+ "anonymized_databases_location": "Anonymized databases are stored in {{- anonymizedFolder}}.",
+ "download": "Download",
"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",
@@ -1355,8 +1357,6 @@
"disabled": "disabled"
},
"ribbon": {
- "widgets": "Ribbon widgets",
- "promoted_attributes_message": "Promoted Attributes ribbon tab will automatically open if promoted attributes are present on the note",
"edited_notes_message": "Edited Notes ribbon tab will automatically open on day notes"
},
"theme": {
diff --git a/apps/client/src/widgets/type_widgets/options/advanced.tsx b/apps/client/src/widgets/type_widgets/options/advanced.tsx
index 340c50d1ae..747ac22966 100644
--- a/apps/client/src/widgets/type_widgets/options/advanced.tsx
+++ b/apps/client/src/widgets/type_widgets/options/advanced.tsx
@@ -1,12 +1,13 @@
-import { AnonymizedDbResponse, DatabaseAnonymizeResponse, DatabaseCheckIntegrityResponse } from "@triliumnext/commons";
+import { AnonymizedDbResponse, DatabaseAnonymizeResponse, DatabaseCheckIntegrityResponse, ExistingAnonymizedDatabasesResponse } from "@triliumnext/commons";
import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
-import { getAvailableExperimentalFeatures, type ExperimentalFeatureId } from "../../../services/experimental_features";
+import { type ExperimentalFeatureId,getAvailableExperimentalFeatures } from "../../../services/experimental_features";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
import FormText from "../../react/FormText";
import { useTriliumOptionJson } from "../../react/hooks";
+import DatabaseFileList from "./components/DatabaseFileList";
import { OptionsRowWithButton, OptionsRowWithToggle } from "./components/OptionsRow";
import OptionsSection from "./components/OptionsSection";
@@ -87,75 +88,78 @@ function DatabaseOptions() {
}
function DatabaseAnonymizationOptions() {
- const [existingAnonymizedDatabases, setExistingAnonymizedDatabases] = useState<AnonymizedDbResponse[]>([]);
-
- function refreshAnonymizedDatabase() {
- server.get<AnonymizedDbResponse[]>("database/anonymized-databases").then(setExistingAnonymizedDatabases);
- }
-
- useEffect(refreshAnonymizedDatabase, []);
+ const [databases, setDatabases] = useState<AnonymizedDbResponse[]>([]);
+ const [anonymizedFolderPath, setAnonymizedFolderPath] = useState<string | null>(null);
+ const [anonymizationInProgress, setAnonymizationInProgress] = useState(false);
+
+ const refreshAnonymizedDatabases = useCallback(() => {
+ server.get<ExistingAnonymizedDatabasesResponse>("database/anonymized-databases").then((response) => {
+ setDatabases(response.databases);
+ setAnonymizedFolderPath(response.anonymizedFolderPath);
+ });
+ }, []);
+
+ useEffect(refreshAnonymizedDatabases, []);
+
+ const anonymize = async (type: "full" | "light") => {
+ setAnonymizationInProgress(true);
+ try {
+ toast.showMessage(type === "full"
+ ? t("database_anonymization.creating_fully_anonymized_database")
+ : t("database_anonymization.creating_lightly_anonymized_database"));
+ const resp = await server.post<DatabaseAnonymizeResponse>(`database/anonymize/${type}`);
+
+ if (!resp.success) {
+ toast.showError(t("database_anonymization.error_creating_anonymized_database"));
+ } else {
+ toast.showMessage(type === "full"
+ ? t("database_anonymization.successfully_created_fully_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath })
+ : t("database_anonymization.successfully_created_lightly_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);
+ refreshAnonymizedDatabases();
+ }
+ } finally {
+ setAnonymizationInProgress(false);
+ }
+ };
return (
- <OptionsSection title={t("database_anonymization.title")}>
- <FormText>{t("database_anonymization.description")}</FormText>
-
- <OptionsRowWithButton
- label={t("database_anonymization.full_anonymization")}
- description={t("database_anonymization.full_anonymization_description")}
- onClick={async () => {
- toast.showMessage(t("database_anonymization.creating_fully_anonymized_database"));
- const resp = await server.post<DatabaseAnonymizeResponse>("database/anonymize/full");
-
- if (!resp.success) {
- toast.showError(t("database_anonymization.error_creating_anonymized_database"));
- } else {
- toast.showMessage(t("database_anonymization.successfully_created_fully_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);
- refreshAnonymizedDatabase();
- }
- }}
- />
-
- <OptionsRowWithButton
- label={t("database_anonymization.light_anonymization")}
- description={t("database_anonymization.light_anonymization_description")}
- onClick={async () => {
- toast.showMessage(t("database_anonymization.creating_lightly_anonymized_database"));
- const resp = await server.post<DatabaseAnonymizeResponse>("database/anonymize/light");
-
- if (!resp.success) {
- toast.showError(t("database_anonymization.error_creating_anonymized_database"));
- } else {
- toast.showMessage(t("database_anonymization.successfully_created_lightly_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);
- refreshAnonymizedDatabase();
- }
- }}
- />
+ <>
+ <OptionsSection
+ title={t("database_anonymization.title")}
+ description={t("database_anonymization.description")}
+ >
+ <OptionsRowWithButton
+ label={t("database_anonymization.full_anonymization")}
+ description={t("database_anonymization.full_anonymization_description")}
+ disabled={anonymizationInProgress}
+ onClick={() => anonymize("full")}
+ />
- <hr />
+ <OptionsRowWithButton
+ label={t("database_anonymization.light_anonymization")}
+ description={t("database_anonymization.light_anonymization_description")}
+ disabled={anonymizationInProgress}
+ onClick={() => anonymize("light")}
+ />
+ </OptionsSection>
- <ExistingAnonymizedDatabases databases={existingAnonymizedDatabases} />
- </OptionsSection>
+ <ExistingAnonymizedDatabases databases={databases} anonymizedFolderPath={anonymizedFolderPath} />
+ </>
);
}
-function ExistingAnonymizedDatabases({ databases }: { databases: AnonymizedDbResponse[] }) {
- if (!databases.length) {
- return <FormText>{t("database_anonymization.no_anonymized_database_yet")}</FormText>;
- }
-
+function ExistingAnonymizedDatabases({ databases, anonymizedFolderPath }: { databases: AnonymizedDbResponse[]; anonymizedFolderPath: string | null }) {
return (
- <table className="table table-stripped">
- <thead>
- <th>{t("database_anonymization.existing_anonymized_databases")}</th>
- </thead>
- <tbody>
- {databases.map(({ filePath }) => (
- <tr>
- <td>{filePath}</td>
- </tr>
- ))}
- </tbody>
- </table>
+ <DatabaseFileList
+ title={t("database_anonymization.existing_anonymized_databases")}
+ locationDescription={anonymizedFolderPath && t("database_anonymization.anonymized_databases_location", { anonymizedFolder: anonymizedFolderPath })}
+ files={databases}
+ downloadEndpoint="api/database/anonymized/download"
+ rowName="anonymized-database"
+ downloadText={t("database_anonymization.download")}
+ emptyIcon="bx bx-glasses"
+ emptyText={t("database_anonymization.no_anonymized_database_yet")}
+ />
);
}
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index 4d62a9b3a0..9f1aa017c2 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -4,12 +4,9 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
-import { formatSize } from "../../../services/utils";
-import { formatDateTime } from "../../../utils/formatters";
-import ActionButton from "../../react/ActionButton";
import Button from "../../react/Button";
import { useTriliumOptionBool } from "../../react/hooks";
-import NoItems from "../../react/NoItems";
+import DatabaseFileList from "./components/DatabaseFileList";
import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";
import OptionsSection from "./components/OptionsSection";
@@ -19,14 +16,7 @@ export default function BackupSettings() {
const refreshBackups = useCallback(() => {
server.get<ExistingBackupsResponse>("database/backups").then((response) => {
- // Sort the backup files by modification date & time in a desceding order
- const backupFiles = [...response.backups].sort((a, b) => {
- if (a.mtime < b.mtime) return 1;
- if (a.mtime > b.mtime) return -1;
- return 0;
- });
-
- setBackups(backupFiles);
+ setBackups(response.backups);
setBackupFolderPath(response.backupFolderPath);
});
}, []);
@@ -79,29 +69,16 @@ export function BackupList({ backups, backupFolderPath, refreshCallback }: { bac
const [backupInProgress, setBackupInProgress] = useState(false);
return (
- <OptionsSection
+ <DatabaseFileList
title={t("backup.existing_backups")}
- description={backupFolderPath && (
- <span className="selectable-text">{t("backup.backup_location_description", { backupFolder: backupFolderPath })}</span>
- )}
+ locationDescription={backupFolderPath && t("backup.backup_location_description", { backupFolder: backupFolderPath })}
+ files={backups}
+ downloadEndpoint="api/database/backup/download"
+ rowName="existing-backup"
+ downloadText={t("backup.download")}
+ emptyIcon="bx bx-archive"
+ emptyText={t("backup.no_backup_yet")}
>
- {backups.length > 0 ? (
- backups.map(({ fileName, filePath, mtime, fileSize }) => (
- <OptionsRow
- key={filePath}
- name="existing-backup"
- label={<span className="selectable-text">{fileName}</span>}
- description={`${mtime ? formatDateTime(mtime) : "-"} • ${formatSize(fileSize)}`}
- >
- <a href={`api/database/backup/download?filePath=${encodeURIComponent(filePath)}`} download>
- <ActionButton icon="bx bx-download" text={t("backup.download")} />
- </a>
- </OptionsRow>
- ))
- ) : (
- <NoItems icon="bx bx-archive" text={t("backup.no_backup_yet")} />
- )}
-
<OptionsRow name="backup-now" centered>
<Button
name="backup-database-now-button"
@@ -120,6 +97,6 @@ export function BackupList({ backups, backupFolderPath, refreshCallback }: { bac
}}
/>
</OptionsRow>
- </OptionsSection>
+ </DatabaseFileList>
);
}
diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
new file mode 100644
index 0000000000..8dee1f3335
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
@@ -0,0 +1,69 @@
+import { ComponentChildren } from "preact";
+import { useMemo } from "preact/hooks";
+
+import { formatSize } from "../../../../services/utils";
+import { formatDateTime } from "../../../../utils/formatters";
+import ActionButton from "../../../react/ActionButton";
+import NoItems from "../../../react/NoItems";
+import OptionsRow from "./OptionsRow";
+import OptionsSection from "./OptionsSection";
+
+export interface DatabaseFile {
+ fileName: string;
+ filePath: string;
+ mtime: Date;
+ /** Size of the file, in bytes. */
+ fileSize: number;
+}
+
+interface DatabaseFileListProps {
+ title: string;
+ /** Sentence describing where the files are stored; omitted when there is no user-accessible location. */
+ locationDescription?: string | null;
+ /** Displayed sorted by modification date & time in a descending order. */
+ files: DatabaseFile[];
+ /** Endpoint the per-file download links point to; the file path is appended as a query parameter. */
+ downloadEndpoint: string;
+ rowName: string;
+ downloadText: string;
+ emptyIcon: string;
+ emptyText: string;
+ /** Extra content rendered below the list (e.g. an action button). */
+ children?: ComponentChildren;
+}
+
+export default function DatabaseFileList({ title, locationDescription, files, downloadEndpoint, rowName, downloadText, emptyIcon, emptyText, children }: DatabaseFileListProps) {
+ const sortedFiles = useMemo(() => [...files].sort((a, b) => {
+ if (a.mtime < b.mtime) return 1;
+ if (a.mtime > b.mtime) return -1;
+ return 0;
+ }), [files]);
+
+ return (
+ <OptionsSection
+ title={title}
+ description={locationDescription && (
+ <span className="selectable-text">{locationDescription}</span>
+ )}
+ >
+ {sortedFiles.length > 0 ? (
+ sortedFiles.map(({ fileName, filePath, mtime, fileSize }) => (
+ <OptionsRow
+ key={filePath}
+ name={rowName}
+ label={<span className="selectable-text">{fileName}</span>}
+ description={`${mtime ? formatDateTime(mtime) : "-"} • ${formatSize(fileSize)}`}
+ >
+ <a href={`${downloadEndpoint}?filePath=${encodeURIComponent(filePath)}`} download>
+ <ActionButton icon="bx bx-download" text={downloadText} />
+ </a>
+ </OptionsRow>
+ ))
+ ) : (
+ <NoItems icon={emptyIcon} text={emptyText} />
+ )}
+
+ {children}
+ </OptionsSection>
+ );
+}
diff --git a/apps/server/internal.openapi.yaml b/apps/server/internal.openapi.yaml
index feab3ae015..68650f4605 100644
--- a/apps/server/internal.openapi.yaml
+++ b/apps/server/internal.openapi.yaml
@@ -2832,10 +2832,54 @@ paths:
content:
application/json:
schema:
- type: array
- items:
- type: string
-
+ type: object
+ properties:
+ anonymizedFolderPath:
+ type: string
+ description: Directory where the anonymized databases are stored.
+ databases:
+ type: array
+ items:
+ type: object
+ properties:
+ fileName:
+ type: string
+ filePath:
+ type: string
+ mtime:
+ type: string
+ format: date-time
+ fileSize:
+ type: integer
+ description: Size of the anonymized database file, in bytes.
+
+ /api/database/anonymized/download:
+ get:
+ tags: [Database]
+ summary: Download an anonymized database file
+ operationId: downloadAnonymizedDatabase
+ parameters:
+ - name: filePath
+ in: query
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Anonymized database file
+ content:
+ application/x-sqlite3:
+ schema:
+ type: string
+ format: binary
+ '400':
+ description: Missing filePath
+ '403':
+ description: Path outside the anonymized database directory
+ '404':
+ description: File not found
+
+
/api/database/find-and-fix-consistency-issues:
post:
tags: [Database]
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
index 1233359ee6..53d145f903 100644
--- a/apps/server/src/routes/api/database.spec.ts
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -21,7 +21,10 @@ function fakeRes() {
describe("Database API", () => {
it("returns existing backups and anonymized databases", async () => {
expect(Array.isArray(await databaseRoute.getExistingBackups())).toBe(true);
- expect(Array.isArray(databaseRoute.getExistingAnonymizedDatabases())).toBe(true);
+
+ const { anonymizedFolderPath, databases } = databaseRoute.getExistingAnonymizedDatabases();
+ expect(anonymizedFolderPath).toBe(path.resolve(dataDir.ANONYMIZED_DB_DIR));
+ expect(Array.isArray(databases)).toBe(true);
});
it("runs an integrity check that reports 'ok'", () => {
@@ -94,4 +97,29 @@ describe("Database API", () => {
}
});
});
+
+ describe("downloadAnonymizedDatabase", () => {
+ it("is restricted to the anonymized-db directory", () => {
+ // A backup file path is valid for downloadBackup but must be rejected here.
+ const { res, calls } = fakeRes();
+ const filePath = path.join(dataDir.BACKUP_DIR, "backup-now.db");
+ databaseRoute.downloadAnonymizedDatabase({ query: { filePath } } as unknown as Request, res);
+ expect(calls.status).toBe(403);
+ });
+
+ it("streams an existing anonymized database via res.download", () => {
+ const filePath = path.join(dataDir.ANONYMIZED_DB_DIR, "anonymized-light-spec.db");
+ fs.mkdirSync(dataDir.ANONYMIZED_DB_DIR, { recursive: true });
+ fs.writeFileSync(filePath, "anonymized-bytes");
+ try {
+ const { res, calls } = fakeRes();
+ databaseRoute.downloadAnonymizedDatabase({ query: { filePath } } as unknown as Request, res);
+ const downloadArgs = calls.download ?? [];
+ expect(downloadArgs[0]).toBe(path.resolve(filePath));
+ expect(String(downloadArgs[1])).toMatch(/anonymized-light-spec_.*\.db/);
+ } finally {
+ fs.rmSync(filePath, { force: true });
+ }
+ });
+ });
});
diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.ts
index 9bfe261d03..97968976b9 100644
--- a/apps/server/src/routes/api/database.ts
+++ b/apps/server/src/routes/api/database.ts
@@ -1,12 +1,11 @@
-import { BackupDatabaseNowResponse, DatabaseCheckIntegrityResponse } from "@triliumnext/commons";
-import { becca_loader, consistency_checks as consistencyChecksService, getBackup, ValidationError } from "@triliumnext/core";
+import { BackupDatabaseNowResponse, DatabaseCheckIntegrityResponse, ExistingAnonymizedDatabasesResponse } from "@triliumnext/commons";
+import { becca_loader, consistency_checks as consistencyChecksService, getBackup, getLog, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs, { readFileSync } from "fs";
import path from "path";
import anonymizationService from "../../services/anonymization.js";
import dataDir from "../../services/data_dir.js";
-import { getLog } from "@triliumnext/core";
import sql from "../../services/sql.js";
import sql_init from "../../services/sql_init.js";
@@ -38,7 +37,10 @@ async function rebuildIntegrationTestDatabase() {
}
function getExistingAnonymizedDatabases() {
- return anonymizationService.getExistingAnonymizedDatabases();
+ return {
+ anonymizedFolderPath: path.resolve(dataDir.ANONYMIZED_DB_DIR),
+ databases: anonymizationService.getExistingAnonymizedDatabases()
+ } satisfies ExistingAnonymizedDatabasesResponse;
}
async function anonymize(req: Request) {
@@ -59,6 +61,27 @@ function checkIntegrity() {
}
function downloadBackup(req: Request, res: Response) {
+ downloadDatabaseFile(req, res, dataDir.BACKUP_DIR, "Backup file not found");
+}
+
+function downloadAnonymizedDatabase(req: Request, res: Response) {
+ downloadDatabaseFile(req, res, dataDir.ANONYMIZED_DB_DIR, "Anonymized database file not found");
+}
+
+export default {
+ getExistingBackups,
+ backupDatabase,
+ vacuumDatabase,
+ findAndFixConsistencyIssues,
+ rebuildIntegrationTestDatabase,
+ getExistingAnonymizedDatabases,
+ anonymize,
+ checkIntegrity,
+ downloadBackup,
+ downloadAnonymizedDatabase
+};
+
+function downloadDatabaseFile(req: Request, res: Response, allowedDir: string, notFoundMessage: string) {
const filePath = req.query.filePath as string;
if (!filePath) {
res.status(400).send("Missing filePath");
@@ -66,13 +89,13 @@ function downloadBackup(req: Request, res: Response) {
}
const resolvedPath = path.resolve(filePath);
- if (!resolvedPath.startsWith(path.resolve(dataDir.BACKUP_DIR) + path.sep)) {
+ if (!resolvedPath.startsWith(path.resolve(allowedDir) + path.sep)) {
res.status(403).send("Access denied");
return;
}
if (!fs.existsSync(resolvedPath)) {
- res.status(404).send("Backup file not found");
+ res.status(404).send(notFoundMessage);
return;
}
@@ -84,15 +107,3 @@ function downloadBackup(req: Request, res: Response) {
const baseName = path.basename(resolvedPath, ext);
res.download(resolvedPath, `${baseName}_${dateStr}${ext}`);
}
-
-export default {
- getExistingBackups,
- backupDatabase,
- vacuumDatabase,
- findAndFixConsistencyIssues,
- rebuildIntegrationTestDatabase,
- getExistingAnonymizedDatabases,
- anonymize,
- checkIntegrity,
- downloadBackup
-};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index ecad96bf53..1241057fac 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -152,6 +152,7 @@ function register(app: express.Application) {
apiRoute(PST, "/api/special-notes/save-llm-chat", llmSpecialNotesRoute.saveLlmChat);
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);
if (process.env.TRILIUM_INTEGRATION_TEST === "memory") {
asyncRoute(PST, "/api/database/rebuild/", [auth.checkApiAuthOrElectron], databaseRoute.rebuildIntegrationTestDatabase, apiResultHandler);
diff --git a/apps/server/src/services/anonymization.spec.ts b/apps/server/src/services/anonymization.spec.ts
index 47c80d6013..148232f1bf 100644
--- a/apps/server/src/services/anonymization.spec.ts
+++ b/apps/server/src/services/anonymization.spec.ts
@@ -7,7 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mockFs = {
existsSync: vi.fn(),
mkdirSync: vi.fn(),
- readdirSync: vi.fn()
+ readdirSync: vi.fn(),
+ statSync: vi.fn()
};
vi.mock("fs", () => ({ default: mockFs, ...mockFs }));
@@ -124,12 +125,16 @@ describe("getExistingAnonymizedDatabases", () => {
expect(mockFs.readdirSync).not.toHaveBeenCalled();
});
- it("lists only files whose name includes 'anonymized'", () => {
+ it("lists only anonymized .db files, with their modification date and size", () => {
+ const mtime = new Date("2025-01-01T00:00:00Z");
mockFs.existsSync.mockReturnValue(true);
+ mockFs.statSync.mockReturnValue({ mtime, size: 42 });
mockFs.readdirSync.mockReturnValue([
"anonymized-full-x.db",
"document.db",
"anonymized-light-y.db",
+ // intermediate SQLite file of an in-progress anonymization must be excluded
+ "anonymized-full-z.db-journal",
"backup.zip"
]);
@@ -143,6 +148,8 @@ describe("getExistingAnonymizedDatabases", () => {
// filePath must be the fully-resolved path under the anonymized-db dir,
// not merely a string that happens to contain the file name.
expect(entry.filePath).toBe(path.resolve(dataDir.ANONYMIZED_DB_DIR, entry.fileName));
+ expect(entry.mtime).toBe(mtime);
+ expect(entry.fileSize).toBe(42);
}
});
});
diff --git a/apps/server/src/services/anonymization.ts b/apps/server/src/services/anonymization.ts
index 172e2b1b8f..0c7d2f21ad 100644
--- a/apps/server/src/services/anonymization.ts
+++ b/apps/server/src/services/anonymization.ts
@@ -84,11 +84,14 @@ function getExistingAnonymizedDatabases() {
return fs
.readdirSync(dataDir.ANONYMIZED_DB_DIR)
- .filter((fileName) => fileName.includes("anonymized"))
- .map((fileName) => ({
- fileName,
- filePath: path.resolve(dataDir.ANONYMIZED_DB_DIR, fileName)
- })) satisfies AnonymizedDbResponse[];
+ // The .db check excludes intermediate SQLite files (e.g. *.db-journal) created while an anonymization is in progress.
+ .filter((fileName) => fileName.includes("anonymized") && fileName.endsWith(".db"))
+ .map((fileName) => {
+ const filePath = path.resolve(dataDir.ANONYMIZED_DB_DIR, fileName);
+ const stat = fs.statSync(filePath);
+
+ return { fileName, filePath, mtime: stat.mtime, fileSize: stat.size };
+ }) satisfies AnonymizedDbResponse[];
}
export default {
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 504e3b1323..e41d5e3e04 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -89,6 +89,15 @@ export interface DatabaseAnonymizeResponse {
export interface AnonymizedDbResponse {
filePath: string;
fileName: string;
+ mtime: Date;
+ /** Size of the anonymized database file, in bytes. */
+ fileSize: number;
+}
+
+export interface ExistingAnonymizedDatabasesResponse {
+ /** The directory where the anonymized databases are stored. */
+ anonymizedFolderPath: string;
+ databases: AnonymizedDbResponse[];
}
export type SyncTestResponse = Response;