summary refs log tree commit diff
path: root/src/api/middlewares
diff options
context:
space:
mode:
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.ts215
-rw-r--r--src/api/middlewares/TestClient.ts154
-rw-r--r--src/api/middlewares/Translation.ts28
-rw-r--r--src/api/middlewares/index.ts5
8 files changed, 553 insertions, 0 deletions
diff --git a/src/api/middlewares/Authentication.ts b/src/api/middlewares/Authentication.ts
new file mode 100644
index 00000000..2d9ccf57
--- /dev/null
+++ b/src/api/middlewares/Authentication.ts
@@ -0,0 +1,72 @@
+import { NextFunction, Request, Response } from "express";
+import { HTTPError } from "@fosscord/util";
+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..35db3c6f
--- /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 "@fosscord/util";
+
+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..8a046e06
--- /dev/null
+++ b/src/api/middlewares/ErrorHandler.ts
@@ -0,0 +1,44 @@
+import { NextFunction, Request, Response } from "express";
+import { HTTPError } from "@fosscord/util";
+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..47180b62
--- /dev/null
+++ b/src/api/middlewares/RateLimit.ts
@@ -0,0 +1,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();
+	*/
+}
diff --git a/src/api/middlewares/TestClient.ts b/src/api/middlewares/TestClient.ts
new file mode 100644
index 00000000..c8ea57f6
--- /dev/null
+++ b/src/api/middlewares/TestClient.ts
@@ -0,0 +1,154 @@
+import express, { Request, Response, Application } from "express";
+import fs from "fs";
+import path from "path";
+import fetch, { Response as FetchResponse, Headers } from "node-fetch";
+import ProxyAgent from 'proxy-agent';
+import { Config } from "@fosscord/util";
+import { AssetCacheItem } from "../util/entities/AssetCacheItem"
+import { green } from "picocolors";
+
+const AssetsPath = path.join(__dirname, "..", "..", "..", "assets")
+
+export default function TestClient(app: Application) {
+	const agent = new ProxyAgent();
+	
+	//build client page
+	let html = fs.readFileSync(path.join(AssetsPath, "index.html"), { encoding: "utf8" });
+	html = applyEnv(html);
+	html = applyInlinePlugins(html);
+	html = applyPlugins(html);
+	html = applyPreloadPlugins(html);
+
+	//load asset cache
+	let newAssetCache: Map<string, AssetCacheItem> = new Map<string, AssetCacheItem>();
+	let assetCacheDir = path.join(AssetsPath, "cache");
+	if(process.env.ASSET_CACHE_DIR)
+		assetCacheDir = process.env.ASSET_CACHE_DIR
+
+	console.log(`[TestClient] ${green(`Using asset cache path: ${assetCacheDir}`)}`)
+	if(!fs.existsSync(assetCacheDir)) {
+		fs.mkdirSync(assetCacheDir);
+	}
+	if(fs.existsSync(path.join(assetCacheDir, "index.json"))) {
+		let rawdata = fs.readFileSync(path.join(assetCacheDir, "index.json"));
+		newAssetCache = new Map<string, AssetCacheItem>(Object.entries(JSON.parse(rawdata.toString())));
+	}
+
+	app.use("/assets", express.static(path.join(AssetsPath)));	
+	app.get("/assets/:file", async (req: Request, res: Response) => {
+		delete req.headers.host;
+		let response: FetchResponse;
+		let buffer: Buffer;
+		let assetCacheItem: AssetCacheItem = new AssetCacheItem(req.params.file);
+		if(newAssetCache.has(req.params.file)){
+			assetCacheItem = newAssetCache.get(req.params.file)!;
+			assetCacheItem.Headers.forEach((value: any, name: any) => {
+				res.set(name, value);
+			});
+		}
+		else {
+			console.log(`[TestClient] Downloading file not yet cached! Asset file: ${req.params.file}`);
+			response = await fetch(`https://discord.com/assets/${req.params.file}`, {
+				agent,
+				// @ts-ignore
+				headers: {
+					...req.headers
+				}
+			});
+			
+			//set cache info
+			assetCacheItem.Headers = Object.fromEntries(stripHeaders(response.headers));
+			assetCacheItem.FilePath = path.join(assetCacheDir, req.params.file);
+			assetCacheItem.Key = req.params.file;
+			//add to cache and save
+			newAssetCache.set(req.params.file, assetCacheItem);
+			fs.writeFileSync(path.join(assetCacheDir, "index.json"), JSON.stringify(Object.fromEntries(newAssetCache), null, 4));
+			//download file
+			fs.writeFileSync(assetCacheItem.FilePath, await response.buffer());
+		}
+		
+		assetCacheItem.Headers.forEach((value: string, name: string) => {
+			res.set(name, value);
+		});
+		return res.send(fs.readFileSync(assetCacheItem.FilePath));
+	});
+	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, "..", "..", "..", "assets", "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);
+	});
+
+	
+}
+
+function applyEnv(html: string): string {
+	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}\`,`);
+	}
+	return html;
+}
+
+function applyPlugins(html: string): string {
+	// plugins
+	let files = fs.readdirSync(path.join(AssetsPath, "plugins"));
+	let plugins = "";
+	files.forEach(x =>{if(x.endsWith(".js")) plugins += `<script src='/assets/plugins/${x}'></script>\n`; });
+	return html.replaceAll("<!-- plugin marker -->", plugins);
+}
+
+function applyInlinePlugins(html: string): string{
+	// inline plugins
+	let files = fs.readdirSync(path.join(AssetsPath, "inline-plugins"));
+	let plugins = "";
+	files.forEach(x =>{if(x.endsWith(".js")) plugins += `<script src='/assets/inline-plugins/${x}'></script>\n\n`; });
+	return html.replaceAll("<!-- inline plugin marker -->", plugins);
+}
+
+function applyPreloadPlugins(html: string): string{
+	//preload plugins
+	let files = fs.readdirSync(path.join(AssetsPath, "preload-plugins"));
+	let plugins = "";
+	files.forEach(x =>{if(x.endsWith(".js")) plugins += `<script>${fs.readFileSync(path.join(AssetsPath, "preload-plugins", x))}</script>\n`; });
+	return html.replaceAll("<!-- preload plugin marker -->", plugins);
+}
+
+function stripHeaders(headers: Headers): Headers {
+	[
+		"content-length",
+		"content-security-policy",
+		"strict-transport-security",
+		"set-cookie",
+		"transfer-encoding",
+		"expect-ct",
+		"access-control-allow-origin",
+		"content-encoding"
+	].forEach(headerName => {
+		headers.delete(headerName);
+	});
+	return headers;
+}
diff --git a/src/api/middlewares/Translation.ts b/src/api/middlewares/Translation.ts
new file mode 100644
index 00000000..64b03bf8
--- /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 + "/../../../assets/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";