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(core): read the environment through the platform provider
Elian Dorana702e65c451c
diff --git a/packages/trilium-core/src/routes/api/script.spec.ts b/packages/trilium-core/src/routes/api/script.spec.tsindex dccdf28075..81cdfedd38 100644--- a/packages/trilium-core/src/routes/api/script.spec.ts+++ b/packages/trilium-core/src/routes/api/script.spec.ts@@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport attributeService from "../../services/attributes";import config from "../../services/config";+import { getPlatform } from "../../services/platform";import scriptService from "../../services/script";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";@@ -22,6 +23,17 @@ async function createCodeNote(content: string): Promise<string> {return res.body.note.noteId;}+/**+ * Turns safe mode on, through the platform provider that owns it.+ *+ * `process.env` is not that provider on every runtime: the browser build has no `process` and takes+ * the value from a `?safeMode` URL parameter, so a spec that set the variable directly would leave+ * the branch untested there. Undone by the `vi.restoreAllMocks()` in `afterEach`.+ */+function enterSafeMode() {+ vi.spyOn(getPlatform(), "getEnv").mockImplementation((key) => (key === "TRILIUM_SAFE_MODE" ? "1" : undefined));+}+describe("Script API (core)", () => {// Script execution enforces the backendScriptingEnabled security toggle (default false).const originalScriptingEnabled = config.Security.backendScriptingEnabled;@@ -132,14 +144,15 @@ describe("Script API (core)", () => {});it("returns no bundles in safe mode", async () => {- vi.stubEnv("TRILIUM_SAFE_MODE", "1");- try {- const res = await api.get<unknown[]>("/api/script/startup");- expect(res.status).toBe(200);- expect(res.body).toEqual([]);- } finally {- vi.unstubAllEnvs();- }+ // Seeded with a bundle the route would otherwise return, so an empty answer can only+ // have come from the safe-mode branch.+ vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([{ noteId: "s" } as any]);+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockReturnValue({ script: "s" } as any);+ enterSafeMode();++ const res = await api.get<unknown[]>("/api/script/startup");+ expect(res.status).toBe(200);+ expect(res.body).toEqual([]);});});@@ -154,14 +167,13 @@ describe("Script API (core)", () => {});it("returns no widget bundles in safe mode", async () => {- vi.stubEnv("TRILIUM_SAFE_MODE", "1");- try {- const res = await api.get<unknown[]>("/api/script/widgets");- expect(res.status).toBe(200);- expect(res.body).toEqual([]);- } finally {- vi.unstubAllEnvs();- }+ vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([{ noteId: "w" } as any]);+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockReturnValue({ script: "w" } as any);+ enterSafeMode();++ const res = await api.get<unknown[]>("/api/script/widgets");+ expect(res.status).toBe(200);+ expect(res.body).toEqual([]);});});diff --git a/packages/trilium-core/src/routes/api/script.ts b/packages/trilium-core/src/routes/api/script.tsindex bc9a182111..15ebabf90b 100644--- a/packages/trilium-core/src/routes/api/script.ts+++ b/packages/trilium-core/src/routes/api/script.ts@@ -4,6 +4,7 @@ import type { Request } from "express";import becca from "../../becca/becca.js";import attributeService from "../../services/attributes.js";+import { getPlatform } from "../../services/platform.js";import scriptService, { type Bundle } from "../../services/script.js";import syncService from "../../services/sync.js";import { assertScriptingEnabled } from "../../services/scripting_guard.js";@@ -72,7 +73,7 @@ function getBundlesWithLabel(label: string, value?: string) {}function getStartupBundles(req: Request) {- if (!process.env.TRILIUM_SAFE_MODE) {+ if (!getPlatform().getEnv("TRILIUM_SAFE_MODE")) {if (req.query.mobile === "true") {return getBundlesWithLabel("run", "mobileStartup");}@@ -83,7 +84,7 @@ function getStartupBundles(req: Request) {}function getWidgetBundles() {- if (!process.env.TRILIUM_SAFE_MODE) {+ if (!getPlatform().getEnv("TRILIUM_SAFE_MODE")) {return getBundlesWithLabel("widget");}return [];diff --git a/packages/trilium-core/src/services/bootstrap_utils.spec.ts b/packages/trilium-core/src/services/bootstrap_utils.spec.tsindex 0dae2544c3..4bb08e99a4 100644--- a/packages/trilium-core/src/services/bootstrap_utils.spec.ts+++ b/packages/trilium-core/src/services/bootstrap_utils.spec.ts@@ -5,6 +5,7 @@ import getSharedBootstrapItems, { getIconConfig } from "./bootstrap_utils.js";import * as cls from "./context.js";import notes from "./notes.js";import options from "./options.js";+import { getPlatform } from "./platform.js";import { enterSetupMode, leaveSetupMode } from "./setup_mode.js";import sqlInit from "./sql_init.js";@@ -142,6 +143,31 @@ describe("bootstrap_utils (real DB)", () => {expect(items.themeBase).toBe("next-dark");});+ it("withholds both custom theme URLs in safe mode", () => {+ cls.init(() => {+ const { note } = notes.createNewNote({+ parentNoteId: "root",+ title: "Custom Theme",+ content: "body {}",+ type: "code",+ mime: "text/css"+ });+ attributes.createLabel(note.noteId, "appTheme", "mySafeModeTheme");+ });++ // Safe mode reaches core through the platform provider rather than `process.env`: the+ // browser build has no `process` and takes the value from a `?safeMode` URL parameter.+ const envSpy = vi.spyOn(getPlatform(), "getEnv")+ .mockImplementation((key) => (key === "TRILIUM_SAFE_MODE" ? "1" : undefined));+ try {+ const items = fullPayload("mySafeModeTheme");+ expect(items.themeCssUrl).toBe(false);+ expect(items.customThemeCssUrl).toBeUndefined();+ } finally {+ envSpy.mockRestore();+ }+ });+it("falls back to the baseline light theme for an unknown theme with no matching note", () => {const items = fullPayload("ghostThemeWithoutNote");expect(items.themeCssUrl).toBe(false);diff --git a/packages/trilium-core/src/services/bootstrap_utils.ts b/packages/trilium-core/src/services/bootstrap_utils.tsindex d1276c1966..1f6f0726c4 100644--- a/packages/trilium-core/src/services/bootstrap_utils.ts+++ b/packages/trilium-core/src/services/bootstrap_utils.ts@@ -119,7 +119,7 @@ function getCustomThemeCssUrl(theme: string, themeNote: BNote | null) {return undefined;}- if (!process.env.TRILIUM_SAFE_MODE && themeNote) {+ if (!getPlatform().getEnv("TRILIUM_SAFE_MODE") && themeNote) {return `api/notes/download/${themeNote.noteId}`;}diff --git a/packages/trilium-core/src/services/migration.ts b/packages/trilium-core/src/services/migration.tsindex 271410f615..cbebd74292 100644--- a/packages/trilium-core/src/services/migration.ts+++ b/packages/trilium-core/src/services/migration.ts@@ -142,8 +142,9 @@ async function migrateIfNecessary() {}if (!isDbUpToDate()) {- if (process.env.TRILIUM_MANUAL_DB_MIGRATION === "true") {- await getPlatform().crash(t("migration.automatic_migrations_disabled", { envVarValue: process.env.TRILIUM_MANUAL_DB_MIGRATION}));+ const manualMigration = getPlatform().getEnv("TRILIUM_MANUAL_DB_MIGRATION");+ if (manualMigration === "true") {+ await getPlatform().crash(t("migration.automatic_migrations_disabled", { envVarValue: manualMigration }));return;}await migrate();diff --git a/packages/trilium-core/src/services/scheduler.spec.ts b/packages/trilium-core/src/services/scheduler.spec.tsindex 89ad608d11..a70ccfaea2 100644--- a/packages/trilium-core/src/services/scheduler.spec.ts+++ b/packages/trilium-core/src/services/scheduler.spec.ts@@ -7,6 +7,7 @@ import config from "./config.js";import events from "./events.js";import hiddenSubtreeService from "./hidden_subtree.js";import options from "./options.js";+import { getPlatform } from "./platform.js";import protected_session from "./protected_session.js";import { startScheduler } from "./scheduler.js";import scriptService from "./script.js";@@ -44,10 +45,20 @@ function buildBackendScript() {return buildNote({ type: "code", mime: "application/javascript;env=backend", content: "" });}+/**+ * Sets what `TRILIUM_SAFE_MODE` reads as, through the platform provider that owns it.+ *+ * `process.env` is not that provider on every runtime: the browser build has no `process` and takes+ * the value from a `?safeMode` URL parameter, so a spec that sets the variable directly would leave+ * the branch untested there.+ */+function stubSafeMode(value?: string) {+ vi.spyOn(getPlatform(), "getEnv").mockImplementation((key) => (key === "TRILIUM_SAFE_MODE" ? value : undefined));+}+describe("scheduler", () => {const originalScriptingEnabled = config.Security.backendScriptingEnabled;const originalInstanceName = config.General.instanceName;- const originalSafeMode = process.env.TRILIUM_SAFE_MODE;let getNotesWithLabel: ReturnType<typeof vi.spyOn>;let executeNoteNoException: ReturnType<typeof vi.spyOn>;@@ -66,7 +77,7 @@ describe("scheduler", () => {config.Security.backendScriptingEnabled = true;config.General.instanceName = "";- delete process.env.TRILIUM_SAFE_MODE;+ stubSafeMode();getNotesWithLabel = vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([]);executeNoteNoException = vi.spyOn(scriptService, "executeNoteNoException").mockImplementation(() => {});@@ -85,11 +96,6 @@ describe("scheduler", () => {vi.restoreAllMocks();config.Security.backendScriptingEnabled = originalScriptingEnabled;config.General.instanceName = originalInstanceName;- if (originalSafeMode === undefined) {- delete process.env.TRILIUM_SAFE_MODE;- } else {- process.env.TRILIUM_SAFE_MODE = originalSafeMode;- }});it("runs backendStartup, hourly and daily scripts on their timers when scripting is enabled", async () => {@@ -145,7 +151,7 @@ describe("scheduler", () => {});it("does not schedule script timers in safe mode", async () => {- process.env.TRILIUM_SAFE_MODE = "1";+ stubSafeMode("1");startScheduler();await settleDbReady();diff --git a/packages/trilium-core/src/services/scheduler.ts b/packages/trilium-core/src/services/scheduler.tsindex 3a807d00da..33f648d764 100644--- a/packages/trilium-core/src/services/scheduler.ts+++ b/packages/trilium-core/src/services/scheduler.ts@@ -7,6 +7,7 @@ import hiddenSubtreeService from "./hidden_subtree.js";import { reconcileLanguageAfterDbInit } from "./i18n.js";import { getLog } from "./log.js";import options from "./options.js";+import { getPlatform } from "./platform.js";import protected_session from "./protected_session.js";import scriptService from "./script.js";import { isScriptingEnabled } from "./scripting_guard.js";@@ -61,7 +62,7 @@ export function startScheduler() {// Periodic checks.sqlInit.dbReady.then(() => {- if (!process.env.TRILIUM_SAFE_MODE && isScriptingEnabled()) {+ if (!getPlatform().getEnv("TRILIUM_SAFE_MODE") && isScriptingEnabled()) {setTimeout(cls.wrap(() => runNotesWithLabel("backendStartup")),10 * 1000