copilot_work_3 / src /lib /rate-limit.test.ts
arshvinw5's picture
add rate limit to submittions
416bdd1
Raw History Blame
1.05 kB
import { beforeEach, describe, expect, it } from "vitest";
import { checkRateLimit, getClientIp } from "@/lib/rate-limit";
beforeEach(() => {
globalThis.__chainkitRateLimits = undefined;
});
describe("checkRateLimit", () => {
it("blocks after the limit and recovers after the window", () => {
expect(checkRateLimit("k", 2, 1000, 0).allowed).toBe(true);
expect(checkRateLimit("k", 2, 1000, 1).allowed).toBe(true);
const blocked = checkRateLimit("k", 2, 1000, 2);
expect(blocked.allowed).toBe(false);
expect(blocked.retryAfterSeconds).toBeGreaterThan(0);
expect(checkRateLimit("k", 2, 1000, 1001).allowed).toBe(true);
});
it("tracks keys independently", () => {
checkRateLimit("a", 1, 1000, 0);
expect(checkRateLimit("b", 1, 1000, 0).allowed).toBe(true);
});
});
describe("getClientIp", () => {
it("uses the last x-forwarded-for entry", () => {
const request = new Request("http://x", { headers: { "x-forwarded-for": "6.6.6.6, 1.2.3.4" } });
expect(getClientIp(request)).toBe("1.2.3.4");
});
});