Files

45 lines
1.8 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
import {
__resetSignatureOtpRateLimitStoreForTests,
__setSignatureOtpRateLimitStoreForTests,
reserveSignatureOtpAttempt,
} from "./signature-otp-rate-limit.server";
describe("signature OTP rate limit", () => {
beforeEach(() => {
__setSignatureOtpRateLimitStoreForTests(createSharedStore({ namespace: "signature-otp-test", adapter: new MemoryAdapter() }));
});
afterEach(() => {
__resetSignatureOtpRateLimitStoreForTests();
});
it("blocks the sixth attempt for the same signing token", async () => {
for (let attempt = 0; attempt < 5; attempt += 1) {
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" })).resolves.toMatchObject({ allowed: true });
}
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 1800,
});
});
it("keeps the authoritative attempt budget isolated per token", async () => {
for (let attempt = 0; attempt < 5; attempt += 1) {
await reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" });
}
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-b", trustedClientIp: "203.0.113.10" })).resolves.toMatchObject({ allowed: true });
});
it("propagates shared-store failures so callers fail closed", async () => {
const adapter = new MemoryAdapter();
await adapter.close();
__setSignatureOtpRateLimitStoreForTests(createSharedStore({ namespace: "signature-otp-closed", adapter }));
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" })).rejects.toThrow(/closed/i);
});
});