Skip to content

Build your personal knowledge base with Trilium Notes

feat(csrf): use different token to avoid issues with old token

Elian Doranf327b54c0e1e
diff --git a/apps/server/src/routes/csrf_protection.ts b/apps/server/src/routes/csrf_protection.ts
index bd382e3691..2b26afbf3e 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 05b05f6a4a..af58be82f1 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 5a907cee48..60697b156a 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"}`);