From 37bee15932005aa1455d4bac0b5249828f5aaec3 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Sun, 21 Jan 2024 23:56:17 +0900 Subject: [PATCH] refactor(request): use `URL` instead of `path/resolve` and add a test (#125) Co-authored-by: Taku Amano --- src/request.ts | 10 ++-------- test/request.test.ts | 11 ++++++++++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/request.ts b/src/request.ts index 7fa4308..4f2284f 100644 --- a/src/request.ts +++ b/src/request.ts @@ -3,7 +3,6 @@ import type { IncomingMessage } from 'node:http' import type { Http2ServerRequest } from 'node:http2' -import { resolve } from 'node:path' import { Readable } from 'node:stream' const newRequestFromIncoming = ( @@ -42,13 +41,8 @@ const requestPrototype: Record = { }, get url() { - let path = this[incomingKey]['path'] - if (!path) { - const originalPath = this[incomingKey].url - path = /\.\./.test(originalPath) ? resolve(originalPath) : originalPath - this[incomingKey]['path'] = path - } - return `http://${this[incomingKey].headers.host}${path}` + const url = `http://${this[incomingKey].headers.host}${this[incomingKey].url}` + return /\.\./.test(url) ? new URL(url).href : url }, [getRequestCache]() { diff --git a/test/request.test.ts b/test/request.test.ts index 4444c9c..16eab9e 100644 --- a/test/request.test.ts +++ b/test/request.test.ts @@ -27,7 +27,16 @@ describe('Request', () => { } as IncomingMessage) expect(req).toBeInstanceOf(global.Request) expect(req.url).toBe('http://localhost/foo.txt') - // Check if cached value is returned correctly + }) + + it('Should resolve double dots in host header', async () => { + const req = newRequest({ + headers: { + host: 'localhost/..', + }, + url: '/foo.txt', + } as IncomingMessage) + expect(req).toBeInstanceOf(global.Request) expect(req.url).toBe('http://localhost/foo.txt') }) })