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(protected_session): recover from a lost expiry broadcast via ping state (closes #10115)
Elian Doran211b318be99f
diff --git a/apps/client/src/services/ws.spec.ts b/apps/client/src/services/ws.spec.tsindex 1bc5950e32..f70ca9dfeb 100644--- a/apps/client/src/services/ws.spec.ts+++ b/apps/client/src/services/ws.spec.ts@@ -120,6 +120,27 @@ describe("dispatchMessage", () => {expect(bundle.getAndExecuteBundle).toHaveBeenCalledWith("cur2", null, "x", []);});+ it("reloads when a ping reports the protected session expired on the backend", async () => {+ const ws = await loadWs();+ (window as any).glob.isProtectedSessionAvailable = true;++ // flag absent (client->server ping shape) or still true -> no reload+ await ws.dispatchMessage({ type: "ping" } as WebSocketMessage);+ await ws.dispatchMessage({ type: "ping", protectedSessionAvailable: true } as WebSocketMessage);+ expect(utilsCtrl.reloadFrontendApp).not.toHaveBeenCalled();++ await ws.dispatchMessage({ type: "ping", protectedSessionAvailable: false } as WebSocketMessage);+ expect(utilsCtrl.reloadFrontendApp).toHaveBeenCalledWith(expect.stringContaining("protected session"));+ });++ it("does not reload on expiry pings when the client never had the protected session", async () => {+ const ws = await loadWs();+ (window as any).glob.isProtectedSessionAvailable = false;++ await ws.dispatchMessage({ type: "ping", protectedSessionAvailable: false } as WebSocketMessage);+ expect(utilsCtrl.reloadFrontendApp).not.toHaveBeenCalled();+ });+it("ignores unknown message types", async () => {const ws = await loadWs();await ws.dispatchMessage({ type: "totally-unknown" } as any);diff --git a/apps/client/src/services/ws.ts b/apps/client/src/services/ws.tsindex c38413e4c2..5f37a309b9 100644--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@ -86,6 +86,13 @@ export async function dispatchMessage(message: WebSocketMessage) {// Process the messageif (messageType === "ping") {lastPingTs = Date.now();++ // The backend expires the protected session with a one-shot `reload-frontend` broadcast;+ // if the connection was down at that moment, the client would keep showing decrypted+ // notes indefinitely. Ping replies carry the live backend state, so recover here.+ if (msg.protectedSessionAvailable === false && glob.isProtectedSessionAvailable) {+ utils.reloadFrontendApp("protected session expired on the backend");+ }} else if (messageType === "reload-frontend") {utils.reloadFrontendApp("received request from backend to reload frontend");} else if (messageType === "frontend-update") {diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.tsindex 6624df3f2c..c1e80d0025 100644--- a/packages/commons/src/lib/ws_api.ts+++ b/packages/commons/src/lib/ws_api.ts@@ -113,7 +113,13 @@ type AllTaskDefinitions =| TaskDefinition<"importAttachments">;export type WebSocketMessage = AllTaskDefinitions | {- type: "ping"+ type: "ping",+ /**+ * Live protected-session state of the backend, present on server→client pings. Lets the client+ * detect a protected-session expiry whose `reload-frontend` broadcast never arrived (e.g. the+ * WebSocket was dead at expiry time) and reload itself. Absent on client→server pings.+ */+ protectedSessionAvailable?: boolean} | {type: "frontend-update",data: {diff --git a/packages/trilium-core/src/services/ws.spec.ts b/packages/trilium-core/src/services/ws.spec.tsindex 8fd8048d2f..2af44a81d6 100644--- a/packages/trilium-core/src/services/ws.spec.ts+++ b/packages/trilium-core/src/services/ws.spec.ts@@ -135,7 +135,21 @@ describe("ws service (real DB)", () => {await handler("client-1", { type: "ping" });await handler("client-1", { type: "totally-unknown" });- expect(sentToClient).toContainEqual({ clientId: "client-1", message: { type: "ping" } });+ expect(sentToClient).toContainEqual({ clientId: "client-1", message: { type: "ping", protectedSessionAvailable: false } });+ });++ it("ping replies report the live protected-session state", async () => {+ const handler = clientHandler;+ if (!handler) throw new Error("handler not registered");++ protectedSessionService.setDataKey(new Uint8Array([1, 2, 3]));+ try {+ await handler("client-2", { type: "ping" });+ } finally {+ protectedSessionService.resetDataKey();+ }++ expect(sentToClient).toContainEqual({ clientId: "client-2", message: { type: "ping", protectedSessionAvailable: true } });});it("sync status helpers broadcast the matching message types with lastSyncedPush", () => {@@ -161,7 +175,7 @@ describe("ws service (real DB)", () => {it("sends a ping frontend-update when there are no pending entity changes", () => {const before = sentAll.length;cls.init(() => ws.sendTransactionEntityChangesToAllClients());- expect(sentAll[sentAll.length - 1]).toEqual({ type: "ping" });+ expect(sentAll[sentAll.length - 1]).toEqual({ type: "ping", protectedSessionAvailable: false });expect(sentAll.length).toBe(before + 1);});diff --git a/packages/trilium-core/src/services/ws.ts b/packages/trilium-core/src/services/ws.tsindex b28b1d4048..8e6352407f 100644--- a/packages/trilium-core/src/services/ws.ts+++ b/packages/trilium-core/src/services/ws.ts@@ -23,7 +23,7 @@ function init() {log.info(`JS Info: ${message.info}`);} else if (message.type === "ping") {await syncMutexService.doExclusively(() => {- messagingProvider.sendMessageToClient(clientId, { type: "ping" });+ messagingProvider.sendMessageToClient(clientId, buildPingMessage());});} else {log.error("Unrecognized message: ");@@ -130,9 +130,20 @@ const ORDERING: Record<string, number> = {options: 0,};+/**+ * Server→client pings carry the live protected-session state so a client whose `reload-frontend`+ * broadcast got lost (dead WebSocket at expiry time) can still detect the expiry and reload.+ */+function buildPingMessage(): WebSocketMessage {+ return {+ type: "ping",+ protectedSessionAvailable: protectedSessionService.isProtectedSessionAvailable()+ };+}+function buildFrontendUpdateMessage(entityChangeIds: number[]): WebSocketMessage | null {if (entityChangeIds.length === 0) {- return { type: "ping" };+ return buildPingMessage();}const entityChanges = getSql().getManyRows<EntityChange>(/*sql*/`SELECT * FROM entity_changes WHERE id IN (???)`, entityChangeIds);