Harden the app
This commit is contained in:
1 parent
d92c4b50cf
commit
e3a2b348d6
5 files changed
+38
-12
No files matched your search
+14
-2
@@ -45,9 +45,21 @@ const isId = (value) => typeof value === 'string' && value.length === 20;
|
||||
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
|
||||
|
||||
// Behind Caddy, the only way in. Caddy replaces any X-Forwarded-For a client sends, the last entry is
|
||||
// its own anyway.
|
||||
// its own anyway. IPv6 counts by /64: a single host usually has a whole one, every address in it
|
||||
// would get MAX_PER_IP of its own. IPv4, also mapped to IPv6, counts as it is.
|
||||
function clientIp(req) {
|
||||
return req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
|
||||
const ip = req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
|
||||
if (!ip?.includes(':') || ip.includes('.')) return ip;
|
||||
const [head, tail] = ip.split('::');
|
||||
const groups = head ? head.split(':') : [];
|
||||
if (tail !== undefined) {
|
||||
const rest = tail ? tail.split(':') : [];
|
||||
groups.push(...Array(Math.max(0, 8 - groups.length - rest.length)).fill('0'), ...rest);
|
||||
}
|
||||
return `${groups
|
||||
.slice(0, 4)
|
||||
.map((group) => parseInt(group, 16).toString(16))
|
||||
.join(':')}::/64`;
|
||||
}
|
||||
|
||||
function refuse(socket, status) {
|
||||
|
||||
@@ -323,6 +323,17 @@ test('limits connections per IP to 16', async () => {
|
||||
expect(await open()).toBeTruthy();
|
||||
});
|
||||
|
||||
test('counts IPv6 by /64, however it is written', async () => {
|
||||
for (let i = 1; i <= 16; i++) {
|
||||
ip = [`2001:db8:${tests}::${i.toString(16)}`, `2001:0DB8:${tests}:0:${i}::`][i % 2];
|
||||
expect(await open()).toBeTruthy();
|
||||
}
|
||||
ip = `2001:db8:${tests}:0:ffff:ffff:ffff:ffff`;
|
||||
expect(await open()).toBeUndefined();
|
||||
ip = `2001:db8:${tests}:1::1`;
|
||||
expect(await open()).toBeTruthy();
|
||||
});
|
||||
|
||||
test('survives clients resetting refused connections', async () => {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const socket = connectTcp(new URL(url).port, '127.0.0.1');
|
||||
|
||||
Reference in new issue
Block a user