iceshrimp/packages/backend/src/server/api/limiter.ts

86 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-01-13 13:40:33 +09:00
import Limiter from "ratelimiter";
import { CacheableLocalUser, User } from "@/models/entities/user.js";
import Logger from "@/services/logger.js";
import { redisClient } from "../../db/redis.js";
import type { IEndpointMeta } from "./endpoints.js";
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
const logger = new Logger("limiter");
2017-01-23 18:25:52 +09:00
2023-01-13 13:40:33 +09:00
export const limiter = (
limitation: IEndpointMeta["limit"] & { key: NonNullable<string> },
actor: string,
) =>
new Promise<void>((ok, reject) => {
if (process.env.NODE_ENV === "test") ok();
2023-01-13 13:40:33 +09:00
const hasShortTermLimit = typeof limitation.minInterval === "number";
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
const hasLongTermLimit =
typeof limitation.duration === "number" &&
typeof limitation.max === "number";
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
if (hasShortTermLimit) {
min();
} else if (hasLongTermLimit) {
max();
} else {
ok();
}
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
// Short-term limit
function min(): void {
const minIntervalLimiter = new Limiter({
id: `${actor}:${limitation.key}:min`,
duration: limitation.minInterval,
max: 1,
db: redisClient,
});
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
minIntervalLimiter.get((err, info) => {
if (err) {
return reject("ERR");
}
2017-01-23 18:25:52 +09:00
2023-01-13 13:40:33 +09:00
logger.debug(
`${actor} ${limitation.key} min remaining: ${info.remaining}`,
);
2017-01-23 18:25:52 +09:00
2023-01-13 13:40:33 +09:00
if (info.remaining === 0) {
reject("BRIEF_REQUEST_INTERVAL");
2016-12-29 07:49:51 +09:00
} else {
2023-01-13 13:40:33 +09:00
if (hasLongTermLimit) {
max();
} else {
ok();
}
2016-12-29 07:49:51 +09:00
}
2023-01-13 13:40:33 +09:00
});
}
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
// Long term limit
function max(): void {
const limiter = new Limiter({
id: `${actor}:${limitation.key}`,
duration: limitation.duration,
max: limitation.max,
db: redisClient,
});
2016-12-29 07:49:51 +09:00
2023-01-13 13:40:33 +09:00
limiter.get((err, info) => {
if (err) {
return reject("ERR");
}
2017-01-23 18:25:52 +09:00
2023-01-13 13:40:33 +09:00
logger.debug(
`${actor} ${limitation.key} max remaining: ${info.remaining}`,
);
2017-01-23 18:25:52 +09:00
2023-01-13 13:40:33 +09:00
if (info.remaining === 0) {
reject("RATE_LIMIT_EXCEEDED");
} else {
ok();
}
});
}
});