Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): read security.json through a shared, strict parser

Elian Doran6acc40ea7579
diff --git a/apps/client/src/widgets/type_widgets/options/security.tsx b/apps/client/src/widgets/type_widgets/options/security.tsx
index 18ec8a34bd..68575e94cd 100644
--- a/apps/client/src/widgets/type_widgets/options/security.tsx
+++ b/apps/client/src/widgets/type_widgets/options/security.tsx
@@ -1,6 +1,6 @@
import { useState } from "preact/hooks";
-import type { StandaloneSecuritySettingName } from "@triliumnext/commons";
+import type { SecurityToggleName } from "@triliumnext/commons";
import { t } from "../../../services/i18n";
import { isElectron, isStandalone } from "../../../services/utils";
@@ -83,7 +83,7 @@ function canToggle(): boolean {
* the user still has to answer either way.
*/
async function requestSecurityChange(
- setting: StandaloneSecuritySettingName, enabled: boolean
+ setting: SecurityToggleName, enabled: boolean
): Promise<boolean> {
const api = window.electronApi?.security ?? window.standaloneApi?.security;
diff --git a/apps/desktop/src/services/security_settings.spec.ts b/apps/desktop/src/services/security_settings.spec.ts
index 4c49db4f94..26fc25c915 100644
--- a/apps/desktop/src/services/security_settings.spec.ts
+++ b/apps/desktop/src/services/security_settings.spec.ts
@@ -84,6 +84,19 @@ describe("security_settings", () => {
h.fileStore.set(SETTINGS_PATH, "{ not valid json");
expect(securitySettings.getSecuritySettings()).toEqual({});
});
+
+ it("answers for nothing a setting was not given a boolean for", () => {
+ // What main.ts does with this is assign it straight to `config.Security`, where it is
+ // read as a boolean: the string "false" is truthy, so taking the file at its word would
+ // enable the setting it appears to turn off. Nothing but a boolean is an answer.
+ h.fileStore.set(SETTINGS_PATH, JSON.stringify({
+ backendScriptingEnabled: "false",
+ sqlConsoleEnabled: 1,
+ allowLanAccess: true
+ }));
+
+ expect(securitySettings.getSecuritySettings()).toEqual({ allowLanAccess: true });
+ });
});
describe("registerSecurityIpcHandlers — enabling", () => {
diff --git a/apps/desktop/src/services/security_settings.ts b/apps/desktop/src/services/security_settings.ts
index 39c94c00b3..6ddbb30169 100644
--- a/apps/desktop/src/services/security_settings.ts
+++ b/apps/desktop/src/services/security_settings.ts
@@ -1,3 +1,4 @@
+import { parseSecuritySettings, type SecuritySettings } from "@triliumnext/commons";
import dataDirs from "@triliumnext/server/src/services/data_dir.js";
import electron from "electron";
import fs from "fs";
@@ -6,16 +7,10 @@ import path from "path";
const SECURITY_JSON_PATH = path.join(dataDirs.TRILIUM_DATA_DIR, "security.json");
-interface SecuritySettings {
- backendScriptingEnabled?: boolean;
- sqlConsoleEnabled?: boolean;
- allowLanAccess?: boolean;
-}
-
function readSettings(): SecuritySettings {
try {
if (fs.existsSync(SECURITY_JSON_PATH)) {
- return JSON.parse(fs.readFileSync(SECURITY_JSON_PATH, "utf-8"));
+ return parseSecuritySettings(fs.readFileSync(SECURITY_JSON_PATH, "utf-8"));
}
} catch {
// Corrupted or unreadable — treat as defaults
diff --git a/apps/standalone/src/lightweight/security_settings.spec.ts b/apps/standalone/src/lightweight/security_settings.spec.ts
index ae49affcf8..9cc471cfed 100644
--- a/apps/standalone/src/lightweight/security_settings.spec.ts
+++ b/apps/standalone/src/lightweight/security_settings.spec.ts
@@ -3,8 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
acquireSecuritySettings,
DEFAULT_SECURITY_SETTINGS,
- isSecuritySettingName,
- parseSecuritySettings,
+ isWritableSettingName,
+ resolveSecuritySettings,
SecuritySettingsStore,
toCoreConfig
} from "./security_settings.js";
@@ -183,7 +183,7 @@ describe("a file that says something other than yes or no", () => {
});
it("grants only the settings it names, whatever else it carries", () => {
- const settings = parseSecuritySettings(JSON.stringify({
+ const settings = resolveSecuritySettings(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.
@@ -250,10 +250,10 @@ describe("a change that is not one of the two", () => {
});
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);
+ expect(isWritableSettingName("backendScriptingEnabled")).toBe(true);
+ expect(isWritableSettingName("sqlConsoleEnabled")).toBe(true);
+ expect(isWritableSettingName("allowLanAccess")).toBe(false);
+ expect(isWritableSettingName("__proto__")).toBe(false);
});
});
diff --git a/apps/standalone/src/lightweight/security_settings.ts b/apps/standalone/src/lightweight/security_settings.ts
index 6c923c97c2..a355cac7b6 100644
--- a/apps/standalone/src/lightweight/security_settings.ts
+++ b/apps/standalone/src/lightweight/security_settings.ts
@@ -1,4 +1,4 @@
-import type { StandaloneSecuritySettingName } from "@triliumnext/commons";
+import { parseSecuritySettings, type SecurityToggleName } from "@triliumnext/commons";
import type { CoreConfig } from "@triliumnext/core";
/**
@@ -25,7 +25,11 @@ export interface StandaloneSecuritySettings {
sqlConsoleEnabled: boolean;
}
-export const SECURITY_SETTING_NAMES: readonly StandaloneSecuritySettingName[] = [
+/**
+ * What this build writes. The file can carry the desktop's LAN access too, but there is no listener
+ * here for it to open, so a request naming it is refused rather than stored.
+ */
+export const WRITABLE_SETTING_NAMES: readonly SecurityToggleName[] = [
"backendScriptingEnabled",
"sqlConsoleEnabled"
];
@@ -107,7 +111,7 @@ export class SecuritySettingsStore {
try {
const bytes = new Uint8Array(this.handle.getSize());
this.handle.read(bytes, { at: 0 });
- return parseSecuritySettings(new TextDecoder().decode(bytes));
+ return resolveSecuritySettings(new TextDecoder().decode(bytes));
} catch (e) {
console.warn("[SecuritySettings] The settings file could not be read:", e);
return { ...DEFAULT_SECURITY_SETTINGS };
@@ -122,7 +126,7 @@ export class SecuritySettingsStore {
* becomes what the next start reads.
*/
setSetting(name: unknown, enabled: unknown): boolean {
- if (!this.handle || !isSecuritySettingName(name) || typeof enabled !== "boolean") {
+ if (!this.handle || !isWritableSettingName(name) || typeof enabled !== "boolean") {
return false;
}
@@ -150,32 +154,23 @@ export class SecuritySettingsStore {
}
}
-export function isSecuritySettingName(name: unknown): name is StandaloneSecuritySettingName {
- return typeof name === "string" && (SECURITY_SETTING_NAMES as readonly string[]).includes(name);
+export function isWritableSettingName(name: unknown): name is SecurityToggleName {
+ return typeof name === "string" && (WRITABLE_SETTING_NAMES as readonly string[]).includes(name);
}
/**
- * Reads what the file says, granting nothing it does not say exactly.
+ * What the file says, as an answer for each setting rather than only for the ones it named.
*
- * 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.
+ * The shared reader leaves a setting out when the file has nothing to say about it, which is what
+ * a server needs so `config.ini` still gets a turn. There is no config file here, so an unanswered
+ * setting is one nobody has agreed to.
*/
-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 };
- }
+export function resolveSecuritySettings(raw: string): StandaloneSecuritySettings {
+ const settings = parseSecuritySettings(raw);
- const record = parsed as Record<string, unknown>;
return {
- backendScriptingEnabled: record.backendScriptingEnabled === true,
- sqlConsoleEnabled: record.sqlConsoleEnabled === true
+ backendScriptingEnabled: settings.backendScriptingEnabled === true,
+ sqlConsoleEnabled: settings.sqlConsoleEnabled === true
};
}
diff --git a/apps/standalone/src/security_gate.ts b/apps/standalone/src/security_gate.ts
index 98546676c2..215bc772a5 100644
--- a/apps/standalone/src/security_gate.ts
+++ b/apps/standalone/src/security_gate.ts
@@ -1,4 +1,4 @@
-import type { StandaloneSecurityApi, StandaloneSecuritySettingName } from "@triliumnext/commons";
+import type { SecurityToggleName, StandaloneSecurityApi } from "@triliumnext/commons";
import { requestSecurityChange } from "./local-bridge.js";
@@ -51,7 +51,7 @@ export function createSecurityApi(): StandaloneSecurityApi {
/** Whether the user agreed, and the change reached the file. Every other answer is `false`. */
async function requestChange(
- setting: StandaloneSecuritySettingName, enabled: boolean
+ setting: SecurityToggleName, enabled: boolean
): Promise<boolean> {
// Only granting is limited. Turning a capability off is what the user does to get out of a
// situation like this one, and a script that keeps asking for it can achieve nothing worse
@@ -96,7 +96,7 @@ function hasUserActivation(): boolean {
* costs nothing and keeps i18next out of the startup bundle.
*/
async function promptFor(
- setting: StandaloneSecuritySettingName, enabled: boolean
+ setting: SecurityToggleName, enabled: boolean
): Promise<string> {
const { t } = await import("../../client/src/services/i18n.js");
const settingLabel = setting === "backendScriptingEnabled"
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index 6f561454f3..3fb3345f80 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -35,6 +35,7 @@ export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";
export * from "./lib/backup_name.js";
export * from "./lib/filesystem_name.js";
export * from "./lib/electron_api_interface.js";
+export * from "./lib/security_settings.js";
export * from "./lib/setup_marker.js";
export * from "./lib/standalone_api_interface.js";
export * from "./lib/favicon_contrast.js";
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index fa28234eb8..7584944087 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -1,3 +1,5 @@
+import type { SecurityToggleApi } from "./security_settings.js";
+
/**
* Parameters delivered by the main process to the renderer when the user opens
* the system context menu (right-click) somewhere inside a web view.
@@ -487,17 +489,7 @@ export interface ElectronNavigationApi {
* to prevent malicious scripts from modifying them. Changes require a native
* OS confirmation dialog and an app restart to take effect.
*/
-export interface ElectronSecurityApi {
- /**
- * Requests a change to a security setting. Shows a native OS confirmation
- * dialog before writing. Returns `true` if the user confirmed and the
- * change was written (restart required to take effect), `false` if cancelled.
- */
- setBackendScriptingEnabled(enabled: boolean): Promise<boolean>;
-
- /** Requests a change to the SQL console setting. Same flow as above. */
- setSqlConsoleEnabled(enabled: boolean): Promise<boolean>;
-
+export interface ElectronSecurityApi extends SecurityToggleApi {
/**
* Requests enabling/disabling LAN access. When enabled, the desktop binds
* its TCP listener to all interfaces (instead of loopback) so other devices
diff --git a/packages/commons/src/lib/security_settings.spec.ts b/packages/commons/src/lib/security_settings.spec.ts
new file mode 100644
index 0000000000..477a97f86a
--- /dev/null
+++ b/packages/commons/src/lib/security_settings.spec.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+
+import { parseSecuritySettings } from "./security_settings.js";
+
+describe("what the security file says", () => {
+ it("is every setting it named with a boolean", () => {
+ expect(parseSecuritySettings(JSON.stringify({
+ backendScriptingEnabled: true,
+ sqlConsoleEnabled: false,
+ allowLanAccess: true
+ }))).toEqual({
+ backendScriptingEnabled: true,
+ sqlConsoleEnabled: false,
+ allowLanAccess: true
+ });
+ });
+
+ it("leaves out what it did not name, so the config file still gets a turn", () => {
+ // Absent is not the same as `false` here: a server merges this over config.ini, and
+ // answering for a setting the file never mentioned would silently override it.
+ expect(parseSecuritySettings(`{"sqlConsoleEnabled": true}`)).toEqual({ sqlConsoleEnabled: true });
+ });
+
+ it("carries nothing it was not asked about", () => {
+ const settings = parseSecuritySettings(JSON.stringify({
+ backendScriptingEnabled: true,
+ readOnly: true,
+ instanceName: "elsewhere"
+ }));
+
+ expect(settings).toEqual({ backendScriptingEnabled: true });
+ });
+
+ // Only a literal boolean is an answer. Every one of these is what a forged or half-written file
+ // looks like, and a `JSON.parse` that took them at face value would hand the string "false" to
+ // a config field read as a boolean, where it is truthy.
+ 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", `` ]
+ ])("answers for nothing when it holds %s", (_case, contents) => {
+ expect(parseSecuritySettings(contents)).toEqual({});
+ });
+
+ it("leaves the prototype alone when the file aims at it", () => {
+ parseSecuritySettings(`{"__proto__": {"backendScriptingEnabled": true}}`);
+
+ expect(({} as Record<string, unknown>).backendScriptingEnabled).toBeUndefined();
+ expect(Object.prototype).not.toHaveProperty("backendScriptingEnabled");
+ });
+});
diff --git a/packages/commons/src/lib/security_settings.ts b/packages/commons/src/lib/security_settings.ts
new file mode 100644
index 0000000000..e84883b933
--- /dev/null
+++ b/packages/commons/src/lib/security_settings.ts
@@ -0,0 +1,81 @@
+/**
+ * The settings every build keeps outside its database, and the one reader of them.
+ *
+ * Backend scripting, the SQL console and the desktop's LAN access are deliberately not options: a
+ * script that reaches the SQL console can `UPDATE` any table, so a flag stored in the database
+ * would let one of them grant another. Each build keeps them somewhere its own scripts cannot
+ * write instead — `config.ini` on a server, `security.json` in the desktop's data directory, a
+ * locked OPFS file in the browser — and they all read that file through {@link parseSecuritySettings}.
+ *
+ * @module
+ */
+
+/** What a build with no `config.ini` can offer a toggle for, since it can write the file itself. */
+export type SecurityToggleName = "backendScriptingEnabled" | "sqlConsoleEnabled";
+
+/** Everything the file can carry. LAN access is the desktop's, which is where the listener is. */
+export type SecuritySettingName = SecurityToggleName | "allowLanAccess";
+
+/**
+ * What the file says.
+ *
+ * A setting is present only when the file named it with a literal boolean. Absent means the file
+ * has no answer, which leaves whatever the build would otherwise run with — the `config.ini` value
+ * on a server, `false` where there is no config file to read.
+ */
+export type SecuritySettings = Partial<Record<SecuritySettingName, boolean>>;
+
+const SECURITY_SETTING_NAMES: readonly SecuritySettingName[] = [
+ "backendScriptingEnabled",
+ "sqlConsoleEnabled",
+ "allowLanAccess"
+];
+
+/**
+ * Reads the file, granting nothing it does not say exactly.
+ *
+ * Only a literal boolean counts. A `"false"` is a string and every non-empty string is truthy, so
+ * a file carrying one would otherwise enable the setting it appears to disable; a `1`, an object
+ * or a null is what a half-written file looks like, and none of them is a decision the user made.
+ *
+ * Never throws. A file that cannot be read is one the instance is better off without, which is the
+ * safe direction: the settings it holds are the ones worth withholding when in doubt.
+ */
+export function parseSecuritySettings(raw: string): SecuritySettings {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return {};
+ }
+
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
+ return {};
+ }
+
+ const record = parsed as Record<string, unknown>;
+ const settings: SecuritySettings = {};
+ for (const name of SECURITY_SETTING_NAMES) {
+ if (typeof record[name] === "boolean") {
+ settings[name] = record[name];
+ }
+ }
+
+ return settings;
+}
+
+/**
+ * Asks to change a security setting, which the platform's own confirmation gates.
+ *
+ * Both methods resolve `true` only when the user agreed and the change was written; applying it
+ * takes a restart. The confirmation belongs to the platform rather than to the page, because a
+ * note script can reach every dialog the application draws for itself: the desktop asks the
+ * operating system, and the browser build asks the browser.
+ */
+export interface SecurityToggleApi {
+ /** 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>;
+}
diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.ts
index 0a10496932..abdae4e854 100644
--- a/packages/commons/src/lib/standalone_api_interface.ts
+++ b/packages/commons/src/lib/standalone_api_interface.ts
@@ -1,3 +1,5 @@
+import type { SecurityToggleApi } from "./security_settings.js";
+
/**
* What the standalone build exposes to the client as `window.standaloneApi`.
*
@@ -124,28 +126,15 @@ 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.
+ * The same two toggles the desktop offers, defended in a place where it is harder: a frontend
+ * script here runs in the page, so it can call these methods itself. What it cannot do is answer
+ * the dialog, which the browser draws, and it has no other way to the setting, which lives in an
+ * OPFS file the SQLite worker holds an exclusive lock on.
*
- * 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.
+ * A reload applies what is written. Present only on the tab that owns the database.
*/
-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>;
-}
+export type StandaloneSecurityApi = SecurityToggleApi;
/** The complete surface the standalone build exposes to the client. */
export interface StandaloneApi {