diff options
author | 2023-04-04 15:48:28 +0200 | |
---|---|---|
committer | 2023-04-04 15:48:28 +0200 | |
commit | 4cc1bf61b832dba9aab1916b56f5260ceac2d97d (patch) | |
tree | 58da283fba308ca9b25653f03f14e8c0f39f3c8d /packages/integrations/node/src/http-server.ts | |
parent | 1ec1df12641290ec8b3a417a6284fd8d752c02bf (diff) | |
download | astro-4cc1bf61b832dba9aab1916b56f5260ceac2d97d.tar.gz astro-4cc1bf61b832dba9aab1916b56f5260ceac2d97d.tar.zst astro-4cc1bf61b832dba9aab1916b56f5260ceac2d97d.zip |
fix(node): Fix malformed URLs crashing the server in certain cases (#6746)
Diffstat (limited to 'packages/integrations/node/src/http-server.ts')
-rw-r--r-- | packages/integrations/node/src/http-server.ts | 22 |
1 files changed, 19 insertions, 3 deletions
diff --git a/packages/integrations/node/src/http-server.ts b/packages/integrations/node/src/http-server.ts index f0dde82d5..850d61bbb 100644 --- a/packages/integrations/node/src/http-server.ts +++ b/packages/integrations/node/src/http-server.ts @@ -12,16 +12,32 @@ interface CreateServerOptions { 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 = removeBase(req.url); + let pathname: string | undefined = removeBase(req.url); pathname = pathname[0] === '/' ? pathname : '/' + pathname; - pathname = new URL(pathname, `http://${host}:${port}`).pathname; - const stream = send(req, encodeURI(decodeURI(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', }); |