mirror of
https://github.com/HabitRPG/habitica.git
synced 2025-12-19 07:37:25 +01:00
66 lines
1.9 KiB
JavaScript
66 lines
1.9 KiB
JavaScript
import nconf from 'nconf';
|
|
import {
|
|
Forbidden,
|
|
} from '../libs/errors';
|
|
import { apiError } from '../libs/apiError';
|
|
import { model as Blocker } from '../models/blocker';
|
|
|
|
// Middleware to block unwanted IP addresses
|
|
|
|
// NOTE: it's meant to be used behind a proxy (for example a load balancer)
|
|
// that uses the 'x-forwarded-for' header to forward the original IP addresses.
|
|
|
|
// A list of comma separated IPs to block
|
|
// It works fine as long as the list is short,
|
|
// if the list becomes too long for an env variable we'll switch to Redis.
|
|
const BLOCKED_IPS_RAW = nconf.get('BLOCKED_IPS');
|
|
|
|
const blockedIps = BLOCKED_IPS_RAW
|
|
? BLOCKED_IPS_RAW
|
|
.trim()
|
|
.split(',')
|
|
.map(blockedIp => blockedIp.trim())
|
|
.filter(blockedIp => Boolean(blockedIp))
|
|
: [];
|
|
|
|
const blockedClients = [];
|
|
|
|
Blocker.watchBlockers({
|
|
$or: [
|
|
{ type: 'ipaddress' },
|
|
{ type: 'client' },
|
|
],
|
|
area: 'full',
|
|
}, {
|
|
initial: true,
|
|
}).on('change', async change => {
|
|
const { operation, blocker } = change;
|
|
const checkedList = blocker.type === 'ipaddress' ? blockedIps : blockedClients;
|
|
if (operation === 'add') {
|
|
if (blocker.value && !checkedList.includes(blocker.value)) {
|
|
checkedList.push(blocker.value);
|
|
}
|
|
} else if (operation === 'delete') {
|
|
const index = checkedList.indexOf(blocker.value);
|
|
if (index !== -1) {
|
|
checkedList.splice(index, 1);
|
|
}
|
|
}
|
|
});
|
|
|
|
export default function ipBlocker (req, res, next) {
|
|
if (blockedIps.length === 0 && blockedClients.length === 0) return next();
|
|
|
|
const ipMatch = blockedIps.find(blockedIp => blockedIp === req.ip) !== undefined;
|
|
if (ipMatch === true) {
|
|
return next(new Forbidden(apiError('ipAddressBlocked')));
|
|
}
|
|
|
|
const clientMatch = blockedClients.find(blockedClient => blockedClient === req.headers['x-client']) !== undefined;
|
|
if (clientMatch === true) {
|
|
return next(new Forbidden(apiError('clientBlocked')));
|
|
}
|
|
|
|
return next();
|
|
}
|