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

This commit is contained in:
Elian Doran 2025-05-16 19:45:32 +03:00
parent f38105ef05
commit f327b54c0e
No known key found for this signature in database
3 changed files with 6 additions and 3 deletions

View File

@ -2,6 +2,8 @@ import { doubleCsrf } from "csrf-csrf";
import sessionSecret from "../services/session_secret.js"; import sessionSecret from "../services/session_secret.js";
import { isElectron } from "../services/utils.js"; import { isElectron } from "../services/utils.js";
export const CSRF_COOKIE_NAME = "trilium-csrf";
const doubleCsrfUtilities = doubleCsrf({ const doubleCsrfUtilities = doubleCsrf({
getSecret: () => sessionSecret, getSecret: () => sessionSecret,
cookieOptions: { cookieOptions: {
@ -10,7 +12,7 @@ const doubleCsrfUtilities = doubleCsrf({
sameSite: "strict", sameSite: "strict",
httpOnly: !isElectron // set to false for Electron, see https://github.com/TriliumNext/Notes/pull/966 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 getSessionIdentifier: (req) => req.session.id
}); });

View File

@ -3,6 +3,7 @@ import log from "../services/log.js";
import NotFoundError from "../errors/not_found_error.js"; import NotFoundError from "../errors/not_found_error.js";
import ForbiddenError from "../errors/forbidden_error.js"; import ForbiddenError from "../errors/forbidden_error.js";
import HttpError from "../errors/http_error.js"; import HttpError from "../errors/http_error.js";
import { CSRF_COOKIE_NAME } from "./csrf_protection.js";
function register(app: Application) { function register(app: Application) {
@ -14,7 +15,7 @@ function register(app: Application) {
&& err.code === "EBADCSRFTOKEN"; && err.code === "EBADCSRFTOKEN";
if (isCsrfTokenError) { 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")); return next(new ForbiddenError("Invalid CSRF token"));
} }

View File

@ -20,7 +20,7 @@ function index(req: Request, res: Response) {
const view = getView(req); const view = getView(req);
const csrfToken = generateCsrfToken(req, res, { const csrfToken = generateCsrfToken(req, res, {
overwrite: true, overwrite: false,
validateOnReuse: false // if validation fails, generate a new token instead of throwing an error validateOnReuse: false // if validation fails, generate a new token instead of throwing an error
}); });
log.info(`CSRF token generation: ${csrfToken ? "Successful" : "Failed"}`); log.info(`CSRF token generation: ${csrfToken ? "Successful" : "Failed"}`);