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(desktop): serve WebSocket to browser clients when LAN access is on (#10589)
Elian Doran6ac0df8be805
diff --git a/apps/desktop/src/composite_messaging_provider.spec.ts b/apps/desktop/src/composite_messaging_provider.spec.tsnew file mode 100644index 0000000000..023fdc5cff--- /dev/null+++ b/apps/desktop/src/composite_messaging_provider.spec.ts@@ -0,0 +1,103 @@+import type { WebSocketMessage } from "@triliumnext/commons";+import type { ClientMessageHandler } from "@triliumnext/core";+import type WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";+import type express from "express";+import type { Server as HttpServer } from "http";+import { describe, expect, it, vi } from "vitest";++import CompositeMessagingProvider from "./composite_messaging_provider.js";+import type IpcMessagingProvider from "./ipc_messaging_provider.js";++/** Minimal stand-in for one leg of the composite that records interactions and+ * lets the test drive the registered client-message handler. */+function makeFakeLeg() {+ let handler: ClientMessageHandler | undefined;+ return {+ setClientMessageHandler: vi.fn((h: ClientMessageHandler) => { handler = h; }),+ sendMessageToAllClients: vi.fn(),+ sendMessageToClient: vi.fn(() => true),+ getClientCount: vi.fn(() => 0),+ dispose: vi.fn(),+ attachToHttpServer: vi.fn(),+ /** Simulate an inbound message arriving on this transport. */+ emit(id: string, message: unknown) { void handler?.(id, message); }+ };+}++const MESSAGE = { type: "ping" } as unknown as WebSocketMessage;++function build() {+ const ipc = makeFakeLeg();+ const ws = makeFakeLeg();+ const composite = new CompositeMessagingProvider(+ ipc as unknown as IpcMessagingProvider,+ ws as unknown as WebSocketMessagingProvider+ );+ return { ipc, ws, composite };+}++describe("CompositeMessagingProvider", () => {+ it("namespaces inbound client IDs per transport", () => {+ const { ipc, ws, composite } = build();+ const received: Array<[string, unknown]> = [];+ composite.setClientMessageHandler((id, msg) => { received.push([id, msg]); });++ ipc.emit("5", MESSAGE);+ ws.emit("abc123", MESSAGE);++ expect(received).toEqual([+ ["ipc:5", MESSAGE],+ ["ws:abc123", MESSAGE]+ ]);+ });++ it("broadcasts to both transports", () => {+ const { ipc, ws, composite } = build();+ composite.sendMessageToAllClients(MESSAGE);++ expect(ipc.sendMessageToAllClients).toHaveBeenCalledWith(MESSAGE);+ expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(MESSAGE);+ });++ it("routes a per-client reply back over the transport it arrived on", () => {+ const { ipc, ws, composite } = build();++ expect(composite.sendMessageToClient("ipc:5", MESSAGE)).toBe(true);+ expect(ipc.sendMessageToClient).toHaveBeenCalledWith("5", MESSAGE);+ expect(ws.sendMessageToClient).not.toHaveBeenCalled();++ expect(composite.sendMessageToClient("ws:abc123", MESSAGE)).toBe(true);+ expect(ws.sendMessageToClient).toHaveBeenCalledWith("abc123", MESSAGE);+ });++ it("returns false for an unroutable client ID without touching either leg", () => {+ const { ipc, ws, composite } = build();++ expect(composite.sendMessageToClient("bogus", MESSAGE)).toBe(false);+ expect(ipc.sendMessageToClient).not.toHaveBeenCalled();+ expect(ws.sendMessageToClient).not.toHaveBeenCalled();+ });++ it("sums client counts and disposes both legs", () => {+ const { ipc, ws, composite } = build();+ ipc.getClientCount.mockReturnValue(2);+ ws.getClientCount.mockReturnValue(3);++ expect(composite.getClientCount()).toBe(5);++ composite.dispose();+ expect(ipc.dispose).toHaveBeenCalled();+ expect(ws.dispose).toHaveBeenCalled();+ });++ it("attaches only the WebSocket leg to the HTTP server", () => {+ const { ipc, ws, composite } = build();+ const httpServer = {} as unknown as HttpServer;+ const sessionParser = (() => {}) as unknown as express.RequestHandler;++ composite.attachToHttpServer(httpServer, sessionParser);++ expect(ws.attachToHttpServer).toHaveBeenCalledWith(httpServer, sessionParser);+ expect(ipc.attachToHttpServer).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/composite_messaging_provider.ts b/apps/desktop/src/composite_messaging_provider.tsnew file mode 100644index 0000000000..175b1e4a40--- /dev/null+++ b/apps/desktop/src/composite_messaging_provider.ts@@ -0,0 +1,65 @@+import type { WebSocketMessage } from "@triliumnext/commons";+import type { ClientMessageHandler, MessagingProvider } from "@triliumnext/core";+import type WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";+import type express from "express";+import type { Server as HttpServer } from "http";++import type IpcMessagingProvider from "./ipc_messaging_provider.js";++// Client IDs are namespaced per transport so a per-client reply is routed back over+// the same transport it arrived on. The IPC provider keys clients by numeric+// webContents id and the WS provider by a random string, so these prefixes are the+// only thing that reliably disambiguates them.+const IPC_PREFIX = "ipc:";+const WS_PREFIX = "ws:";++/**+ * Fans server→client messaging out across BOTH transports the desktop can serve:+ * - the Electron-IPC channel to the trusted renderer window(s), and+ * - a WebSocket endpoint on the TCP HTTP listener for browser clients.+ *+ * The WS half exists only when the user has opted into LAN/network access (see+ * `apps/desktop/src/main.ts`); without it the desktop uses `IpcMessagingProvider`+ * alone and no WS port is bound. www.ts hands this provider the `http.Server` via+ * `attachToHttpServer()` (detected through the HttpAttachable capability), which we+ * forward to the wrapped WS provider.+ */+export default class CompositeMessagingProvider implements MessagingProvider {+ constructor(+ private readonly ipc: IpcMessagingProvider,+ private readonly ws: WebSocketMessagingProvider+ ) {}++ attachToHttpServer(httpServer: HttpServer, sessionParser: express.RequestHandler): void {+ this.ws.attachToHttpServer(httpServer, sessionParser);+ }++ setClientMessageHandler(handler: ClientMessageHandler): void {+ this.ipc.setClientMessageHandler((id, message) => handler(`${IPC_PREFIX}${id}`, message));+ this.ws.setClientMessageHandler((id, message) => handler(`${WS_PREFIX}${id}`, message));+ }++ sendMessageToAllClients(message: WebSocketMessage): void {+ this.ipc.sendMessageToAllClients(message);+ this.ws.sendMessageToAllClients(message);+ }++ sendMessageToClient(clientId: string, message: WebSocketMessage): boolean {+ if (clientId.startsWith(IPC_PREFIX)) {+ return this.ipc.sendMessageToClient(clientId.slice(IPC_PREFIX.length), message);+ }+ if (clientId.startsWith(WS_PREFIX)) {+ return this.ws.sendMessageToClient(clientId.slice(WS_PREFIX.length), message);+ }+ return false;+ }++ getClientCount(): number {+ return (this.ipc.getClientCount?.() ?? 0) + (this.ws.getClientCount?.() ?? 0);+ }++ dispose(): void {+ this.ipc.dispose?.();+ this.ws.dispose?.();+ }+}diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex c70754d86d..3be7ce5b30 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -647,6 +647,25 @@ describe("security settings override", () => {};expect(config.Security.allowLanAccess).toBe(true);});++ it("uses an IPC-only messaging provider (no WebSocket endpoint) when LAN access is off", async () => {+ h.securitySettings = { allowLanAccess: false };+ const { main } = await importMain();+ await main();+ // An IPC-only provider is not HTTP-attachable, so www.ts binds no WS port.+ const messaging = h.initConfig?.messaging as { attachToHttpServer?: unknown };+ expect(messaging).toBeDefined();+ expect(typeof messaging.attachToHttpServer).not.toBe("function");+ });++ it("adds a WebSocket transport (composite) when LAN access is on", async () => {+ h.securitySettings = { allowLanAccess: true };+ const { main } = await importMain();+ await main();+ // The composite is HTTP-attachable; www.ts binds the WS endpoint for browsers.+ const messaging = h.initConfig?.messaging as { attachToHttpServer?: unknown };+ expect(typeof messaging.attachToHttpServer).toBe("function");+ });});describe("initializeCore dbConfig callbacks + getDemoArchive", () => {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex d1b9ec8857..e42ded163e 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -9,6 +9,7 @@ import config from "@triliumnext/server/src/services/config.js";import dataDirs from "@triliumnext/server/src/services/data_dir.js";import port from "@triliumnext/server/src/services/port.js";import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";+import WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";import { app, BrowserWindow,globalShortcut } from "electron";@@ -21,6 +22,7 @@ import path, { join, resolve } from "path";import { deferred, LOCALES } from "../../../packages/commons/src";import { PRODUCT_NAME } from "./app-info";+import CompositeMessagingProvider from "./composite_messaging_provider";import IpcMessagingProvider from "./ipc_messaging_provider";import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";@@ -191,12 +193,22 @@ export async function main() {}// The IPC provider just registers an `ipcMain.on` listener; no TCP socket- // or session parser needed, so we can init it here (before startTriliumServer)- // instead of going through www.ts. www.ts then only knows about the- // socket-bound WebSocket provider.+ // or session parser needed, so we can init it here (before startTriliumServer).+ // It's the messaging channel to the trusted renderer window(s).const ipcMessaging = new IpcMessagingProvider();ipcMessaging.init();+ // Browser clients (accessing the desktop's HTTP listener directly) can't use the+ // IPC channel, so they need a WebSocket endpoint for live updates. We only expose+ // one when the user has opted into LAN/network access (`allowLanAccess`, already+ // applied to config above) — otherwise the renderer's IPC channel is the sole+ // transport and no WS port is bound. When enabled, the composite serves both: IPC+ // for the renderer and WS for browsers. www.ts attaches the WS server (it owns the+ // http.Server + session parser) via attachToHttpServer().+ const messaging = config.Security.allowLanAccess+ ? new CompositeMessagingProvider(ipcMessaging, new WebSocketMessagingProvider())+ : ipcMessaging;+await initializeCore({dbConfig: {provider: dbProvider,@@ -222,7 +234,7 @@ export async function main() {zipExportProviderFactory: (await import("@triliumnext/server/src/services/export/zip/factory.js")).serverZipExportProviderFactory,request: new ElectronRequestProvider(),executionContext: new ClsHookedExecutionContext(),- messaging: ipcMessaging,+ messaging,schema: loadCoreSchema(),platform: new DesktopPlatformProvider(),translations: (await import("@triliumnext/server/src/services/i18n.js")).initializeTranslations,diff --git a/apps/server/src/services/ws_messaging_provider.spec.ts b/apps/server/src/services/ws_messaging_provider.spec.tsindex 7201e3522b..797f1e3cbd 100644--- a/apps/server/src/services/ws_messaging_provider.spec.ts+++ b/apps/server/src/services/ws_messaging_provider.spec.ts@@ -54,7 +54,7 @@ vi.mock("@triliumnext/core", async () => {return { getLog: () => getLogMock, shouldLogMessage };});-import WebSocketMessagingProvider from "./ws_messaging_provider.js";+import WebSocketMessagingProvider, { isHttpAttachableMessagingProvider } from "./ws_messaging_provider.js";function makeSocket(readyState = OPEN) {const handlers: Record<string, Handler> = {};@@ -92,10 +92,20 @@ describe("WebSocketMessagingProvider", () => {vi.restoreAllMocks();});+ it("is recognised as HTTP-attachable (the capability www.ts gates the WS server on)", () => {+ expect(isHttpAttachableMessagingProvider(provider)).toBe(true);+ // A plain IPC-style provider without attachToHttpServer must not qualify.+ expect(isHttpAttachableMessagingProvider({+ sendMessageToAllClients() {},+ sendMessageToClient: () => false,+ setClientMessageHandler() {}+ })).toBe(false);+ });+function init() {const httpServer = {} as any;const sessionParser = vi.fn((_req: any, _params: any, cb: () => void) => cb());- provider.init(httpServer, sessionParser as any);+ provider.attachToHttpServer(httpServer, sessionParser as any);return { server: state.instances[0], sessionParser };}diff --git a/apps/server/src/services/ws_messaging_provider.ts b/apps/server/src/services/ws_messaging_provider.tsindex 1a59b7de17..5ded6690c0 100644--- a/apps/server/src/services/ws_messaging_provider.ts+++ b/apps/server/src/services/ws_messaging_provider.ts@@ -9,22 +9,39 @@ import { randomString } from "./utils.js";type SessionParser = (req: IncomingMessage, params: {}, cb: () => void) => void;+/**+ * A messaging provider that serves clients over the TCP HTTP listener and so+ * needs the `http.Server` (and session parser for auth) handed to it once www.ts+ * has built them. www.ts detects this capability via the type guard below rather+ * than a concrete `instanceof`, so a desktop composite that wraps a WS provider+ * qualifies too.+ */+export interface HttpAttachableMessagingProvider extends MessagingProvider {+ attachToHttpServer(httpServer: HttpServer, sessionParser: express.RequestHandler): void;+}++export function isHttpAttachableMessagingProvider(provider: MessagingProvider): provider is HttpAttachableMessagingProvider {+ return typeof (provider as Partial<HttpAttachableMessagingProvider>).attachToHttpServer === "function";+}+/*** WebSocket-based implementation of MessagingProvider.** Handles the raw WebSocket transport: server setup, connection management,* message serialization, and client tracking.*- * Note: this provider is no longer used by the Electron desktop build —- * desktop runs IpcMessagingProvider instead so the renderer↔server messaging- * channel never crosses a TCP socket. See `apps/server/src/main.ts`.+ * Used directly by the server build, and by the Electron desktop build only when+ * the user has opted into LAN/network access — there it's wrapped in a composite+ * alongside the IPC provider so browser clients get live updates while the trusted+ * renderer keeps talking over IPC. Without that opt-in the desktop binds no WS+ * endpoint. See `apps/desktop/src/composite_messaging_provider.ts`.*/-export default class WebSocketMessagingProvider implements MessagingProvider {+export default class WebSocketMessagingProvider implements HttpAttachableMessagingProvider {private webSocketServer!: WebSocketServer;private clientMap = new Map<string, WebSocket>();private clientMessageHandler?: ClientMessageHandler;- init(httpServer: HttpServer, sessionParser: express.RequestHandler) {+ attachToHttpServer(httpServer: HttpServer, sessionParser: express.RequestHandler) {this.webSocketServer = new WebSocketServer({verifyClient: (info, done) => {sessionParser(info.req as express.Request, {} as express.Response, () => {diff --git a/apps/server/src/www.ts b/apps/server/src/www.tsindex f238204cd1..471effe834 100644--- a/apps/server/src/www.ts+++ b/apps/server/src/www.ts@@ -13,7 +13,7 @@ import host from "./services/host.js";import port from "./services/port.js";import { isScriptingEnabled } from "./services/scripting_guard.js";import { getDbSize } from "./services/sql_init.js";-import WebSocketMessagingProvider from "./services/ws_messaging_provider.js";+import { isHttpAttachableMessagingProvider } from "./services/ws_messaging_provider.js";const MINIMUM_NODE_VERSION = "20.0.0";@@ -79,14 +79,15 @@ export default async function startTriliumServer(): Promise<Express> {const app = await buildApp();const httpServer = startHttpServer(app);- // Only the WS provider needs the HTTP server and session parser; other- // providers (e.g. the Electron-IPC provider from apps/desktop) are- // initialised by their owning app before startup. Gating on the concrete- // type keeps www.ts platform-agnostic.+ // Only providers that serve clients over the TCP listener need the HTTP server+ // and session parser (the server's WebSocket provider, or the desktop composite+ // when LAN access is on). A pure Electron-IPC provider isn't HTTP-attachable, so+ // it's skipped here and no WS endpoint is bound. Gating on the capability rather+ // than a concrete type keeps www.ts platform-agnostic.const messaging = getMessagingProvider();- if (messaging instanceof WebSocketMessagingProvider) {+ if (isHttpAttachableMessagingProvider(messaging)) {const sessionParser = (await import("./routes/session_parser.js")).default;- messaging.init(httpServer, sessionParser);+ messaging.attachToHttpServer(httpServer, sessionParser);}const { ws } = await import("@triliumnext/core");