From 9a61ba86465a9fa1fe6381c500ccb1549d9d19c2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 2 Aug 2026 20:45:44 -0500 Subject: [PATCH] feat(http): complete HEAD and OPTIONS semantics Signed-off-by: Diego Resendez --- src/http/core.ts | 98 +++++++++++++++++++++++++-------- src/http/router.ts | 37 ++++++++++++- src/http/server.ts | 10 +++- src/http/web.ts | 14 ++++- test/parity.test.ts | 49 ++++++++++++++++- test/router.test.ts | 30 ++++++++-- test/transport-security.test.ts | 10 ++-- 7 files changed, 207 insertions(+), 41 deletions(-) diff --git a/src/http/core.ts b/src/http/core.ts index 0a4c4fe..7fea20e 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -3,7 +3,7 @@ import { HttpError, NotFound } from '../signals'; import { renderError } from '../transformers'; import { isStreamResult, type PipelineResult } from '../pipeline'; import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; -import { matchRoute, allowedMethods, parseQuery } from './router'; +import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router'; import { pickEncoder } from './stream'; import type { RouteDef, HttpOptions } from './types'; import type { StreamEncoder } from '../encoders'; @@ -49,6 +49,61 @@ export function computeInjected( return injected; } +function errorOutcome( + error: unknown, + req: NeutralRequest, + injected: Record, + opts: HttpOptions | undefined, + headers: Record = {}, +): HandleResult { + const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); + return { + injected, + outcome: { + kind: 'buffered', + status: rendered.status, + headers: { ...rendered.headers, ...headers }, + body: req.method === 'HEAD' ? '' : rendered.body, + }, + }; +} + +async function unmatchedOutcome( + routes: RouteDef[], + opts: HttpOptions | undefined, + req: NeutralRequest, + path: string, + injected: Record, +): Promise { + if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { + const hit = await opts.static(path); + + if (hit) { + return { + injected, + outcome: { + kind: 'buffered', + status: 200, + headers: { 'content-type': hit.contentType }, + body: req.method === 'HEAD' ? '' : hit.body, + }, + }; + } + } + + const allow = allowedMethods(routes, path); + + if (req.method === 'OPTIONS' && allow.length) { + return { + injected, + outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' }, + }; + } + + const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); + return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {}); +} + /** * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the @@ -59,35 +114,22 @@ export async function handle( opts: HttpOptions | undefined, req: NeutralRequest, ): Promise { - const path = req.url.split('?')[0]; const injected = computeInjected(opts, req); + let path: string; + + try { + path = normalizeRequestPath(req.url.split('?')[0]); + } catch { + return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts); + } if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { return { preflight: corsPreflightHeaders(opts.cors, req) }; } - const matched = matchRoute(routes, req.method, path); + const matched = resolveRoute(routes, req.method, path); - if (!matched) { - if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { - const hit = await opts.static(path); - - if (hit) { - const body = req.method === 'HEAD' ? '' : hit.body; - return { - injected, - outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body }, - }; - } - } - - // Path matches a route under a different method → 405 with Allow; otherwise 404. - const allow = allowedMethods(routes, path); - const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); - const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); - const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers; - return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } }; - } + if (!matched) return unmatchedOutcome(routes, opts, req, path, injected); let result: PipelineResult; @@ -111,5 +153,13 @@ export async function handle( return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } }; } - return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } }; + return { + injected, + outcome: { + kind: 'buffered', + status: result.status, + headers: result.headers, + body: req.method === 'HEAD' ? '' : result.body, + }, + }; } diff --git a/src/http/router.ts b/src/http/router.ts index 3884298..647e146 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -249,11 +249,44 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma return best; } +/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */ +export interface ResolvedRoute extends MatchedRoute { + implicitHead: boolean; +} + +export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined { + const explicit = matchRoute(routes, method, path); + if (explicit) return { ...explicit, implicitHead: false }; + if (method !== 'HEAD') return undefined; + + const fallback = matchRoute( + routes.filter((route) => route.transport === 'buffer'), + 'GET', + path, + ); + return fallback ? { ...fallback, implicitHead: true } : undefined; +} + +const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; + /** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ export function allowedMethods(routes: RouteDef[], path: string): string[] { const methods = new Set(); - for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method); - return [...methods]; + + for (const route of routes) { + if (!matchPattern(route.pattern, path)) continue; + methods.add(route.method); + if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD'); + } + + if (methods.size) methods.add('OPTIONS'); + return [...methods].sort((a, b) => { + const indexA = METHOD_ORDER.indexOf(a); + const indexB = METHOD_ORDER.indexOf(b); + return ( + (indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b) + ); + }); } /** Parses a URL's query string into a flat string map (last value wins for repeated keys). */ diff --git a/src/http/server.ts b/src/http/server.ts index b54f2a4..bc496f9 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -5,7 +5,7 @@ import { isHttpError, HttpError } from '../signals'; import type { Bus } from '../bus'; import { buildSecurityHeaders, resolveCors } from '../security'; import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; -import { matchRoute } from './router'; +import { normalizeRequestPath, resolveRoute } from './router'; import { readBody, deriveSecure, deriveIp } from './request'; import { pipeStream } from './stream'; import { attachWs } from './ws'; @@ -93,7 +93,13 @@ function createRequestHandler(cfg: HandlerConfig) { // Mirror handle()'s own preflight/route-match decision here, so we only read the body // (below) for a request that actually reaches a route handler — matching prior behaviour. const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']); - const matched = isPreflight ? undefined : matchRoute(routes, method, path); + let matched: ReturnType; + + try { + matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path)); + } catch { + matched = undefined; // handle() owns the standard 400 envelope and injected headers + } let body: unknown; diff --git a/src/http/web.ts b/src/http/web.ts index c0f5e97..503b99e 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -2,7 +2,7 @@ import type { StreamEncoder } from '../encoders'; import { handle, computeInjected, type HandleResult } from './core'; import { mergeInjectedHeaders } from './headers'; import { parseRequestBody } from './server'; -import { matchRoute } from './router'; +import { normalizeRequestPath, resolveRoute } from './router'; import { HttpError } from '../signals'; import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers'; import type { RouteDef, HttpOptions, MatchedRoute } from './types'; @@ -108,7 +108,8 @@ function outcomeToResponse(result: HandleResult): Response { return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers }); } - return new Response(result.outcome.body, { status: result.outcome.status, headers }); + const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body; + return new Response(body, { status: result.outcome.status, headers }); } /** @@ -123,7 +124,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { const url = new URL(request.url); const path = url.pathname + url.search; const headers = headersToRecord(request.headers); - const matched = matchRoute(routes, request.method, url.pathname); + let matched: ReturnType; + + try { + matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname)); + } catch { + matched = undefined; // handle() renders the shared 400 response without reading a body + } + const secure = url.protocol === 'https:'; // Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501, // before a route handler even runs) carry the same security/CORS headers Node's writeHead patch diff --git a/test/parity.test.ts b/test/parity.test.ts index c880a20..9d18135 100644 --- a/test/parity.test.ts +++ b/test/parity.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import type { Server } from 'http'; -import { createApp, Provider, Route, Get, Post, Module, needs, body, Sse } from '../src/index'; +import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index'; @Provider({ provides: 'db' }) class Db { @@ -22,6 +22,21 @@ class Ctl { yield { n: 2 }; })(); } + @Get('/implicit-head') implicitHead() { + return { from: 'get' }; + } + @Get('/explicit-head') explicitHeadGet() { + return { from: 'get' }; + } + @Head('/explicit-head') explicitHead() { + return { from: 'head' }; + } + @Get('/explicit-options') explicitOptionsGet() { + return { from: 'get' }; + } + @Options('/explicit-options') explicitOptions() { + return { from: 'options' }; + } } @Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] }) class M {} @@ -78,6 +93,38 @@ describe('Node vs app.fetch parity (Node is truth)', () => { expect(web.status).toBe(node.status); expect(norm(web.headers)).toEqual(norm(node.headers)); }); + it('implicit and explicit HEAD return no body in both adapters', async () => { + for (const path of ['/api/implicit-head', '/api/explicit-head']) { + const { node, web } = await both(path, { method: 'HEAD' }); + expect(node.status).toBe(200); + expect(web.status).toBe(node.status); + expect(await node.text()).toBe(''); + expect(await web.text()).toBe(''); + } + }); + it('automatic OPTIONS is 204 with the same canonical Allow header', async () => { + const { node, web } = await both('/api/x', { method: 'OPTIONS' }); + expect(node.status).toBe(204); + expect(web.status).toBe(204); + expect(node.headers.get('allow')).toBe('GET, HEAD, OPTIONS'); + expect(web.headers.get('allow')).toBe(node.headers.get('allow')); + }); + it('explicit OPTIONS route runs normally', async () => { + const { node, web } = await both('/api/explicit-options', { method: 'OPTIONS' }); + expect(node.status).toBe(200); + expect(web.status).toBe(200); + expect(await node.json()).toEqual({ from: 'options' }); + expect(await web.json()).toEqual({ from: 'options' }); + }); + it('rejects repeated slashes and malformed encoding with secure 400 responses', async () => { + for (const path of ['/api//x', '/api/%E0%A4%A']) { + const { node, web } = await both(path); + expect(node.status).toBe(400); + expect(web.status).toBe(400); + expect(node.headers.get('x-content-type-options')).toBe('nosniff'); + expect(web.headers.get('x-content-type-options')).toBe('nosniff'); + } + }); it('SSE first two events', async () => { const nodeText = await (await fetch(base + '/api/s')).text(); const webText = await (await app.fetch(new Request(base + '/api/s'))).text(); diff --git a/test/router.test.ts b/test/router.test.ts index 4af15a4..ffcf34b 100644 --- a/test/router.test.ts +++ b/test/router.test.ts @@ -1,5 +1,12 @@ import { describe, it, expect } from 'vitest'; -import { compilePattern, matchPattern, matchRoute, allowedMethods, normalizeRequestPath } from '../src/http/router'; +import { + compilePattern, + matchPattern, + matchRoute, + resolveRoute, + allowedMethods, + normalizeRequestPath, +} from '../src/http/router'; import type { RouteDef } from '../src/http/types'; const route = (method: string, pattern: string): RouteDef => ({ @@ -90,9 +97,24 @@ describe('matchRoute precedence', () => { }); describe('allowedMethods (405 support)', () => { - it('lists distinct methods whose pattern matches the path', () => { - const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')]; - expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']); + it('lists methods in canonical order with implicit HEAD and OPTIONS', () => { + const routes = [route('POST', '/a'), route('GET', '/a'), route('GET', '/b')]; + expect(allowedMethods(routes, '/a')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']); expect(allowedMethods(routes, '/nope')).toEqual([]); }); }); + +describe('resolveRoute', () => { + it('prefers explicit HEAD and otherwise falls back to buffered GET', () => { + const explicit = [route('GET', '/a'), route('HEAD', '/a')]; + expect(resolveRoute(explicit, 'HEAD', '/a')).toMatchObject({ implicitHead: false, def: { method: 'HEAD' } }); + + const fallback = resolveRoute([route('GET', '/a')], 'HEAD', '/a'); + expect(fallback).toMatchObject({ implicitHead: true, def: { method: 'GET' } }); + }); + + it('does not use a streaming GET as implicit HEAD', () => { + const streaming = { ...route('GET', '/a'), transport: 'sse' as const }; + expect(resolveRoute([streaming], 'HEAD', '/a')).toBeUndefined(); + }); +}); diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 3228f5a..7eecc02 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -187,7 +187,7 @@ describe('CORS', () => { expect(r.headers.get('access-control-allow-credentials')).toBe('true'); }); - it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → 405 Allow for an existing path', async () => { + it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → automatic 204 Allow', async () => { @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } @Module({ mountpoint: '/', controllers: [C] }) class CMod {} app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); @@ -195,11 +195,11 @@ describe('CORS', () => { const port = (server.address() as any).port; const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } }); expect(r.headers.get('access-control-allow-origin')).toBeNull(); - // A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the path exists - // under GET, so the router answers 405 with an Allow header rather than 404. + // A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the router + // answers it automatically and advertises the explicit + implicit methods. const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); - expect(bare.status).toBe(405); - expect(bare.headers.get('allow')).toContain('GET'); + expect(bare.status).toBe(204); + expect(bare.headers.get('allow')).toBe('GET, HEAD, OPTIONS'); }); it("merges a handler's Title-Case Vary with CORS's Origin", async () => {