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(auth): return open tabs to login after a password change
Elian Doran4d198368a25c
diff --git a/apps/client/src/widgets/type_widgets/options/password.spec.tsx b/apps/client/src/widgets/type_widgets/options/password.spec.tsxindex 6e6926207c..18221c1d15 100644--- a/apps/client/src/widgets/type_widgets/options/password.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/password.spec.tsx@@ -23,8 +23,7 @@ const mocks = vi.hoisted(() => {post: vi.fn(async (_url: string): Promise<{ success: boolean; message?: string }> => ({ success: true })),confirm: vi.fn(async () => true),showMessage: vi.fn(),- showError: vi.fn(),- resetProtectedSession: vi.fn()+ showError: vi.fn()};});@@ -66,11 +65,6 @@ vi.mock("../../../services/dialog", () => ({default: { confirm: mocks.confirm, prompt: vi.fn() }}));-// A changed password invalidates whatever the old one unlocked, so the session is dropped with it.-vi.mock("../../../services/protected_session_holder", () => ({- default: { resetProtectedSession: mocks.resetProtectedSession }-}));-vi.mock("../../../services/toast", () => ({default: { showMessage: mocks.showMessage, showError: mocks.showError }}));@@ -236,25 +230,23 @@ describe("changing the password", () => {expect(mocks.post).not.toHaveBeenCalled();});- it("sends the change and clears the protected session, which the old password unlocked", async () => {+ it("sends only the change, since the server closes the sessions the old password opened", async () => {await open();await fillIn("old", "new", "new");- expect(mocks.post).toHaveBeenCalledWith("password/change", {+ expect(mocks.post.mock.calls).toEqual([ [ "password/change", {current_password: "old",new_password: "new"- });- expect(mocks.resetProtectedSession).toHaveBeenCalled();+ } ] ]);expect(mocks.showMessage).toHaveBeenCalledWith("password.password_changed_success");});- it("reports what the server objected to, and keeps the session as it was", async () => {+ it("reports what the server objected to", async () => {mocks.post.mockResolvedValueOnce({ success: false, message: "password.wrong_password" });await open();await fillIn("wrong", "new", "new");expect(mocks.showError).toHaveBeenCalledWith("password.wrong_password");- expect(mocks.resetProtectedSession).not.toHaveBeenCalled();});});diff --git a/apps/client/src/widgets/type_widgets/options/password.tsx b/apps/client/src/widgets/type_widgets/options/password.tsxindex ca00e463f8..ea65acc8e5 100644--- a/apps/client/src/widgets/type_widgets/options/password.tsx+++ b/apps/client/src/widgets/type_widgets/options/password.tsx@@ -7,7 +7,6 @@ import { useCallback, useEffect, useState } from "preact/hooks";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import { oauthAccountLabel, oauthProviderDisplayName } from "../../../services/oauth_status";-import protected_session_holder from "../../../services/protected_session_holder";import server from "../../../services/server";import toast from "../../../services/toast";import { isElectron } from "../../../services/utils";@@ -111,9 +110,6 @@ function ChangePasswordModal({ show, onHidden }: ChangePasswordModalProps) {setNewPassword1("");setNewPassword2("");toast.showMessage(t("password.password_changed_success"));-- // password changed so current protected session is invalid and needs to be cleared- protected_session_holder.resetProtectedSession();} else if (result.message) {toast.showError(result.message);}diff --git a/apps/desktop/src/composite_messaging_provider.ts b/apps/desktop/src/composite_messaging_provider.tsindex b184dbf2d4..82313019b1 100644--- a/apps/desktop/src/composite_messaging_provider.ts+++ b/apps/desktop/src/composite_messaging_provider.ts@@ -34,6 +34,10 @@ export default class CompositeMessagingProvider implements MessagingProvider {this.ws.attachToHttpServer(httpServer, sessionParser);}+ disconnectAllClients(reason: string): void {+ this.ws.disconnectAllClients(reason);+ }+setClientMessageHandler(handler: ClientMessageHandler): void {this.ipc.setClientMessageHandler((id, message) => handler(`${IPC_PREFIX}${id}`, message));this.ws.setClientMessageHandler((id, message) => handler(`${WS_PREFIX}${id}`, message));diff --git a/apps/server/src/routes/login.spec.ts b/apps/server/src/routes/login.spec.tsindex 455fbe182f..a368b828e4 100644--- a/apps/server/src/routes/login.spec.ts+++ b/apps/server/src/routes/login.spec.ts@@ -4,7 +4,7 @@ import { SessionData } from "express-session";import supertest, { type Response } from "supertest";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";-import { cls, events, options } from "@triliumnext/core";+import { cls, events, initMessaging, options } from "@triliumnext/core";import { refreshAuth } from "../services/auth.js";import config from "../services/config.js";import totp from "../services/totp.js";@@ -295,13 +295,22 @@ describe("Login Route test", () => {describe("Password change revokes sessions", () => {let originalHash: string;+ const disconnectAllClients = vi.fn();beforeAll(() => {originalHash = cls.init(() => options.getOption("passwordVerificationHash"));+ initMessaging({+ attachToHttpServer() {},+ disconnectAllClients,+ sendMessageToAllClients() {},+ sendMessageToClient: () => false,+ setClientMessageHandler() {}+ } as Parameters<typeof initMessaging>[0]);});afterEach(() => {cls.init(() => options.setOption("passwordVerificationHash", originalHash));+ disconnectAllClients.mockClear();});async function logIn() {@@ -318,6 +327,7 @@ describe("Login Route test", () => {const cookie = await logIn();cls.init(() => options.setOption("redirectBareDomain", "false"));expect((await getSessionFromCookie(cookie)).session?.loggedIn).toBe(true);+ expect(disconnectAllClients).not.toHaveBeenCalled();});it("removes every session when the password changes on this instance", async () => {@@ -328,6 +338,7 @@ describe("Login Route test", () => {expect((await getSessionFromCookie(first)).session).toBeFalsy();expect((await getSessionFromCookie(second)).session).toBeFalsy();+ expect(disconnectAllClients).toHaveBeenCalled();});it("removes every session when a password change arrives by sync", async () => {@@ -339,6 +350,7 @@ describe("Login Route test", () => {}));expect((await getSessionFromCookie(cookie)).session).toBeFalsy();+ expect(disconnectAllClients).toHaveBeenCalled();});});}, 100_000);diff --git a/apps/server/src/routes/session_parser.ts b/apps/server/src/routes/session_parser.tsindex a4d418a737..a6ba2fd010 100644--- a/apps/server/src/routes/session_parser.ts+++ b/apps/server/src/routes/session_parser.ts@@ -2,10 +2,11 @@ import type express from "express";import session, { Store } from "express-session";import config from "../services/config.js";-import { events, getLog } from "@triliumnext/core";+import { events, getLog, getMessagingProvider, isMessagingInitialized } from "@triliumnext/core";import sessionSecret from "../services/session_secret.js";import sql from "../services/sql.js";import sqlInit from "../services/sql_init.js";+import { isHttpAttachableMessagingProvider } from "../services/ws_messaging_provider.js";/*** The amount of time in milliseconds after which expired sessions are cleaned up.@@ -147,7 +148,7 @@ export function startSessionCleanup() {/*** Logs out every session when `passwordVerificationHash` changes, whether the password is changed* or reset here or the new hash arrives by sync. A changed password must also cut off a stolen- * session cookie.+ * session cookie, including its open WebSocket connection.*/export function startSessionRevocationOnPasswordChange() {events.subscribe(events.ENTITY_CHANGED, ({ entityName, entity }) => {@@ -166,6 +167,11 @@ export function startSessionRevocationOnPasswordChange() {function revokeAllSessions() {const result = sql.execute(/*sql*/`DELETE FROM sessions`);getLog().info(`Password changed, logged out ${result.changes} session(s).`);++ const messaging = isMessagingInitialized() ? getMessagingProvider() : null;+ if (messaging && isHttpAttachableMessagingProvider(messaging)) {+ messaging.disconnectAllClients("password changed");+ }}export default sessionParser;diff --git a/apps/server/src/services/ws_messaging_provider.spec.ts b/apps/server/src/services/ws_messaging_provider.spec.tsindex 797f1e3cbd..ef0f2bf10b 100644--- a/apps/server/src/services/ws_messaging_provider.spec.ts+++ b/apps/server/src/services/ws_messaging_provider.spec.ts@@ -69,6 +69,10 @@ function makeSocket(readyState = OPEN) {send(data: string) {this.sent.push(data);},+ closed: false,+ close() {+ this.closed = true;+ },emit(event: string, ...args: any[]) {return handlers[event]?.(...args);}@@ -227,6 +231,29 @@ describe("WebSocketMessagingProvider", () => {});});+ describe("disconnectAllClients", () => {+ it("asks every open client to reload, then closes every connection", () => {+ const { server } = init();+ const open = makeSocket(OPEN);+ const closed = makeSocket(CLOSED);+ server.clients.add(open);+ server.clients.add(closed);++ provider.disconnectAllClients("password changed");++ expect(open.sent.map((data) => JSON.parse(data))).toEqual([+ { type: "reload-frontend", reason: "password changed" }+ ]);+ expect(closed.sent).toHaveLength(0);+ expect(open.closed).toBe(true);+ expect(closed.closed).toBe(true);+ });++ it("is a no-op when the server is not initialized", () => {+ expect(() => provider.disconnectAllClients("password changed")).not.toThrow();+ });+ });+describe("sendMessageToClient", () => {it("returns false for an unknown client", () => {init();diff --git a/apps/server/src/services/ws_messaging_provider.ts b/apps/server/src/services/ws_messaging_provider.tsindex 5ded6690c0..2a6b228a4d 100644--- a/apps/server/src/services/ws_messaging_provider.ts+++ b/apps/server/src/services/ws_messaging_provider.ts@@ -18,6 +18,8 @@ type SessionParser = (req: IncomingMessage, params: {}, cb: () => void) => void;*/export interface HttpAttachableMessagingProvider extends MessagingProvider {attachToHttpServer(httpServer: HttpServer, sessionParser: express.RequestHandler): void;+ /** Asks every client connected over the TCP listener to reload, then closes its connection. */+ disconnectAllClients(reason: string): void;}export function isHttpAttachableMessagingProvider(provider: MessagingProvider): provider is HttpAttachableMessagingProvider {@@ -124,6 +126,21 @@ export default class WebSocketMessagingProvider implements HttpAttachableMessagi}}+ /**+ * Asks every client to reload, then closes its connection. `verifyClient` checks the session+ * only when a connection opens, so a revoked session keeps receiving messages until then.+ */+ disconnectAllClients(reason: string): void {+ const jsonStr = JSON.stringify({ type: "reload-frontend", reason } satisfies WebSocketMessage);++ for (const client of this.webSocketServer?.clients ?? []) {+ if (client.readyState === WebSocket.OPEN) {+ client.send(jsonStr);+ }+ client.close();+ }+ }+sendMessageToClient(clientId: string, message: WebSocketMessage): boolean {const client = this.clientMap.get(clientId);if (!client || client.readyState !== WebSocket.OPEN) {diff --git a/docs/User Guide/User Guide/Installation & Setup/Server Installation/Authentication.md b/docs/User Guide/User Guide/Installation & Setup/Server Installation/Authentication.mdindex d0b5f0c0e8..276de6cdc8 100644--- a/docs/User Guide/User Guide/Installation & Setup/Server Installation/Authentication.md+++ b/docs/User Guide/User Guide/Installation & Setup/Server Installation/Authentication.md@@ -51,7 +51,7 @@ cookieMaxAge=86400When “Remember me” is unchecked, the behavior is different. At client/browser level the authentication does not have any expiration date, but it will be automatically cleared as soon as the user closes the browser. Nevertheless, the server will also dismiss this authentication in around 24 hours from the _last interaction with the application_.-Changing or resetting the password logs out every session, including the one that made the change, so you have to log in again with the new password. This also applies when the password is changed on another instance and reaches the server through synchronization. If you suspect that someone has obtained your session cookie, changing the password cuts off their access.+Changing or resetting the password logs out every session, including the one that made the change: open tabs return to the login screen, where you log in again with the new password. This also applies when the password is changed on another instance and reaches the server through synchronization. If you suspect that someone has obtained your session cookie, changing the password cuts off their access.## Viewing active sessionsdiff --git a/packages/trilium-core/src/services/encryption/password.spec.ts b/packages/trilium-core/src/services/encryption/password.spec.tsindex 595f96388a..067cbb009b 100644--- a/packages/trilium-core/src/services/encryption/password.spec.ts+++ b/packages/trilium-core/src/services/encryption/password.spec.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";import options from "../options.js";import { getContext } from "../context.js";+import protectedSessionService from "../protected_session.js";import passwordEncryptionService from "./password_encryption.js";import passwordService from "./password.js";@@ -59,6 +60,7 @@ describe("password service (real DB)", () => {FIXTURE_PASSWORD)) as Uint8Array;expect(dataKeyBefore).toBeInstanceOf(Uint8Array);+ protectedSessionService.setDataKey(dataKeyBefore);const newPassword = "brandNewPass-123";const result = await getContext().init(() =>@@ -77,6 +79,9 @@ describe("password service (real DB)", () => {expect(await passwordEncryptionService.verifyPassword(newPassword)).toBe(true);expect(await passwordEncryptionService.verifyPassword(FIXTURE_PASSWORD)).toBe(false);+ // The protected session opened with the old password is closed.+ expect(protectedSessionService.isProtectedSessionAvailable()).toBe(false);+// The underlying data key is preserved across the re-encryption.const dataKeyAfter = (await passwordEncryptionService.getDataKey(newPassworddiff --git a/packages/trilium-core/src/services/encryption/password.ts b/packages/trilium-core/src/services/encryption/password.tsindex 97d19518f7..81cb01a512 100644--- a/packages/trilium-core/src/services/encryption/password.ts+++ b/packages/trilium-core/src/services/encryption/password.ts@@ -1,10 +1,13 @@import type { ChangePasswordResponse } from "@triliumnext/commons";+import events from "../events.js";import options from "../options.js";+import protectedSessionService from "../protected_session.js";import { getSql } from "../sql/index.js";import scryptService from "./scrypt.js";import passwordEncryptionService from "./password_encryption.js";import { encodeBase64 } from "../utils/binary.js";import { getCrypto } from "./crypto.js";+import ws from "../ws.js";/*** Generates a random secure token encoded as base64.@@ -24,7 +27,7 @@ export function isPasswordSet(): boolean {/*** Changes the password from currentPassword to newPassword.- * Re-encrypts the data key with the new password.+ * Re-encrypts the data key with the new password and closes the protected session.*/export async function changePassword(currentPassword: string,@@ -59,6 +62,12 @@ export async function changePassword(options.setOption("passwordVerificationHash", newPasswordVerificationKey);+ if (protectedSessionService.isProtectedSessionAvailable()) {+ protectedSessionService.resetDataKey();+ events.emit(events.LEAVE_PROTECTED_SESSION);+ ws.sendMessageToAllClients({ type: "protectedSessionLogout" });+ }+return {success: true};