feat: remove csrf from the client (#42242)

This commit is contained in:
Oliver Eyton-Williams
2021-07-16 17:49:47 +02:00
committed by GitHub
parent 017ae24894
commit 1ba9d03cb5
9 changed files with 53 additions and 51 deletions

View File

@ -35,6 +35,7 @@
"helmet#noSniff": {},
"helmet#frameguard": {},
"./middlewares/csurf": {},
"./middlewares/csurf-set-cookie": {},
"./middlewares/constant-headers": {},
"./middlewares/csp": {},
"./middlewares/flash-cheaters": {},
@ -43,6 +44,7 @@
"files": {},
"final:after": {
"./middlewares/sentry-error-handler": {},
"./middlewares/csurf-error-handler": {},
"./middlewares/error-handlers": {},
"strong-error-handler": {
"params": {

View File

@ -0,0 +1,12 @@
import { csrfOptions } from './csurf.js';
export default function csrfErrorHandler() {
return function (err, req, res, next) {
if (err.code === 'EBADCSRFTOKEN' && req.csrfToken) {
// use the middleware to generate a token. The client sends this back via
// a header
res.cookie('csrf_token', req.csrfToken(), csrfOptions);
}
next(err);
};
}

View File

@ -0,0 +1,13 @@
import { csrfOptions } from './csurf.js';
export default function setCSRFCookie() {
return function (req, res, next) {
// not all paths require a CSRF token, so the function may not be available.
if (req.csrfToken && !req.cookies.csrf_token) {
// use the middleware to generate a token. The client sends this back via
// a header
res.cookie('csrf_token', req.csrfToken(), csrfOptions);
}
next();
};
}

View File

@ -1,12 +1,14 @@
import csurf from 'csurf';
export const csrfOptions = {
domain: process.env.COOKIE_DOMAIN || 'localhost',
sameSite: 'strict',
secure: process.env.FREECODECAMP_NODE_ENV === 'production'
};
export default function getCsurf() {
const protection = csurf({
cookie: {
domain: process.env.COOKIE_DOMAIN || 'localhost',
sameSite: 'strict',
secure: process.env.FREECODECAMP_NODE_ENV === 'production'
}
cookie: csrfOptions
});
return function csrf(req, res, next) {
const { path } = req;
@ -14,8 +16,10 @@ export default function getCsurf() {
// eslint-disable-next-line max-len
/^\/hooks\/update-paypal$/.test(path)
) {
return next();
next();
} else {
// add the middleware
protection(req, res, next);
}
return protection(req, res, next);
};
}

View File

@ -64,6 +64,7 @@ export function removeCookies(req, res) {
res.clearCookie('access_token', config);
res.clearCookie('userId', config);
res.clearCookie('_csrf', config);
res.clearCookie('csrf_token', config);
return;
}