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
fix(standalone): put the security command out of reach of backend scripts
Elian Dorandf07447ae9cc
diff --git a/apps/client/src/widgets/type_widgets/options/security.tsx b/apps/client/src/widgets/type_widgets/options/security.tsxindex d7e216338e..18ec8a34bd 100644--- a/apps/client/src/widgets/type_widgets/options/security.tsx+++ b/apps/client/src/widgets/type_widgets/options/security.tsx@@ -147,8 +147,8 @@ function BackendScriptingSettings({ liveValue, pendingValue, setPendingValue }:return (<Cardheading={t("security.backend_scripting_title")}- // 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.+ // Standalone runs core in a Web Worker, so what a backend script reaches there is the+ // database: every note, the options table, and the sync credentials it holds.description={isStandalone? t("security.standalone.backend_scripting_section_description"): t("security.backend_scripting_section_description")}diff --git a/apps/standalone/src/lightweight/security_settings.spec.ts b/apps/standalone/src/lightweight/security_settings.spec.tsindex 10bdcccef8..ae49affcf8 100644--- a/apps/standalone/src/lightweight/security_settings.spec.ts+++ b/apps/standalone/src/lightweight/security_settings.spec.ts@@ -149,7 +149,7 @@ describe("what a start runs with", () => {Security: {backendScriptingEnabled: true,sqlConsoleEnabled: false,- // There is no listener to open in a browser, so this is never the file's to grant.+ // The file holds the two scripting flags; LAN access stays where core defaults it.allowLanAccess: false}});@@ -349,4 +349,20 @@ describe("the lock the file is only trustworthy behind", () => {expect(store.setSetting("backendScriptingEnabled", true)).toBe(false);});++ it("reports a write that landed only partly as refused too", () => {+ // `write()` answers with a byte count rather than throwing when it runs short, and the+ // truncate before it has already happened, so what is left on disk is part of a setting.+ // The next start reads that as no settings at all, and the toggle has to say so rather+ // than claim the change was saved.+ const store = new SecuritySettingsStore({+ getSize: () => 0,+ read: () => 0,+ truncate: () => {},+ write: (bytes: Uint8Array) => bytes.length - 1,+ 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.tsindex 6ff43cf292..6c923c97c2 100644--- a/apps/standalone/src/lightweight/security_settings.ts+++ b/apps/standalone/src/lightweight/security_settings.ts@@ -130,8 +130,18 @@ export class SecuritySettingsStore {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 });+ const written = this.handle.write(bytes, { at: 0 });this.handle.flush();++ // A short write leaves the file holding part of a setting, which the next start reads+ // as no settings at all. Saying so is what keeps the toggle from claiming otherwise.+ if (written !== bytes.length) {+ console.error(+ `[SecuritySettings] Only ${written} of ${bytes.length} bytes were written.`+ );+ return false;+ }+return true;} catch (e) {console.error("[SecuritySettings] The settings file could not be written:", e);@@ -172,9 +182,8 @@ export function parseSecuritySettings(raw: string): StandaloneSecuritySettings {/*** 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.+ * Core treats an empty string and `false` as "no override" and falls back to the stored option, so+ * this carries the two flags the file holds and lets core answer the rest for itself.*/export function toCoreConfig(settings: StandaloneSecuritySettings): CoreConfig {return {diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.tsindex 093da7a905..ccb7143403 100644--- a/apps/standalone/src/local-bridge.spec.ts+++ b/apps/standalone/src/local-bridge.spec.ts@@ -125,7 +125,11 @@ describe("startLocalServerWorker", () => {const bridge = await freshBridge();const worker = bridge.startLocalServerWorker();expect(workerInstances).toHaveLength(1);- expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "INIT", useNativeHttp: false }));+ expect(worker.postMessage).toHaveBeenCalledWith(+ expect.objectContaining({ type: "INIT", useNativeHttp: false }),+ // The security channel's worker end, transferred rather than copied.+ [ expect.anything() ]+ );// Second call returns the same instance without creating another worker.expect(bridge.startLocalServerWorker()).toBe(worker);@@ -136,7 +140,10 @@ describe("startLocalServerWorker", () => {const bridge = await freshBridge();bridge.registerNativeHttpHandler(vi.fn());bridge.startLocalServerWorker();- expect(lastWorker().postMessage).toHaveBeenCalledWith(expect.objectContaining({ useNativeHttp: true }));+ expect(lastWorker().postMessage).toHaveBeenCalledWith(+ expect.objectContaining({ useNativeHttp: true }),+ [ expect.anything() ]+ );});});@@ -778,45 +785,93 @@ describe("leadership", () => {});describe("security settings", () => {- it("sends the change to the worker that holds the file, and answers what it wrote", async () => {+ /**+ * The worker's end of the security channel, handed over with INIT.+ *+ * A channel of its own rather than the worker's message handler, because that handler is+ * reachable from inside the worker: backend scripts run through `eval()` in its realm, so a+ * command sitting on `self.onmessage` is one a script can issue without the browser ever+ * drawing its confirmation dialog.+ */+ function securityPort(worker: MockWorker): MessagePort {+ const init = worker.postMessage.mock.calls+ .map(([message]) => message as { type: string; securityPort?: MessagePort })+ .find((message) => message.type === "INIT");+ if (!init?.securityPort) {+ throw new Error("INIT carried no security port");+ }+ return init.securityPort;+ }++ /** What the page sent over that channel, as the worker would see it. */+ type SecurityChange = { id: string; setting: string; enabled: boolean };++ function changesSentTo(port: MessagePort): Promise<SecurityChange[]> {+ const seen: SecurityChange[] = [];+ port.onmessage = (event) => {+ const msg = event.data as SecurityChange & { type: string };+ if (msg?.type === "SECURITY_SET") {+ seen.push(msg);+ }+ };+ return vi.waitFor(() => {+ expect(seen.length).toBeGreaterThan(0);+ return seen;+ });+ }++ it("sends the change over the port, and answers what the worker wrote", async () => {const bridge = await freshBridge();- const change = bridge.requestSecurityChange("backendScriptingEnabled", true);+ const port = securityPort(bridge.startLocalServerWorker() as unknown as MockWorker);+ const seen = changesSentTo(port);- 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");+ const change = bridge.requestSecurityChange("backendScriptingEnabled", true);+ const [ sent ] = await seen;expect(sent).toMatchObject({ setting: "backendScriptingEnabled", enabled: true });- worker.onmessage?.({ data: { type: "SECURITY_SET_RESULT", id: sent?.id, written: true } });+ port.postMessage({ type: "SECURITY_SET_RESULT", id: sent.id, written: true });await expect(change).resolves.toBe(true);});+ it("never puts the change on the worker's own message handler", async () => {+ const bridge = await freshBridge();+ const worker = bridge.startLocalServerWorker() as unknown as MockWorker;+ const seen = changesSentTo(securityPort(worker));++ bridge.requestSecurityChange("backendScriptingEnabled", true);+ await seen;++ // Only INIT ever goes to the worker itself. A SECURITY_SET there would be a command a+ // backend script could issue for itself, since eval() runs in the worker's realm.+ const toWorker = worker.postMessage.mock.calls+ .map(([message]) => (message as { type: string }).type);+ expect(toWorker).not.toContain("SECURITY_SET");+ });+it("answers no when the worker refused to write it", async () => {const bridge = await freshBridge();- const change = bridge.requestSecurityChange("sqlConsoleEnabled", true);+ const port = securityPort(bridge.startLocalServerWorker() as unknown as MockWorker);+ const seen = changesSentTo(port);- const worker = lastWorker();- const sent = worker.postMessage.mock.calls- .map(([message]) => message as { type: string; id: string })- .find((message) => message.type === "SECURITY_SET");+ const change = bridge.requestSecurityChange("sqlConsoleEnabled", true);+ const [ sent ] = await seen;// 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" } });+ port.postMessage({ 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 port = securityPort(bridge.startLocalServerWorker() as unknown as MockWorker);const change = bridge.requestSecurityChange("backendScriptingEnabled", true);- const worker = lastWorker();- worker.onmessage?.({ data: { type: "SECURITY_SET_RESULT", id: "some other change", written: true } });+ port.postMessage({ type: "SECURITY_SET_RESULT", id: "some other change", written: true });let settled = false;void change.then(() => { settled = true; });- await Promise.resolve();+ await new Promise((resolve) => setTimeout(resolve, 10));expect(settled).toBe(false);});diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex d00a4eaffd..a874690717 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -104,14 +104,19 @@ 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;+/**+ * The one channel a security setting can be written over, entangled with the worker at startup.+ * Not `self.onmessage`, which backend scripts can call: they run through `eval()` in the worker's+ * realm, which reaches its globals but not another module's bindings.+ */+let securityPort: MessagePort | null = null;+/*** 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.+ * The page cannot write that file itself: the lock is the whole point, see+ * `lightweight/security_settings.ts`. This deliberately avoids the request path too, since a route+ * would put the change behind the same API a frontend script already calls freely.** Only the leader tab has that worker. A follower is refused rather than served, as for a backup.*/@@ -120,7 +125,12 @@ export function requestSecurityChange(setting: string, enabled: boolean): Promisreturn Promise.resolve(false);}- const worker = startLocalServerWorker();+ startLocalServerWorker();+ const port = securityPort;+ if (!port) {+ return Promise.resolve(false);+ }+const id = Math.random().toString(36).slice(2);return new Promise((resolve) => {@@ -132,7 +142,7 @@ export function requestSecurityChange(setting: string, enabled: boolean): Promisconst timer = setTimeout(() => settle(false), SECURITY_CHANGE_TIMEOUT_MS);securityChanges.set(id, settle);- worker.postMessage({ type: "SECURITY_SET", id, setting, enabled });+ port.postMessage({ type: "SECURITY_SET", id, setting, enabled });});}@@ -429,11 +439,24 @@ export function registerNativeHttpHandler(handler: NativeHttpHandler) {export function startLocalServerWorker() {if (localWorker) return localWorker;localWorker = new LocalServerWorker();++ // Handed over with the worker's first message, before it has loaded a module of its own and+ // long before it can run a note's script. See `securityPort`.+ const security = new MessageChannel();+ securityPort = security.port1;+ securityPort.onmessage = (event) => {+ const msg = event.data;+ if (msg?.type === "SECURITY_SET_RESULT") {+ securityChanges.get(msg.id)?.(msg.written === true);+ }+ };+localWorker.postMessage({type: "INIT",queryString: location.search,- useNativeHttp: nativeHttpHandler != null- });+ useNativeHttp: nativeHttpHandler != null,+ securityPort: security.port2+ }, [ security.port2 ]);// Handle worker errors during initializationlocalWorker.onerror = (event) => {@@ -471,13 +494,6 @@ 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.spec.ts b/apps/standalone/src/local-server-worker.spec.tsindex ea39993254..bfbe8fa3de 100644--- a/apps/standalone/src/local-server-worker.spec.ts+++ b/apps/standalone/src/local-server-worker.spec.ts@@ -40,6 +40,56 @@ describe("local-server-worker.ts static imports", () => {});});+/**+ * Backend note scripts run through `eval()` inside this worker's realm, which makes every global+ * theirs to call — `self.onmessage` included. A command reachable that way is a command a script+ * can issue for itself, so the one that writes `security.json` must not live there: a startup+ * script could otherwise grant itself backend scripting again after the user turned it off, on+ * every boot, and the browser's confirmation dialog would never be drawn.+ *+ * It lives on a `MessagePort` the page transfers with INIT and this module keeps in its own scope+ * instead. Evaluated code sees the scope it was evaluated in and the worker's globals, and a+ * module-level binding here is neither.+ */+describe("the security command's reachability", () => {+ it("is off the worker's own message handler, which scripts can call", () => {+ const handler = selfOnMessageHandlerOf(WORKER_ENTRY);++ // The handler this found is the real one: a wrong node would carry no SECURITY_SET either,+ // and the assertion below would hold for the wrong reason.+ expect(handler).toContain("LOCAL_REQUEST");+ expect(handler).not.toContain("SECURITY_SET");+ });++ it("is on the port taken from INIT, which they cannot reach", () => {+ const source = readFileSync(WORKER_ENTRY, "utf8");++ expect(source).toContain("adoptSecurityPort(msg.securityPort)");+ expect(source).toContain("securityPort.onmessage");+ });+});++/** The text of the `self.onmessage` assignment, which is the worker's public message surface. */+function selfOnMessageHandlerOf(entryPath: string): string {+ const source = readFileSync(entryPath, "utf8");+ const sourceFile = ts.createSourceFile(entryPath, source, ts.ScriptTarget.Latest, true);++ let handler: string | null = null;+ for (const statement of sourceFile.statements) {+ if (!ts.isExpressionStatement(statement) || !ts.isBinaryExpression(statement.expression)) {+ continue;+ }+ if (statement.expression.left.getText(sourceFile) === "self.onmessage") {+ handler = statement.expression.right.getText(sourceFile);+ }+ }++ if (handler === null) {+ throw new Error("self.onmessage is not assigned in the worker entry");+ }+ return handler;+}+/** Module specifiers of every top-level static import that survives to runtime. */function staticValueImportsOf(entryPath: string): string[] {const source = readFileSync(entryPath, "utf8");diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex d0aac0623d..cc661e56ac 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -106,6 +106,13 @@ let messagingProvider: InstanceType<typeof WorkerMessagingProvider> | null = nul/** 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;+/**+ * The page's end of the security channel, taken from the INIT message. Not `self.onmessage`, which+ * backend scripts can call: they run through `eval()` in this worker's realm, which reaches its+ * globals but not another module's bindings.+ */+let securityPort: MessagePort | null = null;+// Core module, router, and initialization statelet coreModule: typeof import("@triliumnext/core") | null = null;let router: BrowserRouter | null = null;@@ -562,11 +569,35 @@ 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;+/**+ * Takes the page's end of the security channel, once, and answers what arrives on it. Once, because+ * the port is what proves a message came from the page: a second one could be substituted by+ * anything that reaches the INIT path.+ */+function adoptSecurityPort(port: MessagePort | undefined): void {+ if (securityPort || !port) {+ return;+ }++ securityPort = port;+ securityPort.onmessage = async (event) => {+ const msg = event.data;+ if (msg?.type !== "SECURITY_SET") {+ return;+ }++ // 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);+ };+}+/*** 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+ * Reached only over {@link securityPort}, which carries what `requestSecurityChange` sends after+ * the browser's own confirmation dialog. What arrives 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.*/@@ -577,7 +608,7 @@ function handleSecuritySet(id: string, setting: unknown, enabled: unknown): voidconsole.log(`[Worker] Security setting "${setting}" written; it applies from the next start.`);}- (self as unknown as Worker).postMessage({ type: "SECURITY_SET_RESULT", id, written });+ securityPort?.postMessage({ type: "SECURITY_SET_RESULT", id, written });}/**@@ -637,6 +668,7 @@ self.onmessage = async (event) => {if (msg.type === "INIT") {queryString = msg.queryString || "";useNativeHttp = msg.useNativeHttp || false;+ adoptSecurityPort(msg.securityPort);if (!initReceived) {initReceived = true;console.log("[Worker] Starting initialization...");@@ -665,14 +697,6 @@ 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/security_gate.spec.ts b/apps/standalone/src/security_gate.spec.tsindex 7e54f529a8..8c93e66cc7 100644--- a/apps/standalone/src/security_gate.spec.ts+++ b/apps/standalone/src/security_gate.spec.ts@@ -184,6 +184,44 @@ describe("a script that keeps asking", () => {expect(dialogs).toHaveLength(2);});+ it("never stands between the user and turning a capability back off", async () => {+ confirmed = false;+ const api = await loadGate();++ // Two declines, which is as far as asking to enable anything gets from here on.+ await api.setBackendScriptingEnabled(true);+ await api.setBackendScriptingEnabled(true);+ expect(dialogs).toHaveLength(2);+ await expect(api.setBackendScriptingEnabled(true)).resolves.toBe(false);+ expect(dialogs).toHaveLength(2);++ // Disabling is still asked about, and still works. A user who has just been pestered into+ // the limit is exactly the user who wants this, and a script that keeps asking for it can+ // achieve nothing worse than the capability being turned off.+ confirmed = true;+ await expect(api.setBackendScriptingEnabled(false)).resolves.toBe(true);+ expect(dialogs).toHaveLength(3);+ expect(bridge.calls).toEqual([ { setting: "backendScriptingEnabled", enabled: false } ]);+ });++ it("does not count a declined disable against the limit", async () => {+ confirmed = false;+ const api = await loadGate();++ await api.setBackendScriptingEnabled(false);+ await api.setSqlConsoleEnabled(false);+ await api.setBackendScriptingEnabled(false);++ // Three dialogs, where three declined *enable* requests would have produced two.+ expect(dialogs).toHaveLength(3);++ // And the enable path still has both of its dialogs left.+ await api.setBackendScriptingEnabled(true);+ await api.setBackendScriptingEnabled(true);+ await api.setBackendScriptingEnabled(true);+ expect(dialogs).toHaveLength(5);+ });+it("does not cost the user the toggle over one misclick", async () => {confirmed = false;const api = await loadGate();diff --git a/apps/standalone/src/security_gate.ts b/apps/standalone/src/security_gate.tsindex cc9d4b43bc..98546676c2 100644--- a/apps/standalone/src/security_gate.ts+++ b/apps/standalone/src/security_gate.ts@@ -20,7 +20,9 @@ import { requestSecurityChange } from "./local-bridge.js";* 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.+ * user down into clicking OK. One accidental Cancel does not cost the user the toggle, and the+ * limit covers granting only, so it can never stand between the user and turning a capability+ * back off.** @module*/@@ -51,14 +53,20 @@ export function createSecurityApi(): StandaloneSecurityApi {async function requestChange(setting: StandaloneSecuritySettingName, enabled: boolean): Promise<boolean> {- if (!nativeConfirm || asking || declines >= MAX_DECLINES || !hasUserActivation()) {+ // 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+ // than the user agreeing.+ const outOfDialogs = enabled && declines >= MAX_DECLINES;+ if (!nativeConfirm || asking || outOfDialogs || !hasUserActivation()) {return false;}asking = true;try {if (!nativeConfirm(await promptFor(setting, enabled))) {- declines++;+ if (enabled) {+ declines++;+ }return false;}