Ghost/core/server/web/shared/middlewares/brute.js
Fabien 'egg' O'Carroll 1af2b50dcf
Added userAuth brute middleware to members auth endpoint (#13152)
refs https://github.com/TryGhost/Team/issues/696

The userAuth spam prevention logic is reused, but a new piece of
middleware has to be created so that we can use a custom lookup key to
conatin the member email.

We must also add json parsing middleware to the route so that the brute
middleware can read the email.

The express body-parser middleware handles multiple instances on the
same route, so this doesn't cause problems upstream.

https://github.com/expressjs/body-parser/blob/1.19.0/lib/types/json.js#L99-L103
2021-07-19 09:40:38 +01:00

114 lines
3.1 KiB
JavaScript

const url = require('url');
const spamPrevention = require('./api/spam-prevention');
/**
* We set ignoreIP to false, because we tell brute-knex to use `req.ip`.
* We can use `req.ip`, because express trust proxy option is enabled.
*/
module.exports = {
/**
* block per route per ip
*/
globalBlock(req, res, next) {
return spamPrevention.globalBlock().getMiddleware({
ignoreIP: false,
key: function (_req, _res, _next) {
_next(url.parse(_req.url).pathname);
}
})(req, res, next);
},
/**
* block per route per ip
*/
globalReset(req, res, next) {
return spamPrevention.globalReset().getMiddleware({
ignoreIP: false,
key(_req, _res, _next) {
_next(url.parse(_req.url).pathname);
}
})(req, res, next);
},
/**
* block per user
* username === email!
*/
userLogin(req, res, next) {
return spamPrevention.userLogin().getMiddleware({
ignoreIP: false,
key(_req, _res, _next) {
if (_req.body.username) {
return _next(`${_req.body.username}login`);
}
if (_req.body.authorizationCode) {
return _next(`${_req.body.authorizationCode}login`);
}
if (_req.body.refresh_token) {
return _next(`${_req.body.refresh_token}login`);
}
return _next();
}
})(req, res, next);
},
/**
* block per user
*/
userReset(req, res, next) {
return spamPrevention.userReset().getMiddleware({
ignoreIP: false,
key(_req, _res, _next) {
_next(`${_req.body.username}reset`);
}
})(req, res, next);
},
/**
* block per ip
*/
privateBlog(req, res, next) {
return spamPrevention.privateBlog().getMiddleware({
ignoreIP: false,
key(_req, _res, _next) {
_next('privateblog');
}
})(req, res, next);
},
/*
* protect content api from brute force
*/
contentApiKey(req, res, next) {
return spamPrevention.contentApiKey().getMiddleware({
ignoreIP: false
})(req, res, function (err, ...rest) {
if (!err) {
// Reset any blocks if the request is authorized
// This ensures that the count only goes up for
// unauthorized requests.
res.on('finish', function () {
if (res.statusCode < 400) {
req.brute.reset();
}
});
}
return next(err, ...rest);
});
},
/**
*/
membersAuth(req, res, next) {
return spamPrevention.userLogin().getMiddleware({
ignoreIP: false,
key(_req, _res, _next) {
if (_req.body.email) {
return _next(`${_req.body.email}login`);
}
return _next();
}
})(req, res, next);
}
};