Skip to content

Build your personal knowledge base with Trilium Notes

refactor(server): use different approach to handling the CSRF token

Elian Doran0d889426e814
diff --git a/apps/server/src/express.d.ts b/apps/server/src/express.d.ts
index 781c6db551..5b9673d693 100644
--- a/apps/server/src/express.d.ts
+++ b/apps/server/src/express.d.ts
@@ -26,5 +26,7 @@ export declare module "express-session" {
totpEnabled: boolean;
ssoEnabled: boolean;
};
+ /** Set during /bootstrap to mark the session as modified so express-session persists it and sends the cookie. */
+ csrfInitialized?: true;
}
}
diff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.ts
index eee290ff29..8094c0bdf6 100644
--- a/apps/server/src/routes/index.ts
+++ b/apps/server/src/routes/index.ts
@@ -20,6 +20,15 @@ type View = "desktop" | "mobile" | "print";
export function bootstrap(req: Request, res: Response) {
const options = optionService.getOptionMap();
+ // csrf-csrf v4 binds CSRF tokens to the session ID via HMAC. With saveUninitialized: false,
+ // a brand-new session is never persisted unless explicitly modified, so its cookie is never
+ // sent to the browser — meaning every request gets a different ephemeral session ID, and
+ // CSRF validation fails. Setting this flag marks the session as modified, which causes
+ // express-session to persist it and send the session cookie in this response.
+ if (!req.session.csrfInitialized) {
+ req.session.csrfInitialized = true;
+ }
+
const csrfToken = generateCsrfToken(req, res, {
overwrite: false,
validateOnReuse: false // if validation fails, generate a new token instead of throwing an error
diff --git a/apps/server/src/routes/session_parser.ts b/apps/server/src/routes/session_parser.ts
index f0f0159d24..a52a9183aa 100644
--- a/apps/server/src/routes/session_parser.ts
+++ b/apps/server/src/routes/session_parser.ts
@@ -102,11 +102,7 @@ export const sessionStore = new SQLiteSessionStore();
const sessionParser: express.RequestHandler = session({
secret: sessionSecret,
resave: false, // true forces the session to be saved back to the session store, even if the session was never modified during the request.
- saveUninitialized: true, // Ensures new sessions are always persisted and the session cookie is sent on the first response.
- // This is required for csrf-csrf v4, which binds CSRF tokens to the session ID via HMAC.
- // With saveUninitialized: false, a brand-new session would never be saved (and its cookie
- // never sent) when noAuthentication=true, causing every request to get a different ephemeral
- // session ID and making CSRF validation fail for all API calls.
+ saveUninitialized: false, // true forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
rolling: true, // forces the session to be saved back to the session store, resetting the expiration date.
cookie: {
path: "/",