feat: use unkey for global ratelimiting and identifier overrides (#14173)

* feat: use unkey for global ratelimiting and identifier overrides

fixes #13672

* revert: make test pass

* chore: push timeout incase unkey ever dies

* chore: push timeout incase unkey ever dies

---------

Co-authored-by: sean-brydon <[email protected]>
This commit is contained in:
Andreas Thomasandsean-brydon authored and GitHub committed 2024-03-26 15:52:00 +00:00
1 parent a8d95d54e7
commit 091d3cdd17
8 files changed
+85 -96

No files matched your search

@@ -12,8 +12,7 @@ vi.mock("./rateLimit", () => {
describe("checkRateLimitAndThrowError", () => {
it("should throw an error if rate limit is exceeded", async () => {
process.env.UPSTASH_REDIS_REST_URL = "mockUrl";
process.env.UPSTASH_REDIS_REST_TOKEN = "mockToken";
process.env.UNKEY_ROOT_KEY = "unkey_mock";
vi.mocked(rateLimiter).mockReturnValue(() => {
return {
@@ -30,8 +29,7 @@ describe("checkRateLimitAndThrowError", () => {
});
it("should not throw an error if rate limit is not exceeded", async () => {
process.env.UPSTASH_REDIS_REST_URL = "mockUrl";
process.env.UPSTASH_REDIS_REST_TOKEN = "mockToken";
process.env.UNKEY_ROOT_KEY = "unkey_mock";
vi.mocked(rateLimiter).mockReturnValue(() => {
return {
limit: 10,
+2 -1
View File
@@ -7,8 +7,9 @@ export async function checkRateLimitAndThrowError({
rateLimitingType = "core",
identifier,
onRateLimiterResponse,
opts,
}: RateLimitHelper) {
const response = await rateLimiter()({ rateLimitingType, identifier });
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
const { remaining, reset } = response;
if (onRateLimiterResponse) onRateLimiterResponse(response);
+42 -50
View File
@@ -1,5 +1,4 @@
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { Ratelimit, type LimitOptions, type RatelimitResponse } from "@unkey/ratelimit";
import { isIpInBanListString } from "./getIP";
import logger from "./logger";
@@ -9,6 +8,7 @@ const log = logger.getSubLogger({ prefix: ["RateLimit"] });
export type RateLimitHelper = {
rateLimitingType?: "core" | "forcedSlowMode" | "common" | "api" | "ai";
identifier: string;
opts?: LimitOptions;
/**
* Using a callback instead of a regular return to provide headers even
* when the rate limit is reached and an error is thrown.
@@ -16,27 +16,6 @@ export type RateLimitHelper = {
onRateLimiterResponse?: (response: RatelimitResponse) => void;
};
export type RatelimitResponse = {
/**
* Whether the request may pass(true) or exceeded the limit(false)
*/
success: boolean;
/**
* Maximum number of requests allowed within a window.
*/
limit: number;
/**
* How many requests the user has left within the current window.
*/
remaining: number;
/**
* Unix timestamp in milliseconds when the limits are reset.
*/
reset: number;
pending: Promise<unknown>;
};
let warningDisplayed = false;
/** Prevent flooding the logs while testing/building */
@@ -49,53 +28,66 @@ function logOnce(message: string) {
export const API_KEY_RATE_LIMIT = 30;
export function rateLimiter() {
const UPSATCH_ENV_FOUND = process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN;
const { UNKEY_ROOT_KEY } = process.env;
if (!UPSATCH_ENV_FOUND) {
logOnce("Disabled due to not finding UPSTASH env variables");
if (!UNKEY_ROOT_KEY) {
logOnce("Disabled due to not finding UNKEY_ROOT_KEY env variable");
return () => ({ success: true, limit: 10, remaining: 999, reset: 0 } as RatelimitResponse);
}
const timeout = {
fallback: { success: true, limit: 10, remaining: 999, reset: 0 },
ms: 5000,
};
const redis = Redis.fromEnv();
const limiter = {
core: new Ratelimit({
redis,
analytics: true,
prefix: "ratelimit",
limiter: Ratelimit.fixedWindow(10, "60s"),
rootKey: UNKEY_ROOT_KEY,
namespace: "core",
limit: 10,
duration: "60s",
async: true,
timeout,
}),
common: new Ratelimit({
redis,
analytics: true,
prefix: "ratelimit",
limiter: Ratelimit.fixedWindow(200, "60s"),
rootKey: UNKEY_ROOT_KEY,
namespace: "common",
limit: 200,
duration: "60s",
async: true,
timeout,
}),
forcedSlowMode: new Ratelimit({
redis,
analytics: true,
prefix: "ratelimit:slowmode",
limiter: Ratelimit.fixedWindow(1, "30s"),
rootKey: UNKEY_ROOT_KEY,
namespace: "forcedSlowMode",
limit: 1,
duration: "30s",
async: true,
timeout,
}),
api: new Ratelimit({
redis,
analytics: true,
prefix: "ratelimit:api",
limiter: Ratelimit.fixedWindow(API_KEY_RATE_LIMIT, "60s"),
rootKey: UNKEY_ROOT_KEY,
namespace: "api",
limit: API_KEY_RATE_LIMIT,
duration: "60s",
async: true,
timeout,
}),
ai: new Ratelimit({
redis,
analytics: true,
prefix: "ratelimit",
limiter: Ratelimit.fixedWindow(20, "1d"),
rootKey: UNKEY_ROOT_KEY,
namespace: "ai",
limit: 20,
duration: "1d",
async: true,
timeout,
}),
};
async function rateLimit({ rateLimitingType = "core", identifier }: RateLimitHelper) {
async function rateLimit({ rateLimitingType = "core", identifier, opts }: RateLimitHelper) {
if (isIpInBanListString(identifier)) {
return await limiter.forcedSlowMode.limit(identifier);
return await limiter.forcedSlowMode.limit(identifier, opts);
}
return await limiter[rateLimitingType].limit(identifier);
return await limiter[rateLimitingType].limit(identifier, opts);
}
return rateLimit;