From 118eb5516da92bfff72f7e0f75cee9dc3a52db29 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 13:51:55 -0500 Subject: [PATCH] refactor(http): extract mergeInjectedHeaders pure helper Signed-off-by: Diego Resendez --- src/http/headers.ts | 32 ++++++++++++++++++++++++++++++++ src/http/server.ts | 24 +++--------------------- test/http-headers.test.ts | 25 +++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 21 deletions(-) create mode 100644 src/http/headers.ts create mode 100644 test/http-headers.test.ts diff --git a/src/http/headers.ts b/src/http/headers.ts new file mode 100644 index 0000000..d9fb64e --- /dev/null +++ b/src/http/headers.ts @@ -0,0 +1,32 @@ +import { mergeVary } from '../security'; + +/** + * Merges a handler's response headers with authoritative `injected` headers + * (security + CORS). Injected keys win case-insensitively; `vary` is merged. + * Extracted from the Node writeHead patch so app.fetch shares the exact logic. + */ +export function mergeInjectedHeaders( + handlerHeaders: Record | undefined, + injected: Record, +): Record { + const merged: Record = {}; + const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase())); + let handlerVary: string | undefined; + + if (handlerHeaders) + for (const key of Object.keys(handlerHeaders)) { + const lowerKey = key.toLowerCase(); + + if (lowerKey === 'vary') { + handlerVary = handlerHeaders[key]; + continue; + } + + if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; + } + + Object.assign(merged, injected); + if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); + else if (handlerVary !== undefined) merged['vary'] = handlerVary; + return merged; +} diff --git a/src/http/server.ts b/src/http/server.ts index 719d8ff..70e39fb 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -4,12 +4,13 @@ import { renderError, type ErrorRequest, type ErrorRenderer } from '../transform import { isHttpError, HttpError, NotFound } from '../signals'; import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; import type { Bus } from '../bus'; -import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security'; +import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; import { matchRoute, allowedMethods, parseQuery } from './router'; import { readBody, deriveSecure, deriveIp } from './request'; import { pickEncoder, pipeStream } from './stream'; import { attachWs } from './ws'; +import { mergeInjectedHeaders } from './headers'; import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; interface HandlerConfig { @@ -185,27 +186,8 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record { - // normalize (statusMessage?, headers?) overloads const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined; - const merged: Record = {}; - const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase())); - let handlerVary: string | undefined; - - if (handlerHeaders) - for (const key of Object.keys(handlerHeaders)) { - const lowerKey = key.toLowerCase(); - - if (lowerKey === 'vary') { - handlerVary = handlerHeaders[key]; - continue; - } // merged separately below - - if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; - } - - Object.assign(merged, injected); - if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); - else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS + const merged = mergeInjectedHeaders(handlerHeaders, injected); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); }; } diff --git a/test/http-headers.test.ts b/test/http-headers.test.ts new file mode 100644 index 0000000..ac12196 --- /dev/null +++ b/test/http-headers.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { mergeInjectedHeaders } from '../src/http/headers'; + +describe('mergeInjectedHeaders', () => { + it('makes injected keys authoritative regardless of handler casing', () => { + const out = mergeInjectedHeaders( + { 'Content-Type': 'text/html', 'X-Content-Type-Options': 'sniffme' }, + { 'x-content-type-options': 'nosniff' }, + ); + expect(out['x-content-type-options']).toBe('nosniff'); + expect(Object.keys(out).filter((k) => k.toLowerCase() === 'x-content-type-options')).toHaveLength(1); + expect(out['Content-Type']).toBe('text/html'); // untouched handler header kept + }); + + it('merges Vary from handler and injected', () => { + const out = mergeInjectedHeaders({ Vary: 'Accept' }, { vary: 'Origin' }); + expect(out['vary'].toLowerCase()).toContain('accept'); + expect(out['vary'].toLowerCase()).toContain('origin'); + }); + + it('preserves handler Vary when no injected Vary', () => { + const out = mergeInjectedHeaders({ Vary: 'Accept' }, {}); + expect(out['vary']).toBe('Accept'); + }); +});