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(client): don't fire app requests on the login/set-password screens (#10589)
Elian Doran24eb70ba735a
diff --git a/apps/client/src/index.ts b/apps/client/src/index.tsindex a39765f4a8..bc7f9d6d9a 100644--- a/apps/client/src/index.ts+++ b/apps/client/src/index.ts@@ -89,8 +89,14 @@ function loadStylesheets() {const stylesheetsPath = `${assetPath}/stylesheets`;appendStylesheet({ href: `${stylesheetsPath}/ckeditor-theme.css` });- // Marked so it can be swapped when font options change without reloading.- document.head.appendChild(createFontStylesheetLink());+ // Marked so it can be swapped when font options change without reloading. Skipped on the+ // login / set-password pre-auth screens, where the /api/fonts request 401s (and, under nosniff,+ // surfaces as a MIME-type console error) — those screens use the theme's fonts (#10589). This is+ // the inline equivalent of utils.isPreAuthScreen(): index.ts runs before setupGlob() populates+ // window.glob, and utils.ts reads window.glob at module scope, so index.ts must not import utils.+ if (glob.loggedIn !== false && glob.passwordSet !== false) {+ document.head.appendChild(createFontStylesheetLink());+ }// The light theme is always loaded as the baseline and acts as the anchor for live theme swapping.appendStylesheet({ href: `${stylesheetsPath}/theme-light.css` }, { base: true });for (const ref of buildThemeStylesheetRefs(theme, customThemeCssUrl, themeBase)) {diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.tsindex e75966f6f5..4be564d921 100644--- a/apps/client/src/services/froca.ts+++ b/apps/client/src/services/froca.ts@@ -6,6 +6,7 @@ import FBranch, { type FBranchRow } from "../entities/fbranch.js";import FNote, { type FNoteRow } from "../entities/fnote.js";import type { Froca } from "./froca-interface.js";import server from "./server.js";+import { isPreAuthScreen } from "./utils.js";interface SubtreeResponse {notes: FNoteRow[];@@ -44,7 +45,9 @@ class FrocaImpl implements Froca {}async loadInitialTree() {- if (!glob.dbInitialized) return;+ // Skip on the setup screen (!dbInitialized) and on the login / set-password pre-auth+ // screens (isPreAuthScreen) — otherwise this fires an unauthenticated GET /api/tree (#10589).+ if (!glob.dbInitialized || isPreAuthScreen()) return;const resp = await server.get<SubtreeResponse>("tree");// clear the cache only directly before adding new content which is important for e.g., switching to protected sessiondiff --git a/apps/client/src/services/keyboard_actions.ts b/apps/client/src/services/keyboard_actions.tsindex ee22c12eb7..f55de3791a 100644--- a/apps/client/src/services/keyboard_actions.ts+++ b/apps/client/src/services/keyboard_actions.ts@@ -2,22 +2,27 @@ import server from "./server.js";import appContext from "../components/app_context.js";import { formatShortcut, joinShortcut } from "./keyboard_shortcut_display.js";import shortcutService, { ShortcutBinding } from "./shortcuts.js";+import { isPreAuthScreen } from "./utils.js";import type Component from "../components/component.js";import type { ActionKeyboardShortcut } from "@triliumnext/commons";const keyboardActionRepo: Record<string, ActionKeyboardShortcut> = {};-const keyboardActionsLoaded = server.get<ActionKeyboardShortcut[]>("keyboard-actions").then((actions) => {- actions = actions.filter((a) => !!a.actionName); // filter out separators+// Skip on the login / set-password pre-auth screens, where an unauthenticated+// GET /api/keyboard-actions would 401 (#10589); those screens bind no shortcuts.+const keyboardActionsLoaded: Promise<ActionKeyboardShortcut[]> = isPreAuthScreen()+ ? Promise.resolve([])+ : server.get<ActionKeyboardShortcut[]>("keyboard-actions").then((actions) => {+ actions = actions.filter((a) => !!a.actionName); // filter out separators- for (const action of actions) {- action.effectiveShortcuts = (action.effectiveShortcuts ?? []).filter((shortcut) => !shortcut.startsWith("global:"));+ for (const action of actions) {+ action.effectiveShortcuts = (action.effectiveShortcuts ?? []).filter((shortcut) => !shortcut.startsWith("global:"));- keyboardActionRepo[action.actionName] = action;- }+ keyboardActionRepo[action.actionName] = action;+ }- return actions;-});+ return actions;+ });async function getActions() {return await keyboardActionsLoaded;diff --git a/apps/client/src/services/options.ts b/apps/client/src/services/options.tsindex 06b7cde470..b91fab8d8b 100644--- a/apps/client/src/services/options.ts+++ b/apps/client/src/services/options.ts@@ -1,6 +1,7 @@import { OptionNames } from "@triliumnext/commons";+import server from "./server.js";-import { isShare } from "./utils.js";+import { isPreAuthScreen, isShare } from "./utils.js";export type OptionValue = number | string;@@ -9,7 +10,9 @@ class Options {private arr!: Record<string, OptionValue>;constructor() {- if (!isShare) {+ // Don't fetch on the share view, nor on the login / set-password pre-auth screens, where an+ // unauthenticated GET /api/options would 401 (#10589). Options aren't needed to render those.+ if (!isShare && !isPreAuthScreen()) {this.initializedPromise = server.get<Record<string, OptionValue>>("options").then((data) => this.load(data));} else {this.initializedPromise = Promise.resolve();diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.tsindex 8d5d4b5408..e89d5bcefd 100644--- a/apps/client/src/services/utils.spec.ts+++ b/apps/client/src/services/utils.spec.ts@@ -18,6 +18,7 @@ import utils, {isLaunchBarConfig,isMac,isMobileApp,+ isPreAuthScreen,isPWA,isUpdateAvailable,mapToKeyValueArray,@@ -912,3 +913,42 @@ describe("openInReusableSplit / openInAppHelpFromUrl", () => {expect(setNote).toHaveBeenCalledWith("_help_MyPage", { viewScope: { viewMode: "contextual-help" } });});});++describe("isPreAuthScreen", () => {+ const originalGlob = window.glob;++ afterEach(() => {+ window.glob = originalGlob;+ });++ function setGlob(patch: Record<string, unknown>) {+ // The eager module-load side effects (froca tree load, ws connect, options /+ // keyboard-actions / fonts fetches) read `glob` directly; we only need the auth flags here.+ window.glob = { isMainWindow: true, ...patch } as typeof window.glob;+ }++ it("flags the login screen (loggedIn:false) so eager loads skip their unauthenticated calls", () => {+ setGlob({ dbInitialized: true, loggedIn: false });+ expect(isPreAuthScreen()).toBe(true);+ });++ it("flags the set-password screen (passwordSet:false)", () => {+ setGlob({ dbInitialized: true, passwordSet: false });+ expect(isPreAuthScreen()).toBe(true);+ });++ it("does NOT flag the setup screen — froca/ws already gate on !dbInitialized and the server permits pre-init requests", () => {+ setGlob({ dbInitialized: false });+ expect(isPreAuthScreen()).toBe(false);+ });++ it("does NOT flag the fully authenticated app", () => {+ setGlob({ dbInitialized: true, loggedIn: true, passwordSet: true });+ expect(isPreAuthScreen()).toBe(false);+ });++ it("does NOT flag an unset glob (unit-test / unknown state) — strict === false keeps eager loads working", () => {+ setGlob({});+ expect(isPreAuthScreen()).toBe(false);+ });+});diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 3a3ff3bc64..093bf86fa8 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -7,6 +7,26 @@ const SVG_MIME = "image/svg+xml";export const isShare = !window.glob;+/**+ * True when the client is showing one of the DB-initialized *pre-auth* SPA screens — the login+ * screen (`loggedIn: false`) or the set-password screen (`passwordSet: false`).+ *+ * These screens run with the database already initialized, so `glob.dbInitialized` (the historical+ * proxy for "pre-auth", back when setup was the only pre-auth screen) does NOT catch them. The eager+ * module-load side effects — froca's initial tree load, the WebSocket auto-connect, and the options /+ * keyboard-actions / fonts fetches — must skip on these screens too, otherwise they fire+ * unauthenticated requests that 401 with "Logged in session not found" (#10589).+ *+ * The setup screen (`dbInitialized: false`) is deliberately NOT flagged here: froca and the WebSocket+ * already gate on `!glob.dbInitialized`, and the options / keyboard-actions / fonts requests are+ * accepted unauthenticated server-side while the DB is uninitialized. The strict `=== false`+ * comparison is intentional: an unset flag (the fully-authenticated app, or a unit-test `glob`) must+ * not be treated as pre-auth, so the eager loads keep working there.+ */+export function isPreAuthScreen(): boolean {+ return glob.loggedIn === false || glob.passwordSet === false;+}+export function reloadFrontendApp(reason?: string) {if (reason) {logInfo(`Frontend app reload: ${reason}`);diff --git a/apps/client/src/services/ws.ts b/apps/client/src/services/ws.tsindex 5f37a309b9..d54f07abff 100644--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@ -9,7 +9,7 @@ import { t } from "./i18n.js";import options from "./options.js";import server from "./server.js";import toastService from "./toast.js";-import utils from "./utils.js";+import utils, { isPreAuthScreen } from "./utils.js";type MessageHandler = (message: WebSocketMessage) => void;let messageHandlers: MessageHandler[] = [];@@ -310,7 +310,10 @@ async function sendPing() {setTimeout(() => {if (glob.device === "print") return;- if (!glob.dbInitialized) return;+ // Skip on the setup screen (!dbInitialized) and on the login / set-password pre-auth+ // screens (isPreAuthScreen) — otherwise the browser opens a WebSocket it isn't authorised+ // for, which the server refuses (#10589).+ if (!glob.dbInitialized || isPreAuthScreen()) return;if (glob.isStandalone) {// In standalone mode, listen for messages from the local worker via custom event