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(standalone): let the user enable backend scripting and the SQL console
Elian Doran86c33a89ce19
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex df5fc91ecf..7a3fe0c0b6 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2240,7 +2240,17 @@"server_config_hint": "Add the following to your config.ini file:","server_env_hint": "Or set the following environment variable:","restart_required": "Restart required for this change to take effect.",- "restart_now": "Restart the application now"+ "restart_now": "Restart the application now",+ "standalone": {+ "backend_scripting_section_description": "Backend scripts run inside this browser, with full access to your notes, your settings and your sync credentials. They can be triggered via sync, import, or any content that includes executable attributes, without you opening the note. Frontend scripts are always enabled and reach no further than the app itself does.",+ "reload_required": "Reload required for this change to take effect.",+ "reload_now": "Reload the page now",+ "other_tab_hint": "These settings are changed from the tab that owns the database, which is usually the first Trilium tab you opened. Close the other tabs and reload this page to change them here.",+ "confirm_enable": "Enable {{- setting}}?\n\n{{- warning}} A script in your notes can request this, so only continue if you asked for it yourself.",+ "confirm_disable": "Disable {{- setting}}?",+ "confirm_backend_scripting_warning": "Backend scripts get full access to your notes, settings and sync credentials.",+ "confirm_sql_console_warning": "The SQL console can read your sync credentials and password hash, and change or delete any note."+ }},"password": {"heading": "Password",diff --git a/apps/client/src/widgets/type_widgets/options/security.spec.tsx b/apps/client/src/widgets/type_widgets/options/security.spec.tsxindex 7404a155a3..804cfa90aa 100644--- a/apps/client/src/widgets/type_widgets/options/security.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/security.spec.tsx@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({electron: true,+ standalone: false,/** What the settings currently are, as the options store answers them. */stored: {} as Record<string, boolean>,/** What the main process answers when asked to write one — refusing leaves nothing pending. */@@ -12,9 +13,12 @@ const mocks = vi.hoisted(() => ({// `isElectron` decides both whether these settings can be written at all and whether the LAN card is// on offer, so a scenario has to be able to say which kind of build it is pretending to be.+// `isStandalone` is a const rather than a function, hence the getter: a scenario sets it before it+// renders, and the page reads it while rendering.vi.mock("../../../services/utils", async (importOriginal) => ({...(await importOriginal<typeof import("../../../services/utils")>()),- isElectron: () => mocks.electron+ isElectron: () => mocks.electron,+ get isStandalone() { return mocks.standalone; }}));// i18next is never initialised here and answers `undefined` until it is, which would make every@@ -34,6 +38,7 @@ let host: HTMLElement;beforeEach(() => {mocks.electron = true;+ mocks.standalone = false;mocks.stored = {};mocks.confirms = true;(window as unknown as { electronApi: unknown }).electronApi = {@@ -50,8 +55,36 @@ afterEach(() => {render(null, host);document.body.innerHTML = "";delete (window as unknown as { electronApi?: unknown }).electronApi;+ delete (window as unknown as { standaloneApi?: unknown }).standaloneApi;});+/**+ * Turns this into the in-browser build, where the settings live in an OPFS file the database+ * worker holds the lock on. Only the tab that owns that worker is given a `security` API to reach+ * it with, which is what `ownsDatabase` decides here.+ */+function asStandalone(ownsDatabase: boolean) {+ mocks.electron = false;+ mocks.standalone = true;+ delete (window as unknown as { electronApi?: unknown }).electronApi;+ (window as unknown as { standaloneApi: unknown }).standaloneApi = {+ restore: {},+ backup: {},+ security: ownsDatabase+ ? {+ setBackendScriptingEnabled: vi.fn(async () => mocks.confirms),+ setSqlConsoleEnabled: vi.fn(async () => mocks.confirms)+ }+ : undefined+ };+}++function standaloneSecurityApi() {+ return (window as unknown as {+ standaloneApi: { security: Record<string, ReturnType<typeof vi.fn>> };+ }).standaloneApi.security;+}+function open() {act(() => {render(<SecuritySettings />, host);@@ -133,3 +166,56 @@ describe("the security settings", () => {expect(restartOffered()).toBe(false);});});++describe("the security settings in a browser", () => {+ it("are written through the standalone bridge, asking for a reload not a restart", async () => {+ asStandalone(true);+ open();++ // LAN access is a desktop setting: there is no listener here to open.+ expect(switches()).toHaveLength(2);+ expect(switches().every((toggle) => toggle.disabled)).toBe(false);++ await flip(0);+ expect(standaloneSecurityApi().setBackendScriptingEnabled).toHaveBeenCalledWith(true);++ const row = switches()[0].closest(".tn-card-option");+ const description = row?.querySelector(".tn-card-option-description")?.textContent;+ expect(description).toBe("security.standalone.reload_required");+ expect(host.querySelector(".restart-action button")?.textContent)+ .toContain("security.standalone.reload_now");+ });++ it("describes what a backend script reaches in a browser, not on a server", () => {+ asStandalone(true);+ open();++ // The desktop wording promises filesystem, network and OS access, none of which a Web+ // Worker has — telling a browser user that would be scaring them off the wrong thing.+ const description = host.querySelector(".tn-card-description")?.textContent;+ expect(description).toBe("security.standalone.backend_scripting_section_description");+ });++ it("leaves the switch where it was when the user declines the browser's dialog", async () => {+ mocks.confirms = false;+ asStandalone(true);+ open();++ await flip(0);++ expect(standaloneSecurityApi().setBackendScriptingEnabled).toHaveBeenCalledWith(true);+ expect(restartOffered()).toBe(false);+ });++ it("holds them out of reach in a tab that does not own the database", () => {+ asStandalone(false);+ open();++ expect(switches().every((toggle) => toggle.disabled)).toBe(true);+ expect(host.textContent).toContain("security.standalone.other_tab_hint");++ // Never the server instructions: there is no config.ini to add anything to.+ expect(host.querySelectorAll(".collapsible")).toHaveLength(0);+ expect(host.textContent).not.toContain("security.server_config_hint");+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/security.tsx b/apps/client/src/widgets/type_widgets/options/security.tsxindex ac2a6510f8..d7e216338e 100644--- a/apps/client/src/widgets/type_widgets/options/security.tsx+++ b/apps/client/src/widgets/type_widgets/options/security.tsx@@ -1,7 +1,9 @@import { useState } from "preact/hooks";+import type { StandaloneSecuritySettingName } from "@triliumnext/commons";+import { t } from "../../../services/i18n";-import { isElectron } from "../../../services/utils";+import { isElectron, isStandalone } from "../../../services/utils";import { Card, CardSection, OptionCardSection } from "../../react/Card";import CodeBlock from "../../react/CodeBlock";import Collapsible from "../../react/Collapsible";@@ -47,18 +49,70 @@ export default function SecuritySettings() {setPendingValue={setPendingLanAccess}/>)}- {hasPendingChanges && isElectron() && (- <RestartAction text={t("security.restart_now")} icon="bx-refresh" />+ {hasPendingChanges && canToggle() && (+ <RestartAction+ text={isElectron()+ ? t("security.restart_now")+ : t("security.standalone.reload_now")}+ icon="bx-refresh"+ />)}</>);}-function ServerConfigHint({ configKey, envVar }: { configKey: string; envVar: string }) {- if (isElectron()) {+/**+ * Whether this build can change the settings from here.+ *+ * Both platforms that can keep them outside the database can: the desktop in its data directory,+ * standalone in an OPFS file its database worker holds the lock on. A server reads them from+ * `config.ini`, and a standalone tab that does not own the database has no worker to write through+ * — the tab that does is where the toggle works. Elsewhere the toggle shows the state and+ * `ServerConfigHint` says where to change it.+ */+function canToggle(): boolean {+ return isElectron() || (isStandalone && !!window.standaloneApi?.security);+}++/**+ * Asks the platform to change a setting, and says whether the user agreed to it.+ *+ * The confirmation is the platform's, not this page's: a note script can reach any dialog the+ * application draws for itself, so the desktop asks the operating system and standalone asks the+ * browser. Which means this is not the only caller — the page is one way to reach a request that+ * the user still has to answer either way.+ */+async function requestSecurityChange(+ setting: StandaloneSecuritySettingName, enabled: boolean+): Promise<boolean> {+ const api = window.electronApi?.security ?? window.standaloneApi?.security;++ if (setting === "backendScriptingEnabled") {+ return await api?.setBackendScriptingEnabled(enabled) === true;+ }++ return await api?.setSqlConsoleEnabled(enabled) === true;+}++/**+ * Where to change a setting this build does not change from here.+ *+ * A server reads them from `config.ini`; a standalone tab that does not own the database has no+ * worker to write the file through, so the one that does is where the toggle works.+ */+function WhereToEnableHint({ configKey, envVar }: { configKey: string; envVar: string }) {+ if (canToggle()) {return null;}+ if (isStandalone) {+ return (+ <CardSection>+ <p>{t("security.standalone.other_tab_hint")}</p>+ </CardSection>+ );+ }+return (<CardSection><Collapsible title={t("security.how_to_enable")}>@@ -80,13 +134,11 @@ interface ToggleSectionProps {}function BackendScriptingSettings({ liveValue, pendingValue, setPendingValue }: ToggleSectionProps) {- const isDesktop = isElectron();const displayValue = pendingValue ?? liveValue;const hasPendingChange = pendingValue !== null && pendingValue !== liveValue;async function handleToggle(enabled: boolean) {- const confirmed = await window.electronApi?.security.setBackendScriptingEnabled(enabled);- if (confirmed) {+ if (await requestSecurityChange("backendScriptingEnabled", enabled)) {// If toggling back to the live value, clear pending statesetPendingValue(enabled === liveValue ? null : enabled);}@@ -95,20 +147,24 @@ function BackendScriptingSettings({ liveValue, pendingValue, setPendingValue }:return (<Cardheading={t("security.backend_scripting_title")}- description={t("security.backend_scripting_section_description")}+ // Standalone runs core in a Web Worker, where none of the filesystem, network and OS+ // access the other builds grant a backend script exists to grant.+ description={isStandalone+ ? t("security.standalone.backend_scripting_section_description")+ : t("security.backend_scripting_section_description")}actions={<HelpButton helpPage="SPirpZypehBG" />}><OptionCardSectionname="backend-scripting-enabled"label={t("security.backend_scripting_label")}description={hasPendingChange- ? t("security.restart_required")+ ? restartRequiredText(): t("security.backend_scripting_description")}>- <FormToggle currentValue={displayValue} onChange={handleToggle} disabled={!isDesktop} />+ <FormToggle currentValue={displayValue} onChange={handleToggle} disabled={!canToggle()} /></OptionCardSection>- <ServerConfigHint+ <WhereToEnableHintconfigKey="backendScriptingEnabled"envVar="TRILIUM_SECURITY_BACKEND_SCRIPTING_ENABLED"/>@@ -116,14 +172,17 @@ function BackendScriptingSettings({ liveValue, pendingValue, setPendingValue }:);}+/** What has to happen before a change counts: a relaunch on the desktop, a reload in a browser. */+function restartRequiredText(): string {+ return isElectron() ? t("security.restart_required") : t("security.standalone.reload_required");+}+function SqlConsoleSettings({ liveValue, pendingValue, setPendingValue }: ToggleSectionProps) {- const isDesktop = isElectron();const displayValue = pendingValue ?? liveValue;const hasPendingChange = pendingValue !== null && pendingValue !== liveValue;async function handleToggle(enabled: boolean) {- const confirmed = await window.electronApi?.security.setSqlConsoleEnabled(enabled);- if (confirmed) {+ if (await requestSecurityChange("sqlConsoleEnabled", enabled)) {setPendingValue(enabled === liveValue ? null : enabled);}}@@ -131,6 +190,8 @@ function SqlConsoleSettings({ liveValue, pendingValue, setPendingValue }: Togglereturn (<Cardheading={t("security.sql_console_title")}+ // The options table holds the sync credentials and the password hash wherever Trilium+ // runs, so what the SQL console reaches is the same in a browser as anywhere else.description={t("security.sql_console_section_description")}actions={<HelpButton helpPage="YKWqdJhzi2VY" />}>@@ -138,13 +199,13 @@ function SqlConsoleSettings({ liveValue, pendingValue, setPendingValue }: Togglename="sql-console-enabled"label={t("security.sql_console_label")}description={hasPendingChange- ? t("security.restart_required")+ ? restartRequiredText(): t("security.sql_console_description")}>- <FormToggle currentValue={displayValue} onChange={handleToggle} disabled={!isDesktop} />+ <FormToggle currentValue={displayValue} onChange={handleToggle} disabled={!canToggle()} /></OptionCardSection>- <ServerConfigHint+ <WhereToEnableHintconfigKey="sqlConsoleEnabled"envVar="TRILIUM_SECURITY_SQL_CONSOLE_ENABLED"/>diff --git a/apps/standalone/src/lightweight/security_settings.spec.ts b/apps/standalone/src/lightweight/security_settings.spec.tsnew file mode 100644index 0000000000..10bdcccef8--- /dev/null+++ b/apps/standalone/src/lightweight/security_settings.spec.ts@@ -0,0 +1,352 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ acquireSecuritySettings,+ DEFAULT_SECURITY_SETTINGS,+ isSecuritySettingName,+ parseSecuritySettings,+ SecuritySettingsStore,+ toCoreConfig+} from "./security_settings.js";++/**+ * The origin's private filesystem, with the part of it this depends on: an OPFS sync access handle+ * takes an exclusive lock, which is what keeps the page — where a frontend script runs — out of a+ * file the worker holds.+ */+class FakeFile {+ bytes = new Uint8Array(0);+ heldBy: string | null = null;+}++const files = new Map<string, FakeFile>();++/** The error a browser raises for a file another context has open. */+function lockedError(): DOMException {+ const error = Object.assign(new Error("locked"), { name: "NoModificationAllowedError" });+ return error as unknown as DOMException;+}++function fileHandleFor(name: string) {+ return {+ // Reading a file this way takes no lock, so a browser grants it whoever else holds the+ // file — which is why the contents are only ever read through the handle below.+ async getFile() {+ const file = files.get(name);+ return { arrayBuffer: async () => (file?.bytes ?? new Uint8Array(0)).buffer };+ },+ async createSyncAccessHandle() {+ const file = files.get(name);+ if (!file) {+ throw new Error("NotFoundError");+ }+ if (file.heldBy) {+ throw lockedError();+ }+ file.heldBy = "worker";++ return {+ getSize: () => file.bytes.length,+ read: (into: Uint8Array) => {+ into.set(file.bytes.subarray(0, into.length));+ return Math.min(into.length, file.bytes.length);+ },+ write: (from: Uint8Array) => {+ file.bytes = new Uint8Array(from);+ return from.length;+ },+ truncate: () => { file.bytes = new Uint8Array(0); },+ flush: () => {},+ close: () => { file.heldBy = null; }+ };+ }+ };+}++function fakeRoot() {+ return {+ async getFileHandle(name: string, opts?: { create?: boolean }) {+ if (!files.has(name)) {+ if (!opts?.create) {+ throw new Error("NotFoundError");+ }+ files.set(name, new FakeFile());+ }+ return fileHandleFor(name);+ }+ } as unknown as FileSystemDirectoryHandle;+}++const getRoot = async () => fakeRoot();++/** What the file says on disk, as the next start would read it. */+function fileContents(): string {+ const file = files.get("security.json");+ return file ? new TextDecoder().decode(file.bytes) : "";+}++/** Writes the file the way something else would: a previous start, or an attacker. */+function writeFile(contents: string): void {+ const file = files.get("security.json") ?? new FakeFile();+ file.bytes = new TextEncoder().encode(contents);+ files.set("security.json", file);+}++beforeEach(() => {+ files.clear();+ vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("what a start runs with", () => {+ it("is nothing enabled when there is no file, and leaves one for later writes", async () => {+ const store = await acquireSecuritySettings({ getRoot });++ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ expect(store.isWritable).toBe(true);+ expect(files.has("security.json")).toBe(true);+ });++ it("is what the file says, once something agreed to it", async () => {+ const store = await acquireSecuritySettings({ getRoot });++ expect(store.setSetting("backendScriptingEnabled", true)).toBe(true);+ expect(store.read()).toEqual({ backendScriptingEnabled: true, sqlConsoleEnabled: false });++ // What the next start reads, rather than what this one remembers.+ expect(JSON.parse(fileContents())).toEqual({+ backendScriptingEnabled: true,+ sqlConsoleEnabled: false+ });+ });++ it("keeps the settings apart, so agreeing to one grants only that one", async () => {+ const store = await acquireSecuritySettings({ getRoot });++ store.setSetting("sqlConsoleEnabled", true);++ expect(store.read()).toEqual({ backendScriptingEnabled: false, sqlConsoleEnabled: true });+ });++ it("can be taken back", async () => {+ const store = await acquireSecuritySettings({ getRoot });++ store.setSetting("backendScriptingEnabled", true);+ expect(store.setSetting("backendScriptingEnabled", false)).toBe(true);++ expect(store.read().backendScriptingEnabled).toBe(false);+ });++ it("becomes the config core is started with, and overrides nothing else", () => {+ expect(toCoreConfig({ backendScriptingEnabled: true, sqlConsoleEnabled: false })).toEqual({+ General: { instanceName: "", readOnly: false },+ Sync: { syncServerHost: "", syncServerTimeout: "", syncProxy: "" },+ Security: {+ backendScriptingEnabled: true,+ sqlConsoleEnabled: false,+ // There is no listener to open in a browser, so this is never the file's to grant.+ allowLanAccess: false+ }+ });+ });+});++describe("a file that says something other than yes or no", () => {+ // Every one of these is what a forged or half-written file looks like, and none of them is a+ // decision the user made. The type of the value is the whole check: a truthy `"false"` would+ // otherwise enable backend scripting.+ it.each([+ [ "a string", `{"backendScriptingEnabled": "true"}` ],+ [ "the string false, which is truthy", `{"backendScriptingEnabled": "false"}` ],+ [ "a number", `{"backendScriptingEnabled": 1}` ],+ [ "an object", `{"backendScriptingEnabled": {}}` ],+ [ "an array", `{"backendScriptingEnabled": [true]}` ],+ [ "null", `{"backendScriptingEnabled": null}` ],+ [ "a nested shape", `{"Security": {"backendScriptingEnabled": true}}` ],+ [ "not an object at all", `"backendScriptingEnabled"` ],+ [ "a bare true", `true` ],+ [ "an array of settings", `[{"backendScriptingEnabled": true}]` ],+ [ "not JSON", `backendScriptingEnabled=true` ],+ [ "half a file", `{"backendScriptingEnabled": tr` ],+ [ "nothing at all", `` ]+ ])("grants nothing when it holds %s", async (_case, contents) => {+ writeFile(contents);++ const store = await acquireSecuritySettings({ getRoot });++ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ });++ it("grants only the settings it names, whatever else it carries", () => {+ const settings = parseSecuritySettings(JSON.stringify({+ backendScriptingEnabled: true,+ // A file that names something else is not a way to reach it: only these two are read,+ // and only these two are written back.+ allowLanAccess: true,+ readOnly: true,+ instanceName: "elsewhere"+ }));++ expect(settings).toEqual({ backendScriptingEnabled: true, sqlConsoleEnabled: false });+ });++ it("drops what it did not put there, rather than carrying it forward", async () => {+ writeFile(JSON.stringify({ sqlConsoleEnabled: true, allowLanAccess: true }));+ const store = await acquireSecuritySettings({ getRoot });++ store.setSetting("backendScriptingEnabled", true);++ expect(JSON.parse(fileContents())).toEqual({+ backendScriptingEnabled: true,+ sqlConsoleEnabled: true+ });+ });+});++describe("a change that is not one of the two", () => {+ it.each([+ [ "a setting that is not kept here", "allowLanAccess" ],+ [ "the prototype", "__proto__" ],+ [ "a constructor", "constructor" ],+ [ "a method name", "toString" ],+ [ "nothing", "" ],+ [ "a number", 1 ],+ [ "an object", { backendScriptingEnabled: true } ],+ [ "nothing at all", undefined ],+ [ "null", null ]+ ])("is refused when the name is %s", async (_case, name) => {+ const store = await acquireSecuritySettings({ getRoot });++ expect(store.setSetting(name, true)).toBe(false);+ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ expect(fileContents()).toBe("");+ });++ it.each([+ [ "a string", "true" ],+ [ "a number", 1 ],+ [ "an object", {} ],+ [ "nothing at all", undefined ],+ [ "null", null ]+ ])("is refused when the value is %s", async (_case, enabled) => {+ const store = await acquireSecuritySettings({ getRoot });++ expect(store.setSetting("backendScriptingEnabled", enabled)).toBe(false);+ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ });++ it("leaves the prototype alone when the name was aiming at it", async () => {+ const store = await acquireSecuritySettings({ getRoot });++ store.setSetting("__proto__", true);++ expect(({} as Record<string, unknown>).backendScriptingEnabled).toBeUndefined();+ expect(Object.prototype).not.toHaveProperty("backendScriptingEnabled");+ });++ it("knows which names are settings", () => {+ expect(isSecuritySettingName("backendScriptingEnabled")).toBe(true);+ expect(isSecuritySettingName("sqlConsoleEnabled")).toBe(true);+ expect(isSecuritySettingName("allowLanAccess")).toBe(false);+ expect(isSecuritySettingName("__proto__")).toBe(false);+ });+});++describe("the lock the file is only trustworthy behind", () => {+ it("is held for as long as the store lives, so nothing else can write the file", async () => {+ await acquireSecuritySettings({ getRoot });++ // What the page would be doing: the same file, from a context that does not own the+ // database. While the worker holds it, the browser refuses.+ await expect(fileHandleFor("security.json").createSyncAccessHandle())+ .rejects.toMatchObject({ name: "NoModificationAllowedError" });+ });++ it("is waited for, since a reload starts this worker before the last let go", async () => {+ writeFile(JSON.stringify({ backendScriptingEnabled: true }));+ const file = files.get("security.json");+ if (!file) {+ throw new Error("the file should exist");+ }+ file.heldBy = "the previous worker";+ setTimeout(() => { file.heldBy = null; }, 30);++ const store = await acquireSecuritySettings({ getRoot, pollMs: 5, deadlineMs: 5_000 });++ expect(store.isWritable).toBe(true);+ expect(store.read().backendScriptingEnabled).toBe(true);+ });++ it("grants nothing when it was never taken, whatever the file says", async () => {+ // The shape of an attack this cannot otherwise win: hold the file open from the page so+ // the worker cannot lock it, having written it to say yes. Refusing to read an unlocked+ // file costs the user the toggle until the tabs are closed; honouring it would cost them+ // the guarantee.+ writeFile(JSON.stringify({ backendScriptingEnabled: true, sqlConsoleEnabled: true }));+ const file = files.get("security.json");+ if (file) {+ file.heldBy = "a page that will not let go";+ }++ const store = await acquireSecuritySettings({ getRoot, pollMs: 1, deadlineMs: 10 });++ expect(store.isWritable).toBe(false);+ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ expect(store.setSetting("backendScriptingEnabled", true)).toBe(false);+ });++ it("gives up immediately on a failure waiting cannot fix", async () => {+ files.set("security.json", new FakeFile());+ const root = {+ getFileHandle: async () => ({+ createSyncAccessHandle: async () => {+ const name = "NotSupportedError";+ throw Object.assign(new Error("no such capability"), { name });+ }+ })+ } as unknown as FileSystemDirectoryHandle;++ const store = await acquireSecuritySettings({+ getRoot: async () => root,+ // Long enough that a retry loop would outlast the test.+ deadlineMs: 60_000,+ pollMs: 1_000+ });++ expect(store.isWritable).toBe(false);+ });++ it("grants nothing when there is no private filesystem to keep it in", async () => {+ const store = await acquireSecuritySettings({+ getRoot: async () => { throw new Error("no OPFS here"); }+ });++ expect(store.isWritable).toBe(false);+ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ });++ it("grants nothing when the file cannot be read", () => {+ const store = new SecuritySettingsStore({+ getSize: () => { throw new Error("the handle went away"); }+ } as unknown as FileSystemSyncAccessHandle);++ expect(store.read()).toEqual(DEFAULT_SECURITY_SETTINGS);+ });++ it("reports a write that did not land as refused", () => {+ const store = new SecuritySettingsStore({+ getSize: () => 0,+ read: () => 0,+ truncate: () => {},+ write: () => { throw new Error("out of space"); },+ flush: () => {}+ } as unknown as FileSystemSyncAccessHandle);++ expect(store.setSetting("backendScriptingEnabled", true)).toBe(false);+ });+});diff --git a/apps/standalone/src/lightweight/security_settings.ts b/apps/standalone/src/lightweight/security_settings.tsnew file mode 100644index 0000000000..6ff43cf292--- /dev/null+++ b/apps/standalone/src/lightweight/security_settings.ts@@ -0,0 +1,189 @@+import type { StandaloneSecuritySettingName } from "@triliumnext/commons";+import type { CoreConfig } from "@triliumnext/core";++/**+ * The `security.json` this build keeps in the origin's private filesystem.+ *+ * The desktop keeps the same file in its data directory, deliberately outside the database, so a+ * script that reaches the SQL console cannot grant itself backend scripting with an `UPDATE+ * options`. Here the file has to survive a stronger attacker: a frontend script runs in the page,+ * and the page can reach OPFS on its own.+ *+ * What keeps it out of reach is the exclusive lock an OPFS sync access handle takes.+ * `createSyncAccessHandle()` exists only in a dedicated worker, so this worker takes the handle+ * during startup and holds it until the page that owns it goes away; while it does, a+ * `createWritable()` on the same file from the page fails with `NoModificationAllowedError`, and+ * so does removing it. The worker is therefore the only writer, and the only way to reach the+ * worker is the `SECURITY_SET` message that `security_gate.ts` sends after the browser has asked+ * the user.+ *+ * @module+ */++export interface StandaloneSecuritySettings {+ backendScriptingEnabled: boolean;+ sqlConsoleEnabled: boolean;+}++export const SECURITY_SETTING_NAMES: readonly StandaloneSecuritySettingName[] = [+ "backendScriptingEnabled",+ "sqlConsoleEnabled"+];++/** What an instance never told otherwise runs with, and what every failure falls back to. */+export const DEFAULT_SECURITY_SETTINGS: StandaloneSecuritySettings = {+ backendScriptingEnabled: false,+ sqlConsoleEnabled: false+};++const SECURITY_FILE_NAME = "security.json";++/** Matches `waitForSahPoolRelease`, which waits out the same handover for the database pool. */+const ACQUIRE_DEADLINE_MS = 15_000;+const ACQUIRE_POLL_MS = 150;++export interface AcquireOptions {+ deadlineMs?: number;+ pollMs?: number;+ getRoot?: () => Promise<FileSystemDirectoryHandle>;+}++/**+ * Takes the lock on `security.json` and answers what it says, for as long as the worker lives.+ *+ * A reload starts this worker while the browser is still releasing the previous one's handles, so+ * the acquisition is retried the way the database pool's is. Every way this can fail — no OPFS, a+ * handle nothing ever releases — produces a store that reads the defaults and refuses writes,+ * because the alternative to a lock that was never taken is a file anything can write.+ */+export async function acquireSecuritySettings({+ deadlineMs = ACQUIRE_DEADLINE_MS,+ pollMs = ACQUIRE_POLL_MS,+ getRoot = () => navigator.storage.getDirectory()+}: AcquireOptions = {}): Promise<SecuritySettingsStore> {+ let file: FileSystemFileHandle;+ try {+ file = await (await getRoot()).getFileHandle(SECURITY_FILE_NAME, { create: true });+ } catch (e) {+ console.warn("[SecuritySettings] The settings file could not be opened:", e);+ return new SecuritySettingsStore(null);+ }++ const deadline = Date.now() + deadlineMs;+ for (;;) {+ try {+ return new SecuritySettingsStore(await file.createSyncAccessHandle());+ } catch (e) {+ // `NoModificationAllowedError` is the one worth waiting out: another context holds the+ // file, usually the worker of the page this one replaced. Anything else is an+ // environment that cannot do this at all, and retrying it only delays the boot.+ const isHeld = (e as DOMException)?.name === "NoModificationAllowedError";+ if (!isHeld || Date.now() >= deadline) {+ console.warn(+ "[SecuritySettings] The settings file could not be locked, so this "+ + "instance runs with backend scripting and the SQL console off:", e+ );+ return new SecuritySettingsStore(null);+ }+ await new Promise(resolve => setTimeout(resolve, pollMs));+ }+ }+}++/** Reads the settings this start runs with, and writes the ones the user agrees to. */+export class SecuritySettingsStore {+ constructor(private readonly handle: FileSystemSyncAccessHandle | null) {}++ /** Whether the lock was taken, which is what decides if a change can be written at all. */+ get isWritable(): boolean {+ return this.handle !== null;+ }++ read(): StandaloneSecuritySettings {+ if (!this.handle) {+ return { ...DEFAULT_SECURITY_SETTINGS };+ }++ try {+ const bytes = new Uint8Array(this.handle.getSize());+ this.handle.read(bytes, { at: 0 });+ return parseSecuritySettings(new TextDecoder().decode(bytes));+ } catch (e) {+ console.warn("[SecuritySettings] The settings file could not be read:", e);+ return { ...DEFAULT_SECURITY_SETTINGS };+ }+ }++ /**+ * Writes one setting, and says whether it was written.+ *+ * The name and the value are checked here rather than trusted, because both arrive as a message+ * from the page: this is the point where a request stops being something a script asked for and+ * becomes what the next start reads.+ */+ setSetting(name: unknown, enabled: unknown): boolean {+ if (!this.handle || !isSecuritySettingName(name) || typeof enabled !== "boolean") {+ return false;+ }++ try {+ const settings = { ...this.read(), [name]: enabled };+ const bytes = new TextEncoder().encode(JSON.stringify(settings, null, 4));+ this.handle.truncate(0);+ this.handle.write(bytes, { at: 0 });+ this.handle.flush();+ return true;+ } catch (e) {+ console.error("[SecuritySettings] The settings file could not be written:", e);+ return false;+ }+ }+}++export function isSecuritySettingName(name: unknown): name is StandaloneSecuritySettingName {+ return typeof name === "string" && (SECURITY_SETTING_NAMES as readonly string[]).includes(name);+}++/**+ * Reads what the file says, granting nothing it does not say exactly.+ *+ * Only a literal `true` enables anything: a `"true"`, a `1` or an object is what a half-written+ * file looks like, and none of them is a decision the user made.+ */+export function parseSecuritySettings(raw: string): StandaloneSecuritySettings {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return { ...DEFAULT_SECURITY_SETTINGS };+ }++ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {+ return { ...DEFAULT_SECURITY_SETTINGS };+ }++ const record = parsed as Record<string, unknown>;+ return {+ backendScriptingEnabled: record.backendScriptingEnabled === true,+ sqlConsoleEnabled: record.sqlConsoleEnabled === true+ };+}++/**+ * The config core is started with, which is where these settings become the guard's answer.+ *+ * Everything outside `Security` is left empty, which is how core reads "no override": the server+ * takes those from `config.ini` and this build has none. `allowLanAccess` is a desktop setting —+ * there is no listener here to open.+ */+export function toCoreConfig(settings: StandaloneSecuritySettings): CoreConfig {+ return {+ General: { instanceName: "", readOnly: false },+ Sync: { syncServerHost: "", syncServerTimeout: "", syncProxy: "" },+ Security: {+ backendScriptingEnabled: settings.backendScriptingEnabled,+ sqlConsoleEnabled: settings.sqlConsoleEnabled,+ allowLanAccess: false+ }+ };+}diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.tsindex a3aeb60353..093da7a905 100644--- a/apps/standalone/src/local-bridge.spec.ts+++ b/apps/standalone/src/local-bridge.spec.ts@@ -777,6 +777,74 @@ describe("leadership", () => {});});+describe("security settings", () => {+ it("sends the change to the worker that holds the file, and answers what it wrote", async () => {+ const bridge = await freshBridge();+ const change = bridge.requestSecurityChange("backendScriptingEnabled", true);++ const worker = lastWorker();+ const sent = worker.postMessage.mock.calls+ .map(([message]) => message as { type: string; id: string; setting?: string; enabled?: boolean })+ .find((message) => message.type === "SECURITY_SET");+ expect(sent).toMatchObject({ setting: "backendScriptingEnabled", enabled: true });++ worker.onmessage?.({ data: { type: "SECURITY_SET_RESULT", id: sent?.id, written: true } });+ await expect(change).resolves.toBe(true);+ });++ it("answers no when the worker refused to write it", async () => {+ const bridge = await freshBridge();+ const change = bridge.requestSecurityChange("sqlConsoleEnabled", true);++ const worker = lastWorker();+ const sent = worker.postMessage.mock.calls+ .map(([message]) => message as { type: string; id: string })+ .find((message) => message.type === "SECURITY_SET");+ // A worker whose settings file is not locked reports the change as unwritten rather than+ // pretending; anything but an outright `true` leaves the setting where it was.+ worker.onmessage?.({ data: { type: "SECURITY_SET_RESULT", id: sent?.id, written: "yes" } });++ await expect(change).resolves.toBe(false);+ });++ it("ignores a result that answers a different change", async () => {+ const bridge = await freshBridge();+ const change = bridge.requestSecurityChange("backendScriptingEnabled", true);+ const worker = lastWorker();++ worker.onmessage?.({ data: { type: "SECURITY_SET_RESULT", id: "some other change", written: true } });++ let settled = false;+ void change.then(() => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);+ });++ it("gives up rather than hanging when the worker never answers", async () => {+ vi.useFakeTimers();+ try {+ const bridge = await freshBridge();+ const change = bridge.requestSecurityChange("backendScriptingEnabled", true);++ await vi.advanceTimersByTimeAsync(30_000);++ await expect(change).resolves.toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it("a follower writes nothing, since the file belongs to the leader's worker", async () => {+ const bridge = await freshBridge();+ leadership.isLeader = false;++ await expect(bridge.requestSecurityChange("backendScriptingEnabled", true)).resolves.toBe(false);++ // No worker either: one here would open a second database against the same OPFS pool.+ expect(workerInstances).toHaveLength(0);+ });+});+describe("cross-tab ws relay", () => {it("relays the worker's ws messages to the other tabs", async () => {const posted: unknown[] = [];diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex 45fa743a1c..d00a4eaffd 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -98,6 +98,44 @@ export function restoreBackup(opts: {});}+/** Security changes waiting on the worker that owns the file, by id. */+const securityChanges = new Map<string, (written: boolean) => void>();++/** Long enough for a worker that is still starting up, short enough that the toggle answers. */+const SECURITY_CHANGE_TIMEOUT_MS = 30_000;++/**+ * Writes a security setting, on the worker that holds the lock on the file it lives in.+ *+ * The page cannot write that file itself — the lock is the whole point, see+ * `lightweight/security_settings.ts` — and this deliberately avoids the request path: a route+ * would put the change behind the same API a frontend script already calls freely. Sending it as+ * a message means the only way to reach it is a reference to the worker, which lives in this+ * module and is handed to nothing.+ *+ * Only the leader tab has that worker. A follower is refused rather than served, as for a backup.+ */+export function requestSecurityChange(setting: string, enabled: boolean): Promise<boolean> {+ if (!isLeader()) {+ return Promise.resolve(false);+ }++ const worker = startLocalServerWorker();+ const id = Math.random().toString(36).slice(2);++ return new Promise((resolve) => {+ const settle = (written: boolean) => {+ clearTimeout(timer);+ securityChanges.delete(id);+ resolve(written);+ };+ const timer = setTimeout(() => settle(false), SECURITY_CHANGE_TIMEOUT_MS);++ securityChanges.set(id, settle);+ worker.postMessage({ type: "SECURITY_SET", id, setting, enabled });+ });+}+/*** How long the download's frame is kept in the page: comfortably past the service worker's own* 30-second wait for the stream to open, after which the response has either been handed to the@@ -433,6 +471,13 @@ export function startLocalServerWorker() {return;}+ // Whether a security setting the user agreed to reached the file. Only ever `true` when+ // the worker wrote it, so a worker that refused the change leaves the toggle where it was.+ if (msg?.type === "SECURITY_SET_RESULT") {+ securityChanges.get(msg.id)?.(msg.written === true);+ return;+ }+// Handle fatal platform crashes (shown as an overlay to the user)if (msg?.type === "FATAL_ERROR") {console.error("[LocalBridge] Fatal error:", msg.message);diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex 3d3de6a57b..d0aac0623d 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -103,6 +103,9 @@ let waitForSahPoolRelease: typeof import('./lightweight/sql_provider').waitForSalet sqlProvider: InstanceType<typeof BrowserSqlProvider> | null = null;let messagingProvider: InstanceType<typeof WorkerMessagingProvider> | null = null;+/** Holds the lock on `security.json` for as long as this worker lives, and is its only writer. */+let securityStore: import('./lightweight/security_settings').SecuritySettingsStore | null = null;+// Core module, router, and initialization statelet coreModule: typeof import("@triliumnext/core") | null = null;let router: BrowserRouter | null = null;@@ -229,6 +232,13 @@ async function initialize(): Promise<void> {// First, load all modules dynamicallyawait loadModules();+ // Before the database, and before anything that can take time: the window in which+ // this file is locked by nobody is the window in which a page that outlived the+ // previous worker could write it, so it is made as short as this boot allows.+ const { acquireSecuritySettings, toCoreConfig } = await import('./lightweight/security_settings.js');+ securityStore = await acquireSecuritySettings();+ const securityConfig = toCoreConfig(securityStore.read());+// A reload starts this worker while the browser is still releasing the previous// worker's exclusive OPFS access handles, so the boot waits for the database pool// to be free — before the log service, whose own OPFS file is held the same way.@@ -320,6 +330,10 @@ async function initialize(): Promise<void> {},inAppHelp: new StandaloneInAppHelpProvider(),image: (await import("./services/image_provider.js")).standaloneImageProvider,+ // What `assertScriptingEnabled()` answers from. Read from a locked OPFS file rather+ // than the database, because the SQL console is enabled separately and an `UPDATE+ // options` would otherwise be all it takes to grant backend scripting.+ config: securityConfig,// Read before core opens anything, because what it says is whether to open the// database at all: a page reloaded by the app itself comes back to the wizard.setupMarker: await consumeSetupMarker(),@@ -548,6 +562,24 @@ async function handleRestoreBackup(id: string, backup: File, passphrase?: string/** Whether a restore is running, since a second one would prepare over the first one's work. */let restoreInProgress = false;+/**+ * Writes a security setting the user has agreed to, which this worker is the only writer of.+ *+ * Reached only from `requestSecurityChange` in local-bridge.ts, which sends it after the browser's+ * own confirmation dialog — but what arrives here is still just a message, so the name and the+ * value are checked by the store rather than trusted. The change applies at the next start, since+ * core was handed its config when it was initialized.+ */+function handleSecuritySet(id: string, setting: unknown, enabled: unknown): void {+ const written = securityStore?.setSetting(setting, enabled) === true;++ if (written) {+ console.log(`[Worker] Security setting "${setting}" written; it applies from the next start.`);+ }++ (self as unknown as Worker).postMessage({ type: "SECURITY_SET_RESULT", id, written });+}+/*** Streams the database into a download the service worker is holding open on the other end of* `port`. Every way this ends is reported twice over: through the port for the download's sake,@@ -633,6 +665,14 @@ self.onmessage = async (event) => {return;}+ if (msg.type === "SECURITY_SET") {+ // Waits for the boot that takes the lock: a change arriving before it would be written by+ // a store that has no handle, and reported as refused for no reason the user could see.+ await initialize().catch(() => undefined);+ handleSecuritySet(msg.id, msg.setting, msg.enabled);+ return;+ }+if (msg.type !== "LOCAL_REQUEST") return;const { id, request } = msg;diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.tsindex 1feeb60096..1e51e768e2 100644--- a/apps/standalone/src/main.spec.ts+++ b/apps/standalone/src/main.spec.ts@@ -9,7 +9,8 @@ const mocks = vi.hoisted(() => ({announceLeadership: vi.fn(),localFetch: vi.fn(),capacitorHttpHandler: vi.fn(),- saveUrlToDevice: vi.fn()+ saveUrlToDevice: vi.fn(),+ requestSecurityChange: vi.fn()}));// Whether this tab wins the database lock. Only the leader may start a worker;@@ -23,7 +24,8 @@ vi.mock("./local-bridge.js", () => ({restoreBackup: mocks.restoreBackup,downloadDatabase: mocks.downloadDatabase,announceLeadership: mocks.announceLeadership,- localFetch: mocks.localFetch+ localFetch: mocks.localFetch,+ requestSecurityChange: mocks.requestSecurityChange}));vi.mock("./leader_election.js", () => ({claimLeadership: (onElected: () => void) => {@@ -100,6 +102,9 @@ describe("bootstrap", () => {await vi.waitFor(() => expect(mocks.announceLeadership).toHaveBeenCalled());// The leader also answers the client's API calls directly, skipping that route.expect(window.standaloneApi?.localFetch).toBe(mocks.localFetch);+ // And its worker is the one holding the settings file, so it is the tab that can change+ // what this instance is allowed to run.+ expect(window.standaloneApi?.security).toBeDefined();});it("a follower tab starts no worker but still bridges the SW", async () => {@@ -116,6 +121,10 @@ describe("bootstrap", () => {// A follower must keep calling through the service worker: with no worker of its own,// a localFetch here would answer from nothing.expect(window.standaloneApi?.localFetch).toBeUndefined();++ // Nor can it change a security setting: the file that holds them is locked by the+ // leader's worker, which this tab has no way to reach.+ expect(window.standaloneApi?.security).toBeUndefined();});it("asks the browser to keep the storage the database lives in", async () => {diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.tsindex a074a149ac..d95809650f 100644--- a/apps/standalone/src/main.ts+++ b/apps/standalone/src/main.ts@@ -7,6 +7,7 @@ import { showErrorOverlay } from "./error-overlay.js";import { installIosInterceptors } from "./ios-interceptors.js";import { claimLeadership } from "./leader_election.js";import { announceLeadership, attachServiceWorkerBridge, downloadDatabase, localFetch, registerNativeHttpHandler, restoreBackup, saveDatabase, startLocalServerWorker } from "./local-bridge.js";+import { createSecurityApi } from "./security_gate.js";/*** What a cold standalone start passes through, drawn as the splash's progress bar. Weights are@@ -120,6 +121,9 @@ async function bootstrap() {// The leader answers API requests from its own worker, so the client's server.ts// can skip the service-worker round trip.standaloneApi.localFetch = localFetch;+ // Its worker is also the one holding the lock on the security settings file, so it is+ // the only tab that can change what this instance is allowed to run. See security_gate.ts.+ standaloneApi.security = createSecurityApi();announceLeadership();});diff --git a/apps/standalone/src/security_gate.spec.ts b/apps/standalone/src/security_gate.spec.tsnew file mode 100644index 0000000000..7e54f529a8--- /dev/null+++ b/apps/standalone/src/security_gate.spec.ts@@ -0,0 +1,218 @@+import type { StandaloneSecurityApi } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++/** What the page asked the worker to write, and what the worker said back. */+const bridge = vi.hoisted(() => ({+ calls: [] as Array<{ setting: string; enabled: boolean }>,+ /** Resolved with what the worker reports; a pending one is a write still in flight. */+ answer: null as null | ((written: boolean) => void),+ result: true as boolean | "pending"+}));++vi.mock("./local-bridge.js", () => ({+ requestSecurityChange: (setting: string, enabled: boolean) => {+ bridge.calls.push({ setting, enabled });+ if (bridge.result === "pending") {+ return new Promise<boolean>((resolve) => { bridge.answer = resolve; });+ }+ return Promise.resolve(bridge.result);+ }+}));++// The strings are the client's, loaded by the time any of this can be reached. Keys rather than+// English, so an assertion names what the dialog is supposed to say rather than how it is worded.+vi.mock("../../client/src/services/i18n.js", () => ({+ t: (key: string, params?: Record<string, string>) =>+ params ? `${key} ${JSON.stringify(params)}` : key+}));++/** Answers the dialog the way the user would. */+let confirmed: boolean;+let dialogs: string[];++function setUserActivation(activation: { isActive: boolean } | undefined) {+ Object.defineProperty(navigator, "userActivation", { value: activation, configurable: true });+}++/**+ * A fresh page, with `window.confirm` in place before the module captures it — which is the order+ * the real bootstrap runs in, since `main.ts` loads this long before a note's script bundle.+ */+async function loadGate(confirmImpl: unknown = (message: string) => {+ dialogs.push(message);+ return confirmed;+}): Promise<StandaloneSecurityApi> {+ vi.resetModules();+ Object.defineProperty(window, "confirm", {+ value: confirmImpl, configurable: true, writable: true+ });+ return (await import("./security_gate.js")).createSecurityApi();+}++beforeEach(() => {+ bridge.calls = [];+ bridge.answer = null;+ bridge.result = true;+ confirmed = true;+ dialogs = [];+ setUserActivation({ isActive: true });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("a change the user agrees to", () => {+ it("is asked about, then written", async () => {+ const api = await loadGate();++ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(true);++ expect(dialogs).toHaveLength(1);+ expect(bridge.calls).toEqual([ { setting: "backendScriptingEnabled", enabled: true } ]);+ });++ it("names the setting and what it grants, in words the caller cannot supply", async () => {+ const api = await loadGate();++ await api.setBackendScriptingEnabled(true);+ await api.setSqlConsoleEnabled(true);++ expect(dialogs[0]).toContain("security.standalone.confirm_enable");+ expect(dialogs[0]).toContain("security.backend_scripting_title");+ expect(dialogs[0]).toContain("security.standalone.confirm_backend_scripting_warning");+ expect(dialogs[1]).toContain("security.sql_console_title");+ expect(dialogs[1]).toContain("security.standalone.confirm_sql_console_warning");+ });++ it("asks before taking one back, without the warning that belongs to granting", async () => {+ const api = await loadGate();++ await expect(api.setSqlConsoleEnabled(false)).resolves.toBe(true);++ expect(dialogs[0]).toContain("security.standalone.confirm_disable");+ expect(dialogs[0]).not.toContain("warning");+ expect(bridge.calls).toEqual([ { setting: "sqlConsoleEnabled", enabled: false } ]);+ });++ it("is only granted once the worker says it reached the file", async () => {+ bridge.result = false;+ const api = await loadGate();++ // The user agreed, but nothing was written — an unlocked settings file, say. Reporting+ // this as granted would leave the toggle showing something the next start will not do.+ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);+ });+});++describe("a change nobody agreed to", () => {+ it("is refused when the user says no, and nothing reaches the worker", async () => {+ confirmed = false;+ const api = await loadGate();++ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);++ expect(dialogs).toHaveLength(1);+ expect(bridge.calls).toEqual([]);+ });++ it("cannot be answered by a script that replaces window.confirm", async () => {+ confirmed = false;+ const api = await loadGate();++ // What a frontend script would do first. It replaces what the rest of the page sees, but+ // this module captured the function at load, before any note script could run.+ window.confirm = () => true;++ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);+ expect(dialogs).toHaveLength(1);+ expect(bridge.calls).toEqual([]);+ });++ it("never reaches a dialog when nothing the user did led to it", async () => {+ setUserActivation({ isActive: false });+ const api = await loadGate();++ // A script on a timer, or one run at startup: no transient activation, so it is refused+ // before the dialog it would otherwise be spamming.+ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);+ expect(dialogs).toEqual([]);+ expect(bridge.calls).toEqual([]);+ });++ it("still works where the browser tracks no activation at all", async () => {+ // Firefox exposes no `navigator.userActivation`; treating that as "nobody did anything"+ // would leave the toggle dead there, so the dialog and the decline limit carry it.+ setUserActivation(undefined);+ const api = await loadGate();++ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(true);+ expect(dialogs).toHaveLength(1);+ });++ it("is refused outright where there is no dialog to ask with", async () => {+ // `null` rather than `undefined` only because the latter would take the helper's default;+ // what the module checks is that there is no function to call.+ const api = await loadGate(null);++ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);+ expect(bridge.calls).toEqual([]);+ });+});++describe("a script that keeps asking", () => {+ it("runs out of dialogs, so it cannot wear the user down", async () => {+ confirmed = false;+ const api = await loadGate();++ for (let attempt = 0; attempt < 20; attempt++) {+ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);+ }++ expect(dialogs).toHaveLength(2);+ expect(bridge.calls).toEqual([]);+ });++ it("runs out across both settings together, rather than twice per setting", async () => {+ confirmed = false;+ const api = await loadGate();++ await api.setBackendScriptingEnabled(true);+ await api.setSqlConsoleEnabled(true);+ await api.setBackendScriptingEnabled(true);++ expect(dialogs).toHaveLength(2);+ });++ it("does not cost the user the toggle over one misclick", async () => {+ confirmed = false;+ const api = await loadGate();++ await api.setBackendScriptingEnabled(true);+ confirmed = true;++ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(true);+ expect(bridge.calls).toEqual([ { setting: "backendScriptingEnabled", enabled: true } ]);+ });++ it("cannot raise a second dialog over the answer to the first", async () => {+ bridge.result = "pending";+ const api = await loadGate();++ const first = api.setBackendScriptingEnabled(true);+ await vi.waitFor(() => expect(bridge.answer).not.toBeNull());++ // The user has agreed and the write is in flight. A request arriving now would otherwise+ // put a dialog in front of a user who is looking at the outcome of the last one.+ await expect(api.setSqlConsoleEnabled(true)).resolves.toBe(false);+ expect(dialogs).toHaveLength(1);++ bridge.answer?.(true);+ await expect(first).resolves.toBe(true);++ // And once it has settled, an honest request is asked about again.+ bridge.result = true;+ await expect(api.setSqlConsoleEnabled(true)).resolves.toBe(true);+ expect(dialogs).toHaveLength(2);+ });+});diff --git a/apps/standalone/src/security_gate.ts b/apps/standalone/src/security_gate.tsnew file mode 100644index 0000000000..cc9d4b43bc--- /dev/null+++ b/apps/standalone/src/security_gate.ts@@ -0,0 +1,107 @@+import type { StandaloneSecurityApi, StandaloneSecuritySettingName } from "@triliumnext/commons";++import { requestSecurityChange } from "./local-bridge.js";++/**+ * What stands between a request to enable backend scripting and the file that grants it.+ *+ * The desktop asks the operating system to draw this dialog, because a note script can reach every+ * dialog the application draws for itself. Here the equivalent is `confirm()`: the browser draws+ * it, a page cannot overlay it, click it or read its answer, and script execution stops dead until+ * the user has answered. That makes a script calling {@link StandaloneSecurityApi} no better off+ * than a script clicking the toggle in the settings would be — it summons the real dialog, with+ * the real warning, and gets whatever the user says.+ *+ * Three things beyond the dialog itself, in the order they stop an attempt:+ *+ * - The function `confirm` was at load, captured below. A script that assigns `window.confirm =+ * () => true` replaces what everything else on the page sees, not what this calls.+ * - Transient user activation, where the browser tracks it. A script on a timer has none, so it+ * never reaches the dialog at all; the toggle the user just clicked does.+ * - A decline limit, which is the backstop where activation is not tracked (Firefox). A script+ * that keeps asking gets {@link MAX_DECLINES} dialogs and then silence, so it cannot wear the+ * user down into clicking OK. One accidental Cancel does not cost the user the toggle.+ *+ * @module+ */++/**+ * Captured while the page is still only its own code: this module is loaded from `main.ts`, long+ * before the client fetches a note's script bundle.+ */+const nativeConfirm: typeof window.confirm | null =+ typeof window.confirm === "function" ? window.confirm.bind(window) : null;++/** Declines before this stops asking, high enough that a misclick is not a lockout. */+const MAX_DECLINES = 2;++let declines = 0;++/** One dialog at a time, so a second request cannot be raised over the answer to the first. */+let asking = false;++export function createSecurityApi(): StandaloneSecurityApi {+ return {+ setBackendScriptingEnabled: (enabled) => requestChange("backendScriptingEnabled", enabled),+ setSqlConsoleEnabled: (enabled) => requestChange("sqlConsoleEnabled", enabled)+ };+}++/** Whether the user agreed, and the change reached the file. Every other answer is `false`. */+async function requestChange(+ setting: StandaloneSecuritySettingName, enabled: boolean+): Promise<boolean> {+ if (!nativeConfirm || asking || declines >= MAX_DECLINES || !hasUserActivation()) {+ return false;+ }++ asking = true;+ try {+ if (!nativeConfirm(await promptFor(setting, enabled))) {+ declines++;+ return false;+ }++ return await requestSecurityChange(setting, enabled);+ } finally {+ asking = false;+ }+}++/**+ * Whether the user did something just now, which is what a request nobody made lacks.+ *+ * Firefox exposes no `userActivation`, so there the dialog and the decline limit carry this alone.+ * Treating its absence as "no activation" would leave the toggle dead in that browser.+ */+function hasUserActivation(): boolean {+ const activation = navigator.userActivation;+ return !activation || activation.isActive;+}++/**+ * What the dialog says.+ *+ * The text belongs to this module rather than to whoever calls it: a caller that supplied its own+ * could describe the change as something else, and the caller is not necessarily the settings page.+ * The client's catalogue is loaded by the time any of this can be reached, so importing it here+ * costs nothing and keeps i18next out of the startup bundle.+ */+async function promptFor(+ setting: StandaloneSecuritySettingName, enabled: boolean+): Promise<string> {+ const { t } = await import("../../client/src/services/i18n.js");+ const settingLabel = setting === "backendScriptingEnabled"+ ? t("security.backend_scripting_title")+ : t("security.sql_console_title");++ if (!enabled) {+ return t("security.standalone.confirm_disable", { setting: settingLabel });+ }++ const warning = setting === "backendScriptingEnabled"+ ? t("security.standalone.confirm_backend_scripting_warning")+ : t("security.standalone.confirm_sql_console_warning");++ return t("security.standalone.confirm_enable", { setting: settingLabel, warning });+}diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.tsindex a8e51d2bc0..0a10496932 100644--- a/packages/commons/src/lib/standalone_api_interface.ts+++ b/packages/commons/src/lib/standalone_api_interface.ts@@ -124,12 +124,37 @@ export interface StandaloneSaveApi {saveUrl(url: string): Promise<StandaloneSaveResult>;}+/** The security settings a standalone instance keeps outside its database. See {@link StandaloneSecurityApi}. */+export type StandaloneSecuritySettingName = "backendScriptingEnabled" | "sqlConsoleEnabled";++/**+ * Asks to change a security setting, which the browser's own confirmation dialog gates.+ *+ * The twin of `ElectronSecurityApi`, defending the same boundary in a place where it is harder to+ * hold: a frontend script here runs in the page, so it can call these methods itself. What it+ * cannot do is answer the dialog — `confirm()` is drawn by the browser, outside the page's reach —+ * and it cannot reach the setting any other way, because the value lives in an OPFS file the+ * SQLite worker holds an exclusive lock on rather than in the database the SQL console can write.+ *+ * Both methods resolve `true` only when the user confirmed and the change was written; a reload+ * applies it. Present only on the tab that owns the database, which is the tab that has a worker.+ */+export interface StandaloneSecurityApi {+ /** Requests backend script execution be turned on or off. */+ setBackendScriptingEnabled(enabled: boolean): Promise<boolean>;++ /** Requests the SQL console be turned on or off. */+ setSqlConsoleEnabled(enabled: boolean): Promise<boolean>;+}+/** The complete surface the standalone build exposes to the client. */export interface StandaloneApi {restore: StandaloneRestoreApi;backup: StandaloneBackupApi;/** Present only inside the Capacitor shell, where the browser saves no downloads itself. */save?: StandaloneSaveApi;+ /** Present only on the tab that owns the database, which is the one whose worker can write the file. */+ security?: StandaloneSecurityApi;/*** Answers an internal API request from the SQLite worker this page owns. The tab that wins the* database lock sets it, and the client's `server.ts` prefers it over its XHR transport, whichdiff --git a/packages/trilium-core/src/routes/api/options.spec.ts b/packages/trilium-core/src/routes/api/options.spec.tsindex 18edb0a2f8..f84aef489a 100644--- a/packages/trilium-core/src/routes/api/options.spec.ts+++ b/packages/trilium-core/src/routes/api/options.spec.ts@@ -214,6 +214,28 @@ describe("Options API (core)", () => {expect(res.status).toBe(400);});+ it("refuses to let the security flags be written, and keeps them out of the database", async () => {+ // These two decide whether backend scripts and the SQL console run at all, and they come+ // from a file no route can reach: config.ini on a server, security.json in the desktop's+ // data directory, a locked OPFS file in standalone. Making either of them an option would+ // put the first behind the second — a script granted the SQL console could `UPDATE+ // options` its way to backend scripting, without the user being asked.+ for (const name of [ "backendScriptingEnabled", "sqlConsoleEnabled" ]) {+ expect((await api.put(`/api/options/${name}/true`)).status).toBe(400);+ // The map form rolls the whole batch back rather than validating up front, so this is+ // the 500 the surrounding tests describe — either way nothing is written.+ expect((await api.put("/api/options", { body: { [name]: "true" } })).status).toBe(500);+ // No row at all, which the two SQL providers report differently.+ expect(getOptionValue(name) ?? null).toBeNull();+ }++ // The route reports them from the config it was started with, so what a write would have+ // to reach is somewhere the API does not go.+ const res = await api.get<Record<string, string>>("/api/options");+ expect(res.body.backendScriptingEnabled).toBe("false");+ expect(res.body.sqlConsoleEnabled).toBe("false");+ });+it("runs changeLanguage when updating the locale option", async () => {const changeLanguage = vi.spyOn(i18n, "changeLanguage").mockResolvedValue(undefined as never);const res = await api.put("/api/options/locale/de");