45 lines
1.2 KiB
TypeScript
45 lines
1.2 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import { createRateLimiter } from "../../server/rate-limit";
|
|
|
|
describe("createRateLimiter", () => {
|
|
it("allows the first 10 hits from an IP", () => {
|
|
let now = 1_000;
|
|
const limiter = createRateLimiter(10, 60 * 60 * 1000, () => now);
|
|
|
|
for (let i = 0; i < 10; i++) {
|
|
expect(limiter.check("1.1.1.1")).toBe(true);
|
|
}
|
|
});
|
|
|
|
it("rejects the 11th hit within the window", () => {
|
|
let now = 1_000;
|
|
const limiter = createRateLimiter(10, 60 * 60 * 1000, () => now);
|
|
|
|
for (let i = 0; i < 10; i++) {
|
|
limiter.check("1.1.1.1");
|
|
}
|
|
|
|
expect(limiter.check("1.1.1.1")).toBe(false);
|
|
});
|
|
|
|
it("allows another hit after the window elapses", () => {
|
|
let now = 1_000;
|
|
const windowMs = 60 * 60 * 1000;
|
|
const limiter = createRateLimiter(10, windowMs, () => now);
|
|
|
|
for (let i = 0; i < 10; i++) {
|
|
limiter.check("1.1.1.1");
|
|
}
|
|
|
|
now += windowMs + 1;
|
|
expect(limiter.check("1.1.1.1")).toBe(true);
|
|
});
|
|
|
|
it("tracks IPs independently", () => {
|
|
const limiter = createRateLimiter(1, 60_000, () => 1_000);
|
|
expect(limiter.check("a")).toBe(true);
|
|
expect(limiter.check("a")).toBe(false);
|
|
expect(limiter.check("b")).toBe(true);
|
|
});
|
|
});
|