update Rate Limit with new event transmission
This commit is contained in:
parent
0622ce0186
commit
8a197bbeaa
@ -64,7 +64,7 @@ export class FosscordServer extends Server {
|
|||||||
this.app = api;
|
this.app = api;
|
||||||
|
|
||||||
api.use(Authentication);
|
api.use(Authentication);
|
||||||
initRateLimits(api);
|
await initRateLimits(api);
|
||||||
await initTranslation(api);
|
await initTranslation(api);
|
||||||
|
|
||||||
this.routes = await this.registerRoutes(path.join(__dirname, "routes", "/"));
|
this.routes = await this.registerRoutes(path.join(__dirname, "routes", "/"));
|
||||||
|
@ -1,30 +1,16 @@
|
|||||||
// @ts-nocheck
|
// @ts-nocheck
|
||||||
import { db, Bucket, Config } from "@fosscord/util";
|
import { db, Bucket, Config, listenEvent, emitEvent } from "@fosscord/util";
|
||||||
import { NextFunction, Request, Response, Router } from "express";
|
import { NextFunction, Request, Response, Router } from "express";
|
||||||
import { getIpAdress } from "../util/ipAddress";
|
import { getIpAdress } from "../util/ipAddress";
|
||||||
import { API_PREFIX_TRAILING_SLASH } from "./Authentication";
|
import { API_PREFIX_TRAILING_SLASH } from "./Authentication";
|
||||||
|
|
||||||
// const Cache = new MongooseCache(
|
|
||||||
// db.collection("ratelimits"),
|
|
||||||
// [
|
|
||||||
// // TODO: uncomment $match and fix error: not receiving change events
|
|
||||||
// // { $match: { blocked: true } }
|
|
||||||
// ],
|
|
||||||
// { onlyEvents: false, array: true }
|
|
||||||
// );
|
|
||||||
|
|
||||||
// Docs: https://discord.com/developers/docs/topics/rate-limits
|
// Docs: https://discord.com/developers/docs/topics/rate-limits
|
||||||
|
|
||||||
/*
|
/*
|
||||||
? bucket limit? Max actions/sec per bucket?
|
? bucket limit? Max actions/sec per bucket?
|
||||||
|
|
||||||
TODO: ip rate limit
|
|
||||||
TODO: user rate limit
|
|
||||||
TODO: different rate limit for bots/user/oauth/webhook
|
|
||||||
TODO: delay database requests to include multiple queries
|
TODO: delay database requests to include multiple queries
|
||||||
TODO: different for methods (GET/POST)
|
TODO: different for methods (GET/POST)
|
||||||
TODO: bucket major parameters (channel_id, guild_id, webhook_id)
|
|
||||||
TODO: use config values
|
|
||||||
|
|
||||||
> IP addresses that make too many invalid HTTP requests are automatically and temporarily restricted from accessing the Discord API. Currently, this limit is 10,000 per 10 minutes. An invalid request is one that results in 401, 403, or 429 statuses.
|
> IP addresses that make too many invalid HTTP requests are automatically and temporarily restricted from accessing the Discord API. Currently, this limit is 10,000 per 10 minutes. An invalid request is one that results in 401, 403, or 429 statuses.
|
||||||
|
|
||||||
@ -32,6 +18,9 @@ TODO: use config values
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
var Cache = new Map<string, Bucket>();
|
||||||
|
const EventRateLimit = "ratelimit";
|
||||||
|
|
||||||
// TODO: FIX with new event handling
|
// TODO: FIX with new event handling
|
||||||
export default function RateLimit(opts: {
|
export default function RateLimit(opts: {
|
||||||
bucket?: string;
|
bucket?: string;
|
||||||
@ -46,9 +35,6 @@ export default function RateLimit(opts: {
|
|||||||
success?: boolean;
|
success?: boolean;
|
||||||
onlyIp?: boolean;
|
onlyIp?: boolean;
|
||||||
}): any {
|
}): any {
|
||||||
return (req, res, next) => next();
|
|
||||||
Cache.init(); // will only initalize it once
|
|
||||||
|
|
||||||
return async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
return async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
||||||
const bucket_id = opts.bucket || req.originalUrl.replace(API_PREFIX_TRAILING_SLASH, "");
|
const bucket_id = opts.bucket || req.originalUrl.replace(API_PREFIX_TRAILING_SLASH, "");
|
||||||
var user_id = getIpAdress(req);
|
var user_id = getIpAdress(req);
|
||||||
@ -59,7 +45,7 @@ export default function RateLimit(opts: {
|
|||||||
if (opts.GET && ["GET", "OPTIONS", "HEAD"].includes(req.method)) max_hits = opts.GET;
|
if (opts.GET && ["GET", "OPTIONS", "HEAD"].includes(req.method)) max_hits = opts.GET;
|
||||||
else if (opts.MODIFY && ["POST", "DELETE", "PATCH", "PUT"].includes(req.method)) max_hits = opts.MODIFY;
|
else if (opts.MODIFY && ["POST", "DELETE", "PATCH", "PUT"].includes(req.method)) max_hits = opts.MODIFY;
|
||||||
|
|
||||||
const offender = Cache.data?.find((x: Bucket) => x.user_id == user_id && x.id === bucket_id) as Bucket | null;
|
const offender = Cache.get(user_id + bucket_id) as Bucket | null;
|
||||||
|
|
||||||
if (offender && offender.blocked) {
|
if (offender && offender.blocked) {
|
||||||
const reset = offender.expires_at.getTime();
|
const reset = offender.expires_at.getTime();
|
||||||
@ -88,6 +74,7 @@ export default function RateLimit(opts: {
|
|||||||
offender.blocked = false;
|
offender.blocked = false;
|
||||||
// mongodb ttl didn't update yet -> manually update/delete
|
// mongodb ttl didn't update yet -> manually update/delete
|
||||||
db.collection("ratelimits").updateOne({ id: bucket_id, user_id }, { $set: offender });
|
db.collection("ratelimits").updateOne({ id: bucket_id, user_id }, { $set: offender });
|
||||||
|
Cache.delete(user_id + bucket_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
@ -108,8 +95,18 @@ export default function RateLimit(opts: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function initRateLimits(app: Router) {
|
export async function initRateLimits(app: Router) {
|
||||||
const { routes, global, ip, error } = Config.get().limits.rate;
|
const { routes, global, ip, error } = Config.get().limits.rate;
|
||||||
|
await listenEvent(EventRateLimit, (event) => {
|
||||||
|
Cache.set(event.channel_id, event.data);
|
||||||
|
event.acknowledge?.();
|
||||||
|
});
|
||||||
|
|
||||||
|
setInterval(() => {
|
||||||
|
Cache.forEach((x, key) => {
|
||||||
|
if (Date.now() > x.expires_at) Cache.delete(key);
|
||||||
|
});
|
||||||
|
}, 1000 * 60 * 10);
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
RateLimit({
|
RateLimit({
|
||||||
@ -134,32 +131,36 @@ export function initRateLimits(app: Router) {
|
|||||||
app.use("/auth/register", RateLimit({ onlyIp: true, success: true, ...routes.auth.register }));
|
app.use("/auth/register", RateLimit({ onlyIp: true, success: true, ...routes.auth.register }));
|
||||||
}
|
}
|
||||||
|
|
||||||
function hitRoute(opts: { user_id: string; bucket_id: string; max_hits: number; window: number }) {
|
async function hitRoute(opts: { user_id: string; bucket_id: string; max_hits: number; window: number }) {
|
||||||
return db.collection("ratelimits").updateOne(
|
const filter = { id: opts.bucket_id, user_id: opts.user_id };
|
||||||
{ id: opts.bucket_id, user_id: opts.user_id },
|
const { value } = await db.collection("ratelimits").findOneAndUpdate(
|
||||||
[
|
filter,
|
||||||
{
|
{
|
||||||
$replaceRoot: {
|
$setOnInsert: {
|
||||||
newRoot: {
|
id: opts.bucket_id,
|
||||||
// similar to $setOnInsert
|
user_id: opts.user_id,
|
||||||
$mergeObjects: [
|
expires_at: new Date(Date.now() + opts.window * 1000)
|
||||||
{
|
|
||||||
id: opts.bucket_id,
|
|
||||||
user_id: opts.user_id,
|
|
||||||
expires_at: new Date(Date.now() + opts.window * 1000)
|
|
||||||
},
|
|
||||||
"$$ROOT"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
{
|
$inc: {
|
||||||
$set: {
|
hits: 1
|
||||||
hits: { $sum: [{ $ifNull: ["$hits", 0] }, 1] },
|
|
||||||
blocked: { $gte: ["$hits", opts.max_hits] }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
],
|
// Conditionally update blocked doesn't work
|
||||||
{ upsert: true }
|
},
|
||||||
|
{ upsert: true, returnDocument: "before" }
|
||||||
);
|
);
|
||||||
|
if (!value) return;
|
||||||
|
const updateBlock = !value.blocked && value.hits >= opts.max_hits;
|
||||||
|
|
||||||
|
if (updateBlock) {
|
||||||
|
value.blocked = true;
|
||||||
|
Cache.set(opts.user_id + opts.bucket_id, value);
|
||||||
|
await emitEvent({
|
||||||
|
channel_id: EventRateLimit,
|
||||||
|
event: EventRateLimit,
|
||||||
|
data: value
|
||||||
|
});
|
||||||
|
await db.collection("ratelimits").updateOne(filter, { $set: { blocked: true } });
|
||||||
|
} else {
|
||||||
|
Cache.delete(opts.user_id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user