summary refs log tree commit diff
path: root/api/src/middlewares/TestClient.ts
blob: 79f8f442eef03fc2732ffdf394431ad0e00c61d6 (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
import express, { Request, Response, Application } from "express";
import fs from "fs";
import path from "path";
import fetch, { Response as FetchResponse } from "node-fetch";
import { Config } from "@fosscord/util";

export default function TestClient(app: Application) {
	const assetCache = new Map<string, { response: FetchResponse; buffer: Buffer }>();
	const indexHTML = fs.readFileSync(path.join(__dirname, "..", "..", "client_test", "index.html"), { encoding: "utf8" });

	var html = indexHTML;
	const CDN_ENDPOINT = (Config.get().cdn.endpointClient || Config.get()?.cdn.endpoint || process.env.CDN || "").replace(
		/(https?)?(:\/\/?)/g,
		""
	);
	const GATEWAY_ENDPOINT = Config.get().gateway.endpointClient || Config.get()?.gateway.endpoint || 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}\`,`);
	}

	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}`, {
				// @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("*", (req: Request, res: Response) => {
		res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24);
		res.set("content-type", "text/html");

		if (req.url.startsWith("/invite")) return res.send(html.replace("9b2b7f0632acd0c5e781", "9f24f709a3de09b67c49"));

		res.send(html);
	});
}