Files
Solus/tests/rateLimit.test.js

45 lines
1.7 KiB
JavaScript

import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { rateLimit } from '../src/rateLimit.js';
function ctx(ip) {
return {
req: { header: (name) => (name === 'x-forwarded-for' ? ip : null) },
json: (_body, status) => ({ __json: true, status }),
};
}
const OK = { __next: true };
describe('rateLimit', () => {
test('allows up to `max` requests, then rejects with 429', async () => {
const middleware = rateLimit(3, 60_000);
const ip = `10.0.0.${Math.floor(Math.random() * 200) + 10}`;
for (let i = 0; i < 3; i++) {
assert.deepEqual(await middleware(ctx(ip), async () => OK), OK);
}
const res = await middleware(ctx(ip), async () => OK);
assert.equal(res.status, 429);
});
test('isolates per-IP — a different IP is unaffected', async () => {
const middleware = rateLimit(1, 60_000);
const ipA = `10.1.0.${Math.floor(Math.random() * 200) + 10}`;
const ipB = `10.1.1.${Math.floor(Math.random() * 200) + 10}`;
assert.deepEqual(await middleware(ctx(ipA), async () => OK), OK);
const resA = await middleware(ctx(ipA), async () => OK);
assert.equal(resA.status, 429);
// ipB still has a full quota
assert.deepEqual(await middleware(ctx(ipB), async () => OK), OK);
});
test('window expiry frees up the quota again', async () => {
const middleware = rateLimit(1, 60); // 60ms window
const ip = `10.2.0.${Math.floor(Math.random() * 200) + 10}`;
assert.deepEqual(await middleware(ctx(ip), async () => OK), OK);
assert.equal((await middleware(ctx(ip), async () => OK)).status, 429);
await new Promise((r) => setTimeout(r, 90));
assert.deepEqual(await middleware(ctx(ip), async () => OK), OK);
});
});