Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(desktop): native large-zip import via a capability token
Elian Doranfe3e15ccc1bf
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c07af30ef1..28d2b222d9 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -218,6 +218,8 @@"cardDescription": "ZIP, ENEX, OPML, Markdown, HTML, images and more","chooseImportFile": "Choose import file","importZipRecommendation": "When importing a ZIP file, the note hierarchy will reflect the subdirectory structure within the archive.",+ "largeZipHint": "Importing a large ZIP? Choose it directly for best performance:",+ "largeZipButton": "Choose .zip…","options": "Options","safeImportTooltip": "Trilium <code>.zip</code> exports can contain executable scripts. Safe import disables them; uncheck only if the archive is meant to run scripts and you trust its contents.","safeImport": "Safe import",diff --git a/apps/client/src/widgets/dialogs/import/files.tsx b/apps/client/src/widgets/dialogs/import/files.tsxindex ad275d9c4b..abe15ae3f7 100644--- a/apps/client/src/widgets/dialogs/import/files.tsx+++ b/apps/client/src/widgets/dialogs/import/files.tsx@@ -1,7 +1,9 @@+import type { NativeImportOptions } from "@triliumnext/commons";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";import importService, { type UploadFilesOptions } from "../../../services/import.js";+import utils from "../../../services/utils.js";import Button from "../../react/Button.js";import { Card, CardSection } from "../../react/Card.js";import FileDropZone from "../../react/FileDropZone.js";@@ -44,6 +46,27 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPaneawait importService.uploadFiles("notes", parentNoteId, Array.from(files), options).catch(() => {});}, [files, safeImport, shrinkImages, textImportedAsText, codeImportedAsCode, spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces, parentNoteId, closeDialog]);+ // Desktop only: import a large .zip straight from disk. The OS dialog (in the main process) is the+ // sole source of the path — it returns a single-use capability token, never a path — and the archive+ // is read in place, so a multi-GB import stays memory-bounded (no upload, no temp copy). Other files+ // and drag-drop keep the normal upload route above.+ const doNativeZipImport = useCallback(async () => {+ const pick = await window.electronApi?.nativeImport.pickZipFile();+ if (pick?.status !== "selected" || !pick.token) {+ return;+ }++ const options: NativeImportOptions = {+ safeImport, shrinkImages, textImportedAsText, codeImportedAsCode,+ spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces+ };++ // Close immediately and let the shared import toasts (registered in import.ts) report progress,+ // completion and any error over the WebSocket, exactly like the upload route.+ closeDialog();+ await window.electronApi?.nativeImport.importFromToken({ token: pick.token, parentNoteId, taskId: utils.randomString(10), options });+ }, [safeImport, shrinkImages, textImportedAsText, codeImportedAsCode, spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces, parentNoteId, closeDialog]);+// Keep the latest import handler in a ref so the footer effect depends only on whether files are// selected, never on doImport's identity — otherwise re-pushing the footer on every option toggle// would loop with the parent re-rendering us back (see the other panels for the same reasoning).@@ -62,6 +85,12 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPane<CardSection><p className="import-files-description">{t("import.importZipRecommendation")}</p><FileDropZone multiple onChange={setFiles} />+ {utils.isElectron() && (+ <div className="import-native-zip">+ <span className="import-native-zip-hint">{t("import.largeZipHint")}</span>+ <Button text={t("import.largeZipButton")} onClick={() => void doNativeZipImport()} />+ </div>+ )}</CardSection></Card>diff --git a/apps/client/src/widgets/dialogs/import/import_dialog.css b/apps/client/src/widgets/dialogs/import/import_dialog.cssindex 3ffbdf50d6..f69aeade7d 100644--- a/apps/client/src/widgets/dialogs/import/import_dialog.css+++ b/apps/client/src/widgets/dialogs/import/import_dialog.css@@ -23,6 +23,22 @@color: var(--muted-text-color);}+ /* Desktop-only fast path for large .zip imports, shown beneath the drop zone. */+ .import-native-zip {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1em;+ margin-top: 0.75em;+ padding-top: 0.75em;+ border-top: 1px solid var(--main-border-color);+ }++ .import-native-zip-hint {+ color: var(--muted-text-color);+ font-size: 0.9em;+ }+/* Collapsed-by-default options: the section header toggles the option rows below. */.import-options-toggle {display: flex;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex e48f9359b8..37e990b6fe 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -28,6 +28,7 @@ import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";import { applyLaunchOnStartup, setupAutoLaunch, wasLaunchedHidden } from "./services/auto_launch";import { setupCustomDictionary } from "./services/custom_dictionary";import { setupExportHandlers } from "./services/export";+import { setupImportHandlers } from "./services/import";import { setupOneNoteHandlers } from "./services/onenote";import { setupPrintingHandlers } from "./services/printing";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";@@ -130,6 +131,7 @@ export async function main() {setupOneNoteHandlers();setupPrintingHandlers();setupExportHandlers();+ setupImportHandlers();registerSecurityIpcHandlers();setupStartupMetricsIpc();diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex a6f05b1d14..0680de930f 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -623,4 +623,19 @@ describe("preload script", () => {expect(ipcRendererInvoked).toContainEqual({ channel: "export-subtree-to-file", args: [opts] });});});++ describe("nativeImport", () => {+ const nativeImport = () => getGroup("nativeImport");++ it("pickZipFile invokes the open-dialog IPC channel with no path argument", async () => {+ await nativeImport().pickZipFile();+ expect(ipcRendererInvoked).toContainEqual({ channel: "import-pick-zip", args: [] });+ });++ it("importFromToken forwards the token + options (never a path) to its IPC channel", async () => {+ const opts = { token: "tok-1", parentNoteId: "p1", taskId: "task1", options: { explodeArchives: true } };+ await nativeImport().importFromToken(opts);+ expect(ipcRendererInvoked).toContainEqual({ channel: "import-from-token", args: [opts] });+ });+ });});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 02c3238f6a..a8a4087def 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,4 +1,4 @@-import type { ElectronApi, ElectronContextMenuParams, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";+import type { ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";import { contextBridge, ipcRenderer, webFrame } from "electron";contextBridge.exposeInMainWorld("electronApi", {@@ -210,6 +210,15 @@ contextBridge.exposeInMainWorld("electronApi", {}},+ nativeImport: {+ pickZipFile() {+ return ipcRenderer.invoke("import-pick-zip");+ },+ importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions }) {+ return ipcRenderer.invoke("import-from-token", opts);+ }+ },+ws: {// Renderer → main process. Mirror channel name with the server-side// IpcMessagingProvider constants.diff --git a/apps/desktop/src/services/import.spec.ts b/apps/desktop/src/services/import.spec.tsnew file mode 100644index 0000000000..006484aa10--- /dev/null+++ b/apps/desktop/src/services/import.spec.ts@@ -0,0 +1,134 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// --- electron mock: capture the IPC handlers and drive the dialog/window from the test ---+const electronMock = vi.hoisted(() => ({+ handlers: new Map<string, (...args: unknown[]) => unknown>(),+ handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => electronMock.handlers.set(channel, handler)),+ showOpenDialogSync: vi.fn<(...args: unknown[]) => string[] | undefined>(),+ getFocusedWindow: vi.fn<() => object | null>(() => ({}))+}));++vi.mock("electron", () => ({+ default: {+ ipcMain: { handle: electronMock.handle },+ dialog: { showOpenDialogSync: electronMock.showOpenDialogSync },+ BrowserWindow: { getFocusedWindow: electronMock.getFocusedWindow }+ }+}));++vi.mock("i18next", () => ({ t: (key: string) => key }));++// --- core mock: stub the import pipeline so we can assert what the handler calls ---+const coreMock = vi.hoisted(() => ({+ importZip: vi.fn<(...args: unknown[]) => Promise<{ noteId: string }>>(),+ getNoteOrThrow: vi.fn((id: string) => ({ noteId: id })),+ taskSucceeded: vi.fn(),+ reportError: vi.fn(),+ load: vi.fn(),+ tokenCounter: 0+}));++vi.mock("@triliumnext/core", () => ({+ becca: { getNoteOrThrow: coreMock.getNoteOrThrow },+ becca_loader: { load: coreMock.load },+ cls: {+ init: (cb: () => unknown) => cb(),+ disableEntityEvents: vi.fn(),+ ignoreEntityChangeIds: vi.fn()+ },+ getLog: () => ({ error: vi.fn() }),+ TaskContext: { getInstance: () => ({ taskSucceeded: coreMock.taskSucceeded, reportError: coreMock.reportError }) },+ utils: {+ randomString: () => `tok-${coreMock.tokenCounter++}`,+ safeExtractMessageAndStackFromError: (e: unknown) => String(e)+ },+ zipImportService: { importZip: coreMock.importZip }+}));++const { setupImportHandlers } = await import("./import.js");++const OPTIONS = {+ safeImport: true, shrinkImages: false, textImportedAsText: true, codeImportedAsCode: true,+ spreadsheetImportedAsSpreadsheet: true, explodeArchives: true, replaceUnderscoresWithSpaces: true+};++function pick() {+ return electronMock.handlers.get("import-pick-zip")?.() as Promise<{ status: string; token?: string; fileName?: string }>;+}+function importFromToken(opts: object) {+ return electronMock.handlers.get("import-from-token")?.({}, opts) as Promise<{ status: string; importedNoteId?: string; message?: string }>;+}++describe("desktop native import — capability token", () => {+ beforeEach(() => {+ electronMock.handlers.clear();+ vi.clearAllMocks();+ coreMock.tokenCounter = 0;+ coreMock.importZip.mockResolvedValue({ noteId: "imported1" });+ electronMock.getFocusedWindow.mockReturnValue({});+ setupImportHandlers();+ });++ it("pick-zip returns a token + filename (never a path) for the user-chosen file", async () => {+ electronMock.showOpenDialogSync.mockReturnValue(["C:/Users/me/big vault.zip"]);++ const result = await pick();++ expect(result.status).toBe("selected");+ expect(result.token).toBeTruthy();+ expect(result.fileName).toBe("big vault.zip");+ // The renderer is handed a token, not the absolute path.+ expect(JSON.stringify(result)).not.toContain("C:/Users/me");+ });++ it("a cancelled dialog mints no token and imports nothing", async () => {+ electronMock.showOpenDialogSync.mockReturnValue(undefined);++ expect(await pick()).toEqual({ status: "cancelled" });+ expect(coreMock.importZip).not.toHaveBeenCalled();+ });++ it("imports the granted file in place (importZip receives { path }, not bytes)", async () => {+ electronMock.showOpenDialogSync.mockReturnValue(["/data/big.zip"]);+ const { token } = await pick();++ const result = await importFromToken({ token, parentNoteId: "parent1", taskId: "task1", options: OPTIONS });++ expect(result).toEqual({ status: "imported", importedNoteId: "imported1" });+ expect(coreMock.getNoteOrThrow).toHaveBeenCalledWith("parent1");+ const [, source, parentNote] = coreMock.importZip.mock.calls[0];+ expect(source).toEqual({ path: "/data/big.zip" });+ expect(parentNote).toEqual({ noteId: "parent1" });+ expect(coreMock.load).toHaveBeenCalled();+ });++ it("rejects an unknown/forged token without importing (a script can't supply a path or guess a token)", async () => {+ const result = await importFromToken({ token: "forged-token", parentNoteId: "parent1", taskId: "t", options: OPTIONS });++ expect(result.status).toBe("error");+ expect(coreMock.importZip).not.toHaveBeenCalled();+ });++ it("consumes the token: the same token cannot be redeemed twice (no replay)", async () => {+ electronMock.showOpenDialogSync.mockReturnValue(["/data/once.zip"]);+ const { token } = await pick();++ const first = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS });+ const second = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS });++ expect(first.status).toBe("imported");+ expect(second.status).toBe("error");+ expect(coreMock.importZip).toHaveBeenCalledTimes(1);+ });++ it("reports a failed import as an error and surfaces it on the task channel", async () => {+ electronMock.showOpenDialogSync.mockReturnValue(["/data/bad.zip"]);+ coreMock.importZip.mockRejectedValue(new Error("corrupt archive"));+ const { token } = await pick();++ const result = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS });++ expect(result).toEqual({ status: "error", message: "corrupt archive" });+ expect(coreMock.reportError).toHaveBeenCalledWith("corrupt archive");+ });+});diff --git a/apps/desktop/src/services/import.ts b/apps/desktop/src/services/import.tsnew file mode 100644index 0000000000..d7c6e077d3--- /dev/null+++ b/apps/desktop/src/services/import.ts@@ -0,0 +1,101 @@+import type { NativeImportOptions, NativeImportPickResult, NativeImportResult } from "@triliumnext/commons";+import { becca, becca_loader, cls, getLog, TaskContext, utils as coreUtils, zipImportService } from "@triliumnext/core";+import { default as electron } from "electron";+import { basename } from "path";+import { t } from "i18next";++interface ImportFromTokenOpts {+ token: string;+ parentNoteId: string;+ taskId: string;+ options: NativeImportOptions;+}++/**+ * Registers the desktop-native large-`.zip` import IPC handlers.+ *+ * Security model: the renderer **never** supplies a path. The OS dialog runs here in the main process and+ * is the *only* thing that mints an access grant; `import-pick-zip` returns a single-use, short-lived+ * **token** (plus the display filename), and `import-from-token` accepts that token — not a path. So a+ * note script can at most pop the dialog (the user still has to pick a file) and can never read an+ * arbitrary file: it can't forge a valid token, and there's no path parameter to abuse.+ *+ * The chosen file is read **in place** (`zipImportService.importZip({ path })`, streamed per entry), so a+ * multi-GB archive is never copied to a temp file or held in memory — the reason this path exists.+ */+export function setupImportHandlers() {+ electron.ipcMain.handle("import-pick-zip", async (): Promise<NativeImportPickResult> => {+ const focusedWindow = electron.BrowserWindow.getFocusedWindow();+ if (!focusedWindow) {+ return { status: "cancelled" };+ }++ const selection = electron.dialog.showOpenDialogSync(focusedWindow, {+ properties: ["openFile"],+ filters: [{ name: t("import.zip_filter"), extensions: ["zip"] }]+ });+ if (!selection || selection.length === 0) {+ return { status: "cancelled" };+ }++ const path = selection[0];+ return { status: "selected", token: grantFileAccess(path), fileName: basename(path) };+ });++ electron.ipcMain.handle("import-from-token", async (_e, opts: ImportFromTokenOpts): Promise<NativeImportResult> => {+ const path = redeemFileAccess(opts.token);+ if (!path) {+ return { status: "error", message: t("import.invalid_file_grant") };+ }++ try {+ return { status: "imported", importedNoteId: await runZipImport(path, opts) };+ } catch (e) {+ const message = e instanceof Error ? e.message : String(e);+ TaskContext.getInstance(opts.taskId, "importNotes", opts.options).reportError(message);+ getLog().error(`Native zip import failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ return { status: "error", message };+ }+ });+}++// token -> { absolute path, expiry }. A grant is the capability handed to the renderer in place of a path.+const fileGrants = new Map<string, { path: string; expiresAt: number }>();+const GRANT_TTL_MS = 5 * 60 * 1000;++/** Mints a single-use, time-limited token for a path the *user* picked in the OS dialog. */+function grantFileAccess(path: string): string {+ const token = coreUtils.randomString(32);+ fileGrants.set(token, { path, expiresAt: Date.now() + GRANT_TTL_MS });+ return token;+}++/** Resolves and consumes a token (single-use); returns null if unknown or expired. */+function redeemFileAccess(token: string): string | null {+ const grant = fileGrants.get(token);+ fileGrants.delete(token);+ if (!grant || grant.expiresAt < Date.now()) {+ return null;+ }+ return grant.path;+}++/** Imports the zip at `path` in place, reporting progress/success over the WebSocket like the HTTP route. */+async function runZipImport(path: string, opts: ImportFromTokenOpts): Promise<string | undefined> {+ const parentNote = becca.getNoteOrThrow(opts.parentNoteId);+ const taskContext = TaskContext.getInstance(opts.taskId, "importNotes", opts.options);++ const note = await cls.init(async () => {+ // Match the HTTP import route: skip per-entity events and change-id tracking during the bulk import.+ cls.disableEntityEvents();+ cls.ignoreEntityChangeIds();+ return zipImportService.importZip(taskContext, { path }, parentNote);+ });++ // Import ran with entity events disabled, so becca wasn't updated incrementally — force a reload.+ becca_loader.load();+ // Small delay mirrors the route: let the transaction commit before the client reacts to success.+ setTimeout(() => taskContext.taskSucceeded({ parentNoteId: opts.parentNoteId, importedNoteId: note?.noteId }), 1000);++ return note?.noteId;+}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex c7e00adc60..76e8ed0d9d 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -338,6 +338,10 @@"export": {"zip_filter": "ZIP archive (*.zip)"},+ "import": {+ "zip_filter": "ZIP archive (*.zip)",+ "invalid_file_grant": "The file selection has expired or is invalid. Please choose the file again."+ },"pdf": {"export_filter": "PDF Document (*.pdf)","unable-to-export-message": "The current note could not be exported as a PDF.",diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex f21d75701d..fd67d42659 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -532,6 +532,51 @@ export interface ElectronNativeExportApi {exportSubtreeToFile(opts: { branchId: string; format: string; title: string; taskId: string }): Promise<NativeExportResult>;}+/** Import flags forwarded to the native importer (mirrors the HTTP route's options; no path). */+export interface NativeImportOptions {+ safeImport: boolean;+ shrinkImages: boolean;+ textImportedAsText: boolean;+ codeImportedAsCode: boolean;+ spreadsheetImportedAsSpreadsheet: boolean;+ explodeArchives: boolean;+ replaceUnderscoresWithSpaces: boolean;+}++/** Outcome of {@link ElectronNativeImportApi.pickZipFile}: a capability token, never a path. */+export interface NativeImportPickResult {+ status: "selected" | "cancelled";+ /** Single-use, short-lived grant for the user-chosen file (when `status === "selected"`). */+ token?: string;+ /** Display name of the chosen file (when `status === "selected"`). */+ fileName?: string;+}++/** Outcome of {@link ElectronNativeImportApi.importFromToken}. */+export interface NativeImportResult {+ status: "imported" | "error";+ /** Root note of the import (when `status === "imported"`). */+ importedNoteId?: string;+ /** Failure detail (when `status === "error"`). */+ message?: string;+}++/**+ * Desktop-native large-`.zip` import that reads the user's file **in place** (bounded memory, no temp+ * copy). The renderer never handles a filesystem path: {@link pickZipFile} runs the OS dialog in the main+ * process and returns an opaque capability token, which {@link importFromToken} redeems. A script can't+ * forge a token or pass a path, so it can never read an arbitrary file.+ */+export interface ElectronNativeImportApi {+ /** Prompts a native "open file" dialog (`.zip`) and returns a single-use token for the chosen file. */+ pickZipFile(): Promise<NativeImportPickResult>;+ /**+ * Imports the file behind `token` into `parentNoteId`. Progress/success/error are reported over the+ * WebSocket via `taskId`, matching the HTTP import path.+ */+ importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions }): Promise<NativeImportResult>;+}+/*** The complete surface exposed to the renderer as `window.electronApi` via* `contextBridge`. The renderer must access Electron-only functionality through@@ -568,4 +613,6 @@ export interface ElectronApi {onenote: ElectronOneNoteApi;/** Desktop-native subtree export that streams a `.zip` straight to a file. */nativeExport: ElectronNativeExportApi;+ /** Desktop-native large-`.zip` import that reads the user's file in place via a capability token. */+ nativeImport: ElectronNativeImportApi;}