From f327b54c0e1e62d3e9d8d091f36c7cac0d938e75 Mon Sep 17 00:00:00 2001 From: Elian Doran Date: Fri, 16 May 2025 19:45:32 +0300 Subject: [PATCH] feat(csrf): use different token to avoid issues with old token --- apps/server/src/routes/csrf_protection.ts | 4 +++- apps/server/src/routes/error_handlers.ts | 3 ++- apps/server/src/routes/index.ts | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/server/src/routes/csrf_protection.ts b/apps/server/src/routes/csrf_protection.ts index bd382e369..2b26afbf3 100644 --- a/apps/server/src/routes/csrf_protection.ts +++ b/apps/server/src/routes/csrf_protection.ts @@ -2,6 +2,8 @@ import { doubleCsrf } from "csrf-csrf"; import sessionSecret from "../services/session_secret.js"; import { isElectron } from "../services/utils.js"; +export const CSRF_COOKIE_NAME = "trilium-csrf"; + const doubleCsrfUtilities = doubleCsrf({ getSecret: () => sessionSecret, cookieOptions: { @@ -10,7 +12,7 @@ const doubleCsrfUtilities = doubleCsrf({ sameSite: "strict", httpOnly: !isElectron // set to false for Electron, see https://github.com/TriliumNext/Notes/pull/966 }, - cookieName: "_csrf", + cookieName: CSRF_COOKIE_NAME, getSessionIdentifier: (req) => req.session.id }); diff --git a/apps/server/src/routes/error_handlers.ts b/apps/server/src/routes/error_handlers.ts index 05b05f6a4..af58be82f 100644 --- a/apps/server/src/routes/error_handlers.ts +++ b/apps/server/src/routes/error_handlers.ts @@ -3,6 +3,7 @@ import log from "../services/log.js"; import NotFoundError from "../errors/not_found_error.js"; import ForbiddenError from "../errors/forbidden_error.js"; import HttpError from "../errors/http_error.js"; +import { CSRF_COOKIE_NAME } from "./csrf_protection.js"; function register(app: Application) { @@ -14,7 +15,7 @@ function register(app: Application) { && err.code === "EBADCSRFTOKEN"; if (isCsrfTokenError) { - log.error(`Invalid CSRF token: ${req.headers["x-csrf-token"]}, secret: ${req.cookies["_csrf"]}`); + log.error(`Invalid CSRF token: ${req.headers["x-csrf-token"]}, secret: ${req.cookies[CSRF_COOKIE_NAME]}`); return next(new ForbiddenError("Invalid CSRF token")); } diff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.ts index 5a907cee4..60697b156 100644 --- a/apps/server/src/routes/index.ts +++ b/apps/server/src/routes/index.ts @@ -20,7 +20,7 @@ function index(req: Request, res: Response) { const view = getView(req); const csrfToken = generateCsrfToken(req, res, { - overwrite: true, + overwrite: false, validateOnReuse: false // if validation fails, generate a new token instead of throwing an error }); log.info(`CSRF token generation: ${csrfToken ? "Successful" : "Failed"}`);