summary refs log tree commit diff
path: root/src/api/middlewares
diff options
context:
space:
mode:
authorMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2022-09-25 18:24:21 +1000
committerMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2022-09-25 23:35:18 +1000
commit0d23eaba09a4878520bf346af4cead90d76829fc (patch)
treed930eacceff0b407b44abe55f01d8e3c5dfbfa34 /src/api/middlewares
parentAllow edited_timestamp to passthrough in handleMessage (diff)
downloadserver-0d23eaba09a4878520bf346af4cead90d76829fc.tar.xz
Refactor to mono-repo + upgrade packages
Diffstat (limited to 'src/api/middlewares')
-rw-r--r--src/api/middlewares/Authentication.ts72
-rw-r--r--src/api/middlewares/BodyParser.ts19
-rw-r--r--src/api/middlewares/CORS.ts16
-rw-r--r--src/api/middlewares/ErrorHandler.ts44
-rw-r--r--src/api/middlewares/RateLimit.ts208
-rw-r--r--src/api/middlewares/TestClient.ts107
-rw-r--r--src/api/middlewares/Translation.ts28
-rw-r--r--src/api/middlewares/index.ts5
8 files changed, 499 insertions, 0 deletions
diff --git a/src/api/middlewares/Authentication.ts b/src/api/middlewares/Authentication.ts
new file mode 100644
index 00000000..1df7911b
--- /dev/null
+++ b/src/api/middlewares/Authentication.ts
@@ -0,0 +1,72 @@
+import { NextFunction, Request, Response } from "express";
+import { HTTPError } from "lambert-server";
+import { checkToken, Config, Rights } from "@fosscord/util";
+
+export const NO_AUTHORIZATION_ROUTES = [
+	// Authentication routes
+	"/auth/login",
+	"/auth/register",
+	"/auth/location-metadata",
+	"/auth/mfa/totp",
+	// Routes with a seperate auth system
+	"/webhooks/",
+	// Public information endpoints 
+	"/ping",
+	"/gateway",
+	"/experiments",
+	"/updates",
+	"/downloads/",
+	"/scheduled-maintenances/upcoming.json",
+	// Public kubernetes integration
+	"/-/readyz",
+	"/-/healthz",
+	// Client analytics
+	"/science",
+	"/track",
+	// Public policy pages
+	"/policies/instance",
+	// Asset delivery
+	/\/guilds\/\d+\/widget\.(json|png)/
+];
+
+export const API_PREFIX = /^\/api(\/v\d+)?/;
+export const API_PREFIX_TRAILING_SLASH = /^\/api(\/v\d+)?\//;
+
+declare global {
+	namespace Express {
+		interface Request {
+			user_id: string;
+			user_bot: boolean;
+			token: string;
+			rights: Rights;
+		}
+	}
+}
+
+export async function Authentication(req: Request, res: Response, next: NextFunction) {
+	if (req.method === "OPTIONS") return res.sendStatus(204);
+	const url = req.url.replace(API_PREFIX, "");
+	if (url.startsWith("/invites") && req.method === "GET") return next();
+	if (
+		NO_AUTHORIZATION_ROUTES.some((x) => {
+			if (typeof x === "string") return url.startsWith(x);
+			return x.test(url);
+		})
+	)
+		return next();
+	if (!req.headers.authorization) return next(new HTTPError("Missing Authorization Header", 401));
+
+	try {
+		const { jwtSecret } = Config.get().security;
+
+		const { decoded, user }: any = await checkToken(req.headers.authorization, jwtSecret);
+
+		req.token = decoded;
+		req.user_id = decoded.id;
+		req.user_bot = user.bot;
+		req.rights = new Rights(Number(user.rights));
+		return next();
+	} catch (error: any) {
+		return next(new HTTPError(error?.toString(), 400));
+	}
+}
diff --git a/src/api/middlewares/BodyParser.ts b/src/api/middlewares/BodyParser.ts
new file mode 100644
index 00000000..4cb376bc
--- /dev/null
+++ b/src/api/middlewares/BodyParser.ts
@@ -0,0 +1,19 @@
+import bodyParser, { OptionsJson } from "body-parser";
+import { NextFunction, Request, Response } from "express";
+import { HTTPError } from "lambert-server";
+
+export function BodyParser(opts?: OptionsJson) {
+	const jsonParser = bodyParser.json(opts);
+
+	return (req: Request, res: Response, next: NextFunction) => {
+		if (!req.headers["content-type"]) req.headers["content-type"] = "application/json";
+
+		jsonParser(req, res, (err) => {
+			if (err) {
+				// TODO: different errors for body parser (request size limit, wrong body type, invalid body, ...)
+				return next(new HTTPError("Invalid Body", 400));
+			}
+			next();
+		});
+	};
+}
diff --git a/src/api/middlewares/CORS.ts b/src/api/middlewares/CORS.ts
new file mode 100644
index 00000000..20260cf9
--- /dev/null
+++ b/src/api/middlewares/CORS.ts
@@ -0,0 +1,16 @@
+import { NextFunction, Request, Response } from "express";
+
+// TODO: config settings
+
+export function CORS(req: Request, res: Response, next: NextFunction) {
+	res.set("Access-Control-Allow-Origin", "*");
+	// TODO: use better CSP
+	res.set(
+		"Content-security-policy",
+		"default-src *  data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval'; script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src * data: blob: 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src * data: blob: ; style-src * data: blob: 'unsafe-inline'; font-src * data: blob: 'unsafe-inline';"
+	);
+	res.set("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers") || "*");
+	res.set("Access-Control-Allow-Methods", req.header("Access-Control-Request-Methods") || "*");
+
+	next();
+}
diff --git a/src/api/middlewares/ErrorHandler.ts b/src/api/middlewares/ErrorHandler.ts
new file mode 100644
index 00000000..2012b91c
--- /dev/null
+++ b/src/api/middlewares/ErrorHandler.ts
@@ -0,0 +1,44 @@
+import { NextFunction, Request, Response } from "express";
+import { HTTPError } from "lambert-server";
+import { ApiError, FieldError } from "@fosscord/util";
+const EntityNotFoundErrorRegex = /"(\w+)"/;
+
+export function ErrorHandler(error: Error, req: Request, res: Response, next: NextFunction) {
+	if (!error) return next();
+
+	try {
+		let code = 400;
+		let httpcode = code;
+		let message = error?.toString();
+		let errors = undefined;
+
+		if (error instanceof HTTPError && error.code) code = httpcode = error.code;
+		else if (error instanceof ApiError) {
+			code = error.code;
+			message = error.message;
+			httpcode = error.httpStatus;
+		} else if (error.name === "EntityNotFoundError") {
+			message = `${error.message.match(EntityNotFoundErrorRegex)?.[1] || "Item"} could not be found`;
+			code = httpcode = 404;
+		} else if (error instanceof FieldError) {
+			code = Number(error.code);
+			message = error.message;
+			errors = error.errors;
+		} else {
+			console.error(`[Error] ${code} ${req.url}\n`, errors || error, "\nbody:", req.body);
+
+			if (req.server?.options?.production) {
+				// don't expose internal errors to the user, instead human errors should be thrown as HTTPError
+				message = "Internal Server Error";
+			}
+			code = httpcode = 500;
+		}
+
+		if (httpcode > 511) httpcode = 400;
+
+		res.status(httpcode).json({ code: code, message, errors });
+	} catch (error) {
+		console.error(`[Internal Server Error] 500`, error);
+		return res.status(500).json({ code: 500, message: "Internal Server Error" });
+	}
+}
diff --git a/src/api/middlewares/RateLimit.ts b/src/api/middlewares/RateLimit.ts
new file mode 100644
index 00000000..57645c0b
--- /dev/null
+++ b/src/api/middlewares/RateLimit.ts
@@ -0,0 +1,208 @@
+import { getIpAdress } from "@fosscord/api";
+import { Config, getRights, listenEvent } from "@fosscord/util";
+import { NextFunction, Request, Response, Router } from "express";
+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 next();
+		}
+
+		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} ${executor_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;
+	console.log("Enabling rate limits...");
+	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();
+	*/
+}
\ No newline at end of file
diff --git a/src/api/middlewares/TestClient.ts b/src/api/middlewares/TestClient.ts
new file mode 100644
index 00000000..0bd63eb5
--- /dev/null
+++ b/src/api/middlewares/TestClient.ts
@@ -0,0 +1,107 @@
+import express, { Request, Response, Application } from "express";
+import fs from "fs";
+import path from "path";
+import fetch, { Response as FetchResponse } from "node-fetch";
+import ProxyAgent from 'proxy-agent';
+import { Config } from "@fosscord/util";
+
+export default function TestClient(app: Application) {
+	const agent = new ProxyAgent();
+	const assetCache = new Map<string, { response: FetchResponse; buffer: Buffer; }>();
+	const indexHTML = fs.readFileSync(path.join(__dirname, "..", "..", "..", "assets", "client_test", "index.html"), { encoding: "utf8" });
+
+	var html = indexHTML;
+	const CDN_ENDPOINT = (Config.get().cdn.endpointClient || Config.get()?.cdn.endpointPublic || process.env.CDN || "").replace(
+		/(https?)?(:\/\/?)/g,
+		""
+	);
+	const GATEWAY_ENDPOINT = Config.get().gateway.endpointClient || Config.get()?.gateway.endpointPublic || process.env.GATEWAY || "";
+
+	if (CDN_ENDPOINT) {
+		html = html.replace(/CDN_HOST: .+/, `CDN_HOST: \`${CDN_ENDPOINT}\`,`);
+	}
+	if (GATEWAY_ENDPOINT) {
+		html = html.replace(/GATEWAY_ENDPOINT: .+/, `GATEWAY_ENDPOINT: \`${GATEWAY_ENDPOINT}\`,`);
+	}
+	// inline plugins
+	var files = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "preload-plugins"));
+	var plugins = "";
+	files.forEach(x => { if (x.endsWith(".js")) plugins += `<script>${fs.readFileSync(path.join(__dirname, "..", "..", "..", "assets", "preload-plugins", x))}</script>\n`; });
+	html = html.replaceAll("<!-- preload plugin marker -->", plugins);
+
+	// plugins
+	files = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "plugins"));
+	plugins = "";
+	files.forEach(x => { if (x.endsWith(".js")) plugins += `<script src='/assets/plugins/${x}'></script>\n`; });
+	html = html.replaceAll("<!-- plugin marker -->", plugins);
+	//preload plugins
+	files = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "preload-plugins"));
+	plugins = "";
+	files.forEach(x => { if (x.endsWith(".js")) plugins += `<script>${fs.readFileSync(path.join(__dirname, "..", "..", "..", "assets", "preload-plugins", x))}</script>\n`; });
+	html = html.replaceAll("<!-- preload plugin marker -->", plugins);
+
+
+	app.use("/assets", express.static(path.join(__dirname, "..", "..", "assets")));
+
+	app.get("/assets/:file", async (req: Request, res: Response) => {
+		delete req.headers.host;
+		var response: FetchResponse;
+		var buffer: Buffer;
+		const cache = assetCache.get(req.params.file);
+		if (!cache) {
+			response = await fetch(`https://discord.com/assets/${req.params.file}`, {
+				agent,
+				// @ts-ignore
+				headers: {
+					...req.headers
+				}
+			});
+			buffer = await response.buffer();
+		} else {
+			response = cache.response;
+			buffer = cache.buffer;
+		}
+
+		response.headers.forEach((value, name) => {
+			if (
+				[
+					"content-length",
+					"content-security-policy",
+					"strict-transport-security",
+					"set-cookie",
+					"transfer-encoding",
+					"expect-ct",
+					"access-control-allow-origin",
+					"content-encoding"
+				].includes(name.toLowerCase())
+			) {
+				return;
+			}
+			res.set(name, value);
+		});
+		assetCache.set(req.params.file, { buffer, response });
+
+		return res.send(buffer);
+	});
+	app.get("/developers*", (req: Request, res: Response) => {
+		const { useTestClient } = Config.get().client;
+		res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24);
+		res.set("content-type", "text/html");
+
+		if (!useTestClient) return res.send("Test client is disabled on this instance. Use a stand-alone client to connect this instance.");
+
+		res.send(fs.readFileSync(path.join(__dirname, "..", "..", "client_test", "developers.html"), { encoding: "utf8" }));
+	});
+	app.get("*", (req: Request, res: Response) => {
+		const { useTestClient } = Config.get().client;
+		res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24);
+		res.set("content-type", "text/html");
+
+		if (req.url.startsWith("/api") || req.url.startsWith("/__development")) return;
+
+		if (!useTestClient) return res.send("Test client is disabled on this instance. Use a stand-alone client to connect this instance.");
+		if (req.url.startsWith("/invite")) return res.send(html.replace("9b2b7f0632acd0c5e781", "9f24f709a3de09b67c49"));
+
+		res.send(html);
+	});
+}
\ No newline at end of file
diff --git a/src/api/middlewares/Translation.ts b/src/api/middlewares/Translation.ts
new file mode 100644
index 00000000..741d6baf
--- /dev/null
+++ b/src/api/middlewares/Translation.ts
@@ -0,0 +1,28 @@
+import fs from "fs";
+import path from "path";
+import i18next from "i18next";
+import i18nextMiddleware from "i18next-http-middleware";
+import i18nextBackend from "i18next-node-fs-backend";
+import { Router } from "express";
+
+export async function initTranslation(router: Router) {
+	const languages = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "locales"));
+	const namespaces = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "locales", "en"));
+	const ns = namespaces.filter((x) => x.endsWith(".json")).map((x) => x.slice(0, x.length - 5));
+
+	await i18next
+		.use(i18nextBackend)
+		.use(i18nextMiddleware.LanguageDetector)
+		.init({
+			preload: languages,
+			// debug: true,
+			fallbackLng: "en",
+			ns,
+			backend: {
+				loadPath: __dirname + "/../../locales/{{lng}}/{{ns}}.json"
+			},
+			load: "all"
+		});
+
+	router.use(i18nextMiddleware.handle(i18next, {}));
+}
diff --git a/src/api/middlewares/index.ts b/src/api/middlewares/index.ts
new file mode 100644
index 00000000..f0c50dbe
--- /dev/null
+++ b/src/api/middlewares/index.ts
@@ -0,0 +1,5 @@
+export * from "./Authentication";
+export * from "./BodyParser";
+export * from "./CORS";
+export * from "./ErrorHandler";
+export * from "./RateLimit";