Skip to content

Build your personal knowledge base with Trilium Notes

fix(auth): log out all sessions when the password changes

Elian Doran4ddaab4185ce
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index 782459cc0d..4e090336c7 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -117,9 +117,14 @@ export default async function buildApp() {
app.use(`/robots.txt`, express.static(path.join(publicAssetsDir, "robots.txt"), STATIC_OPTIONS));
app.use(`/icon.png`, express.static(path.join(publicAssetsDir, "icon.png"), STATIC_OPTIONS));
- const { default: sessionParser, startSessionCleanup } = await import("./routes/session_parser.js");
+ const {
+ default: sessionParser,
+ startSessionCleanup,
+ startSessionRevocationOnPasswordChange
+ } = await import("./routes/session_parser.js");
app.use(sessionParser);
startSessionCleanup();
+ startSessionRevocationOnPasswordChange();
app.use(favicon(path.join(assetsDir, isDev ? "icon-dev.ico" : "icon.ico")));
// Always mount the OIDC middleware, but have it activate reactively from the current `mfaMethod`
diff --git a/apps/server/src/routes/login.spec.ts b/apps/server/src/routes/login.spec.ts
index fe7e9386d7..455fbe182f 100644
--- a/apps/server/src/routes/login.spec.ts
+++ b/apps/server/src/routes/login.spec.ts
@@ -2,9 +2,9 @@ import { dayjs } from "@triliumnext/commons";
import express, { type Application } from "express";
import { SessionData } from "express-session";
import supertest, { type Response } from "supertest";
-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
-import { cls, options } from "@triliumnext/core";
+import { cls, events, options } from "@triliumnext/core";
import { refreshAuth } from "../services/auth.js";
import config from "../services/config.js";
import totp from "../services/totp.js";
@@ -292,6 +292,55 @@ describe("Login Route test", () => {
expect(session).toBeFalsy();
});
});
+
+ describe("Password change revokes sessions", () => {
+ let originalHash: string;
+
+ beforeAll(() => {
+ originalHash = cls.init(() => options.getOption("passwordVerificationHash"));
+ });
+
+ afterEach(() => {
+ cls.init(() => options.setOption("passwordVerificationHash", originalHash));
+ });
+
+ async function logIn() {
+ const res = await supertest(app)
+ .post("/login")
+ .send({ password: "demo1234" })
+ .expect(302);
+ const cookie = res.headers["set-cookie"][0];
+ expect((await getSessionFromCookie(cookie)).session?.loggedIn).toBe(true);
+ return cookie;
+ }
+
+ it("keeps sessions when an unrelated option changes", async () => {
+ const cookie = await logIn();
+ cls.init(() => options.setOption("redirectBareDomain", "false"));
+ expect((await getSessionFromCookie(cookie)).session?.loggedIn).toBe(true);
+ });
+
+ it("removes every session when the password changes on this instance", async () => {
+ const first = await logIn();
+ const second = await logIn();
+
+ cls.init(() => options.setOption("passwordVerificationHash", "changed-locally"));
+
+ expect((await getSessionFromCookie(first)).session).toBeFalsy();
+ expect((await getSessionFromCookie(second)).session).toBeFalsy();
+ });
+
+ it("removes every session when a password change arrives by sync", async () => {
+ const cookie = await logIn();
+
+ cls.init(() => events.emit(events.ENTITY_CHANGE_SYNCED, {
+ entityName: "options",
+ entityRow: { name: "passwordVerificationHash", value: "changed-remotely", isSynced: 1 }
+ }));
+
+ expect((await getSessionFromCookie(cookie)).session).toBeFalsy();
+ });
+ });
}, 100_000);
const MAX_REDIRECT_HOPS = 5;
diff --git a/apps/server/src/routes/session_parser.ts b/apps/server/src/routes/session_parser.ts
index 874ea54aa8..a4d418a737 100644
--- a/apps/server/src/routes/session_parser.ts
+++ b/apps/server/src/routes/session_parser.ts
@@ -2,7 +2,7 @@ import type express from "express";
import session, { Store } from "express-session";
import config from "../services/config.js";
-import { getLog } from "@triliumnext/core";
+import { events, getLog } from "@triliumnext/core";
import sessionSecret from "../services/session_secret.js";
import sql from "../services/sql.js";
import sqlInit from "../services/sql_init.js";
@@ -144,4 +144,28 @@ export function startSessionCleanup() {
}, CLEAN_UP_INTERVAL);
}
+/**
+ * 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.
+ */
+export function startSessionRevocationOnPasswordChange() {
+ events.subscribe(events.ENTITY_CHANGED, ({ entityName, entity }) => {
+ if (entityName === "options" && entity.name === "passwordVerificationHash") {
+ revokeAllSessions();
+ }
+ });
+
+ events.subscribe(events.ENTITY_CHANGE_SYNCED, ({ entityName, entityRow }) => {
+ if (entityName === "options" && entityRow.name === "passwordVerificationHash") {
+ revokeAllSessions();
+ }
+ });
+}
+
+function revokeAllSessions() {
+ const result = sql.execute(/*sql*/`DELETE FROM sessions`);
+ getLog().info(`Password changed, logged out ${result.changes} session(s).`);
+}
+
export default sessionParser;
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.md
index ca4b6a9676..d0b5f0c0e8 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,6 +51,8 @@ cookieMaxAge=86400
When “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.
+
## Viewing active sessions
The login sessions are now stored in the same <a class="reference-link" href="../../Advanced%20Usage/Database.md">Database</a> as the user data. In order to view which sessions are active, open the <a class="reference-link" href="../../Advanced%20Usage/Database/Manually%20altering%20the%20database/SQL%20Console.md">SQL Console</a> and run the following query: