diff --git a/src/plugins/default/logger-plugin.ts b/src/plugins/default/logger-plugin.ts index 4c302bba..a05b3662 100644 --- a/src/plugins/default/logger-plugin.ts +++ b/src/plugins/default/logger-plugin.ts @@ -2,6 +2,7 @@ import { URL } from 'url'; import { Plugin } from '../../types'; import { getLogger } from '../../logger'; import type { IncomingMessage } from 'node:http'; +import { getPort } from '../../utils/logger-plugin'; type ExpressRequest = { /** Express req.baseUrl */ @@ -43,18 +44,19 @@ export const loggerPlugin: Plugin = (proxyServer, options) => { const originalUrl = req.originalUrl ?? `${req.baseUrl || ''}${req.url}`; // construct targetUrl - // const port = proxyRes.req?.socket?.autoSelectFamilyAttemptedAddresses?.[0]?.split(':')?.reverse()[0]; //.at(-1), - const port = Object.keys(proxyRes.req?.agent?.sockets || {})?.[0]?.split(':')[1]; + const port = getPort(proxyRes.req?.agent?.sockets); const obj = { protocol: proxyRes.req.protocol, host: proxyRes.req.host, - port: port, pathname: proxyRes.req.path, } as URL; const target = new URL(`${obj.protocol}//${obj.host}${obj.pathname}`); - target.port = obj.port; // optional port + + if (port) { + target.port = port; + } const targetUrl = target.toString(); const exchange = `[HPM] ${req.method} ${originalUrl} -> ${targetUrl} [${proxyRes.statusCode}]`; diff --git a/src/utils/logger-plugin.ts b/src/utils/logger-plugin.ts new file mode 100644 index 00000000..869e5827 --- /dev/null +++ b/src/utils/logger-plugin.ts @@ -0,0 +1,11 @@ +import type { Agent } from 'node:http'; + +export type Sockets = Pick; + +/** + * Get port from target + * Using proxyRes.req.agent.sockets to determine the target port + */ +export function getPort(sockets?: Sockets): string | undefined { + return Object.keys(sockets || {})?.[0]?.split(':')[1]; +} diff --git a/test/unit/utils/logger-plugin.spec.ts b/test/unit/utils/logger-plugin.spec.ts new file mode 100644 index 00000000..c10dcae8 --- /dev/null +++ b/test/unit/utils/logger-plugin.spec.ts @@ -0,0 +1,23 @@ +import { getPort, type Sockets } from '../../../src/utils/logger-plugin'; + +describe('getPort()', () => { + it('should return port from proxyRes.req.agent.sockets', () => { + const sockets = { + 'jsonplaceholder.typicode.com:80:': [], + } as unknown as Sockets; + + expect(getPort(sockets)).toBe('80'); + }); + + it('should handle missing "sockets" from proxyRes?.req?.agent?.sockets', () => { + const sockets = undefined; + + expect(getPort(sockets)).toBe(undefined); + }); + + it('should handle empty "sockets" from proxyRes?.req?.agent?.sockets', () => { + const sockets = {} as unknown as Sockets; + + expect(getPort(sockets)).toBe(undefined); + }); +});