diff --git a/src/request.ts b/src/request.ts index c1257a2..d4470f7 100644 --- a/src/request.ts +++ b/src/request.ts @@ -563,7 +563,8 @@ export class HttpRequest extends Macroable { * exists */ if (trustProxy(this.request.socket.remoteAddress!, this.#config.trustProxy)) { - host = this.header('X-Forwarded-Host') || host + const forwardedHost = this.header('X-Forwarded-Host') + host = forwardedHost ? forwardedHost.split(/\s*,\s*/)[0] : host } if (!host) { diff --git a/tests/request.spec.ts b/tests/request.spec.ts index 95591fe..153cd9a 100644 --- a/tests/request.spec.ts +++ b/tests/request.spec.ts @@ -612,6 +612,39 @@ test.group('Request', () => { assert.equal(body.ip, '10.10.10.10') }) + test('use the first forwarded host from a trusted proxy', async ({ assert }) => { + const { url } = await httpServer.create((req, res) => { + const request = new HttpRequestFactory() + .merge({ + req, + res, + encryption, + config: { + trustProxy: proxyAddr.compile('loopback'), + }, + }) + .create() + res.writeHead(200, { 'content-type': 'application/json' }) + res.end( + JSON.stringify({ + host: request.host(), + hostname: request.hostname(), + url: request.completeUrl(), + }) + ) + }) + + const { body } = await supertest(url) + .get('/') + .set('x-forwarded-host', 'client.example.test, edge.example.test') + + assert.deepEqual(body, { + host: 'client.example.test', + hostname: 'client.example.test', + url: 'http://client.example.test/', + }) + }) + test('trust all proxies when trustProxy is true', async ({ assert }) => { const { url } = await httpServer.create((req, res) => { req.headers['x-forwarded-for'] = '10.10.10.10'