summaryrefslogtreecommitdiff
path: root/packages/integrations/node/src/http-server.ts
blob: 8d463ba6ffeadd9862d2655305a403e89dfe3edd (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
import fs from 'fs';
import http from 'http';
import https from 'https';
import send from 'send';
import enableDestroy from 'server-destroy';
import { fileURLToPath } from 'url';

interface CreateServerOptions {
	client: URL;
	port: number;
	host: string | undefined;
	removeBase: (pathname: string) => string;
}

function parsePathname(pathname: string, host: string | undefined, port: number) {
	try {
		const urlPathname = new URL(pathname, `http://${host}:${port}`).pathname;
		return decodeURI(encodeURI(urlPathname));
	} catch (err) {
		return undefined;
	}
}

export function createServer(
	{ client, port, host, removeBase }: CreateServerOptions,
	handler: http.RequestListener
) {
	const listener: http.RequestListener = (req, res) => {
		if (req.url) {
			let pathname: string | undefined = removeBase(req.url);
			pathname = pathname[0] === '/' ? pathname : '/' + pathname;
			const encodedURI = parsePathname(pathname, host, port);

			if (!encodedURI) {
				res.writeHead(400);
				res.end('Bad request.');
				return res;
			}

			const stream = send(req, encodedURI, {
				root: fileURLToPath(client),
				dotfiles: pathname.startsWith('/.well-known/') ? 'allow' : 'deny',
			});

			let forwardError = false;

			stream.on('error', (err) => {
				if (forwardError) {
					// eslint-disable-next-line no-console
					console.error(err.toString());
					res.writeHead(500);
					res.end('Internal server error');
					return;
				}
				// File not found, forward to the SSR handler
				handler(req, res);
			});
			stream.on('directory', () => {
				// On directory find, redirect to the trailing slash
				let location: string;
				if (req.url!.includes('?')) {
					const [url = '', search] = req.url!.split('?');
					location = `${url}/?${search}`;
				} else {
					location = req.url + '/';
				}

				res.statusCode = 301;
				res.setHeader('Location', location);
				res.end(location);
			});
			stream.on('file', () => {
				forwardError = true;
			});
			stream.pipe(res);
		} else {
			handler(req, res);
		}
	};

	let httpServer:
		| http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>
		| https.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;

	if (process.env.SERVER_CERT_PATH && process.env.SERVER_KEY_PATH) {
		httpServer = https.createServer(
			{
				key: fs.readFileSync(process.env.SERVER_KEY_PATH),
				cert: fs.readFileSync(process.env.SERVER_CERT_PATH),
			},
			listener
		);
	} else {
		httpServer = http.createServer(listener);
	}
	httpServer.listen(port, host);
	enableDestroy(httpServer);

	// Resolves once the server is closed
	const closed = new Promise<void>((resolve, reject) => {
		httpServer.addListener('close', resolve);
		httpServer.addListener('error', reject);
	});

	return {
		host,
		port,
		closed() {
			return closed;
		},
		server: httpServer,
		stop: async () => {
			await new Promise((resolve, reject) => {
				httpServer.destroy((err) => (err ? reject(err) : resolve(undefined)));
			});
		},
	};
}