Skip to content

Build your personal knowledge base with Trilium Notes

fix(script api): fail gracefully when backend scripting is disabled

Elian Doran5ebe8b1a6ab7
diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.ts
index 7fbe95404c..6ce0080e87 100644
--- a/apps/client/src/services/frontend_script_api.spec.ts
+++ b/apps/client/src/services/frontend_script_api.spec.ts
@@ -5,7 +5,7 @@ import type FNote from "../entities/fnote.js";
import { buildNote } from "../test/easy-froca.js";
import dateNotesService from "./date_notes.js";
import dialogService from "./dialog.js";
-import FrontendScriptApi, { type Api, type Entity } from "./frontend_script_api.js";
+import FrontendScriptApi, { BackendScriptingDisabledError, type Api, type Entity } from "./frontend_script_api.js";
import { preactAPI } from "./frontend_script_api_preact.js";
import froca from "./froca.js";
import linkService from "./link.js";
@@ -176,7 +176,23 @@ describe("addButtonToToolbar", () => {
});
describe("runOnBackend / __runOnBackendInner", () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Backend scripting enabled by default; the disabled case is covered explicitly below.
+ vi.spyOn(options, "is").mockReturnValue(true);
+ });
+
+ it("short-circuits without posting and throws when backend scripting is disabled", async () => {
+ vi.spyOn(options, "is").mockReturnValue(false);
+ const post = vi.spyOn(server, "post");
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockImplementation(() => {});
+
+ await expect(makeApi().runOnBackend(() => {}, [])).rejects.toBeInstanceOf(BackendScriptingDisabledError);
+
+ // No server round-trip, and a single deduplicated toast (fixed id) is shown instead of a 500.
+ expect(post).not.toHaveBeenCalled();
+ expect(showPersistent).toHaveBeenCalledWith(expect.objectContaining({ id: "backend-scripting-disabled" }));
+ });
it("serializes a sync function, posts it, waits for sync and returns the result", async () => {
const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 42 } as never);
@@ -248,7 +264,21 @@ describe("runOnBackend / __runOnBackendInner", () => {
});
describe("runAsyncOnBackendWithManualTransactionHandling", () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(options, "is").mockReturnValue(true);
+ });
+
+ it("short-circuits without posting and throws when backend scripting is disabled", async () => {
+ vi.spyOn(options, "is").mockReturnValue(false);
+ const post = vi.spyOn(server, "post");
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockImplementation(() => {});
+
+ await expect(makeApi().runAsyncOnBackendWithManualTransactionHandling(async () => {}, [])).rejects.toBeInstanceOf(BackendScriptingDisabledError);
+
+ expect(post).not.toHaveBeenCalled();
+ expect(showPersistent).toHaveBeenCalledWith(expect.objectContaining({ id: "backend-scripting-disabled" }));
+ });
it("warns when passed a sync function reference, then runs non-transactionally", async () => {
const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 7 } as never);
diff --git a/apps/client/src/services/frontend_script_api.ts b/apps/client/src/services/frontend_script_api.ts
index eff08fb06b..b58de1d278 100644
--- a/apps/client/src/services/frontend_script_api.ts
+++ b/apps/client/src/services/frontend_script_api.ts
@@ -595,6 +595,14 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig
}
this.__runOnBackendInner = async (func, params, transactional) => {
+ // Short-circuit when backend scripting is disabled: skip the request entirely so the
+ // server never returns a 500, show a single deduplicated toast (fixed id) instead of one
+ // generic HTTP-error toast per failing script, and throw a typed error callers can detect.
+ if (!options.is("backendScriptingEnabled")) {
+ showBackendScriptingDisabledToast();
+ throw new BackendScriptingDisabledError();
+ }
+
if (typeof func === "function") {
func = func.toString();
}
@@ -799,6 +807,37 @@ export default FrontendScriptApi as any as {
new(startNote: FNote, currentNote: FNote, originEntity: Entity | null, $container: JQuery<HTMLElement> | null): Api;
};
+/**
+ * Thrown by {@link Api.runOnBackend} / {@link Api.runAsyncOnBackendWithManualTransactionHandling}
+ * when backend scripting is disabled on the server. The bundle executor recognizes this so it can
+ * skip its per-note error toast — the single deduplicated toast raised alongside it is enough.
+ */
+export class BackendScriptingDisabledError extends Error {
+ constructor() {
+ super("Backend script execution is disabled.");
+ this.name = "BackendScriptingDisabledError";
+ }
+}
+
+function showBackendScriptingDisabledToast() {
+ toastService.showPersistent({
+ id: "backend-scripting-disabled",
+ icon: "bx bx-code-block",
+ title: t("frontend_script_api.backend_scripting_disabled_title"),
+ message: t("frontend_script_api.backend_scripting_disabled_message"),
+ timeout: 15_000,
+ buttons: [
+ {
+ text: t("frontend_script_api.backend_scripting_disabled_open_settings"),
+ onClick: ({ dismissToast }) => {
+ appContext.tabManager.openInNewTab("_optionsSecurity", "_hidden", true);
+ dismissToast();
+ }
+ }
+ ]
+ });
+}
+
// --- Drift guards -----------------------------------------------------------
// The public script API surface lives in @triliumnext/commons (self-contained so
// it can feed the in-editor language service and the script-deployer). These
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index afd7bbe796..a68aba7e83 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2399,7 +2399,10 @@
},
"frontend_script_api": {
"async_warning": "You're passing an async function to `api.runOnBackend()` which will likely not work as you intended.\\nEither make the function synchronous (by removing `async` keyword), or use `api.runAsyncOnBackendWithManualTransactionHandling()`.",
- "sync_warning": "You're passing a synchronous function to `api.runAsyncOnBackendWithManualTransactionHandling()`,\\nwhile you should likely use `api.runOnBackend()` instead."
+ "sync_warning": "You're passing a synchronous function to `api.runAsyncOnBackendWithManualTransactionHandling()`,\\nwhile you should likely use `api.runOnBackend()` instead.",
+ "backend_scripting_disabled_title": "Backend scripting is disabled",
+ "backend_scripting_disabled_message": "A script tried to run code on the server, but backend scripting is turned off for security reasons. Enable it in Options → Security if you trust this script.",
+ "backend_scripting_disabled_open_settings": "Open security settings"
},
"ws": {
"sync-check-failed": "Sync check failed!",