summary refs log tree commit diff
path: root/src/api/middlewares/RateLimit.ts
blob: 47180b62bf2274d201123a8a4fcc21df59cc3364 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import { Config, getRights, listenEvent, Rights } from "@fosscord/util";
import { NextFunction, Request, Response, Router } from "express";
import { getIpAdress } from "@fosscord/api";
import { API_PREFIX_TRAILING_SLASH } from "./Authentication";

// Docs: https://discord.com/developers/docs/topics/rate-limits

// TODO: use better caching (e.g. redis) as else it creates to much pressure on the database

/*
? bucket limit? Max actions/sec per bucket?
(ANSWER: a small fosscord instance might not need a complex rate limiting system)

TODO: delay database requests to include multiple queries
TODO: different for methods (GET/POST)

> 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.

> All bots can make up to 50 requests per second to our API. This is independent of any individual rate limit on a route. If your bot gets big enough, based on its functionality, it may be impossible to stay below 50 requests per second during normal operations.

*/

type RateLimit = {
	id: "global" | "error" | string;
	executor_id: string;
	hits: number;
	blocked: boolean;
	expires_at: Date;
};

let Cache = new Map<string, RateLimit>();
const EventRateLimit = "RATELIMIT";

export default function rateLimit(opts: {
	bucket?: string;
	window: number;
	count: number;
	bot?: number;
	webhook?: number;
	oauth?: number;
	GET?: number;
	MODIFY?: number;
	error?: boolean;
	success?: boolean;
	onlyIp?: boolean;
}): any {
	return async (req: Request, res: Response, next: NextFunction): Promise<any> => {
		// exempt user? if so, immediately short circuit
		if (req.user_id) {
			const rights = await getRights(req.user_id);
			if (rights.has("BYPASS_RATE_LIMITS")) return;
		}

		const bucket_id = opts.bucket || req.originalUrl.replace(API_PREFIX_TRAILING_SLASH, "");
		let executor_id = getIpAdress(req);
		if (!opts.onlyIp && req.user_id) executor_id = req.user_id;

		let max_hits = opts.count;
		if (opts.bot && req.user_bot) max_hits = opts.bot;
		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;

		let offender = Cache.get(executor_id + bucket_id);

		if (offender) {
			let reset = offender.expires_at.getTime();
			let resetAfterMs = reset - Date.now();
			let resetAfterSec = Math.ceil(resetAfterMs / 1000);

			if (resetAfterMs <= 0) {
				offender.hits = 0;
				offender.expires_at = new Date(Date.now() + opts.window * 1000);
				offender.blocked = false;

				Cache.delete(executor_id + bucket_id);
			}

			if (offender.blocked) {
				const global = bucket_id === "global";
				// each block violation pushes the expiry one full window further
				reset += opts.window * 1000;
				offender.expires_at = new Date(offender.expires_at.getTime() + opts.window * 1000);
				resetAfterMs = reset - Date.now();
				resetAfterSec = Math.ceil(resetAfterMs / 1000);

				console.log("blocked bucket: " + bucket_id, { resetAfterMs });
				return (
					res
						.status(429)
						.set("X-RateLimit-Limit", `${max_hits}`)
						.set("X-RateLimit-Remaining", "0")
						.set("X-RateLimit-Reset", `${reset}`)
						.set("X-RateLimit-Reset-After", `${resetAfterSec}`)
						.set("X-RateLimit-Global", `${global}`)
						.set("Retry-After", `${Math.ceil(resetAfterSec)}`)
						.set("X-RateLimit-Bucket", `${bucket_id}`)
						// TODO: error rate limit message translation
						.send({ message: "You are being rate limited.", retry_after: resetAfterSec, global })
				);
			}
		}

		next();
		const hitRouteOpts = { bucket_id, executor_id, max_hits, window: opts.window };

		if (opts.error || opts.success) {
			res.once("finish", () => {
				// check if error and increment error rate limit
				if (res.statusCode >= 400 && opts.error) {
					return hitRoute(hitRouteOpts);
				} else if (res.statusCode >= 200 && res.statusCode < 300 && opts.success) {
					return hitRoute(hitRouteOpts);
				}
			});
		} else {
			return hitRoute(hitRouteOpts);
		}
	};
}

export async function initRateLimits(app: Router) {
	const { routes, global, ip, error, disabled } = Config.get().limits.rate;
	if (disabled) return;
	await listenEvent(EventRateLimit, (event) => {
		Cache.set(event.channel_id as string, event.data);
		event.acknowledge?.();
	});
	// await RateLimit.delete({ expires_at: LessThan(new Date().toISOString()) }); // cleans up if not already deleted, morethan -> older date
	// const limits = await RateLimit.find({ blocked: true });
	// limits.forEach((limit) => {
	// 	Cache.set(limit.executor_id, limit);
	// });

	setInterval(() => {
		Cache.forEach((x, key) => {
			if (new Date() > x.expires_at) {
				Cache.delete(key);
				// RateLimit.delete({ executor_id: key });
			}
		});
	}, 1000 * 60);

	app.use(
		rateLimit({
			bucket: "global",
			onlyIp: true,
			...ip
		})
	);
	app.use(rateLimit({ bucket: "global", ...global }));
	app.use(
		rateLimit({
			bucket: "error",
			error: true,
			onlyIp: true,
			...error
		})
	);
	app.use("/guilds/:id", rateLimit(routes.guild));
	app.use("/webhooks/:id", rateLimit(routes.webhook));
	app.use("/channels/:id", rateLimit(routes.channel));
	app.use("/auth/login", rateLimit(routes.auth.login));
	app.use("/auth/register", rateLimit({ onlyIp: true, success: true, ...routes.auth.register }));
}

async function hitRoute(opts: { executor_id: string; bucket_id: string; max_hits: number; window: number; }) {
	const id = opts.executor_id + opts.bucket_id;
	let limit = Cache.get(id);
	if (!limit) {
		limit = {
			id: opts.bucket_id,
			executor_id: opts.executor_id,
			expires_at: new Date(Date.now() + opts.window * 1000),
			hits: 0,
			blocked: false
		};
		Cache.set(id, limit);
	}

	limit.hits++;
	if (limit.hits >= opts.max_hits) {
		limit.blocked = true;
	}

	/*
	let ratelimit = await RateLimit.findOne({ where: { id: opts.bucket_id, executor_id: opts.executor_id } });
	if (!ratelimit) {
		ratelimit = new RateLimit({
			id: opts.bucket_id,
			executor_id: opts.executor_id,
			expires_at: new Date(Date.now() + opts.window * 1000),
			hits: 0,
			blocked: false
		});
	}

	ratelimit.hits++;

	const updateBlock = !ratelimit.blocked && ratelimit.hits >= opts.max_hits;

	if (updateBlock) {
		ratelimit.blocked = true;
		Cache.set(opts.executor_id + opts.bucket_id, ratelimit);
		await emitEvent({
			channel_id: EventRateLimit,
			event: EventRateLimit,
			data: ratelimit
		});
	} else {
		Cache.delete(opts.executor_id);
	}

	await ratelimit.save();
	*/
}