From 59763c9af54d015cbda93259539993c4db2067cf Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 9 Oct 2026 13:30:05 -0500 Subject: [PATCH] fix(ws): reject malformed upgrades instead of crashing the server The Node 'upgrade' listener matched the raw request path without the normalization HTTP runs. A bad percent escape in a param segment threw URIError synchronously inside the listener, an uncaught exception that ends the process, and '//' silently matched a route HTTP refuses. Upgrades now normalize the path first: malformed escapes and repeated slashes get a 400, an unknown route a written 404 instead of a bare destroy, and any other throw in the listener a 500. app.upgrade (Deno/Bun/edge) closes 1008 'invalid request path' rather than 1011. On Deno the adapter's socket is still CONNECTING when an early 1008 is sent, and that close was a no-op that left the peer hanging; eventSocket now defers such a close to 'open'. Closes #104 Signed-off-by: Diego Resendez --- CHANGELOG.md | 10 +++ src/app/index.ts | 14 +++- src/http/ws-adapter.ts | 14 +++- src/http/ws.ts | 73 +++++++++++++++------ test/app-upgrade.test.ts | 25 +++++++- test/bun/ws.test.ts | 26 ++++++++ test/deno/ws.test.ts | 36 +++++++++++ test/edge/run.ts | 13 ++++ test/edge/worker.ts | 7 ++ test/ws-upgrade-reject.test.ts | 114 +++++++++++++++++++++++++++++++++ 10 files changed, 309 insertions(+), 23 deletions(-) create mode 100644 test/ws-upgrade-reject.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fbba8b..866836d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,16 @@ npm treats versions as semver and semver forbids leading zeros. emitted for these requests. Deno, Bun and the edge were not affected: they receive `app.fetch`'s promise, and the runtime answers a rejection with a 500 itself. +- **A malformed WebSocket upgrade no longer takes a Node server down** (#104). The upgrade path never + ran the request-path normalization HTTP runs, so a bad percent escape in a param segment + (`/room/%E0%A4%A`) threw out of the `'upgrade'` listener as an uncaught exception, and one request + was enough to end the process. Upgrades now go through the same normalization: a malformed escape + or a repeated slash gets a `400`, an unknown route a written `404` instead of a silent disconnect, + and anything else that throws in the listener a `500`. `//rt//echo` used to match `/rt/echo` on + upgrade while HTTP refused it; both refuse it now. On Deno, Bun and the edge the same paths close + with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before + the socket finished opening now reaches the client instead of leaving it hanging. + ## [26.9.0-beta.2] - 2026-09-22 ### Breaking diff --git a/src/app/index.ts b/src/app/index.ts index 1a0107b..8241506 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -39,7 +39,7 @@ import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import { inspectRoute, buildGraphView, explainRoute } from './introspect'; -import { compilePattern } from '../http/router'; +import { compilePattern, normalizeRequestPath } from '../http/router'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types'; @@ -1290,7 +1290,17 @@ function buildAppUpgrade( await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted - const path = request.url.split('?')[0]; + let path: string; + + // The same normalization HTTP and the Node upgrade listener run. A malformed escape would + // otherwise reject out of the matcher and close with 1011, a server-error code for a client error. + try { + path = normalizeRequestPath(request.url.split('?')[0]); + } catch { + ready.close(1008, 'invalid request path'); + return; + } + const meshControl = getMeshControl(); // The reserved mesh path, checked before route matching: this is what lets a teapot export diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index 1c0d8d8..2400c60 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require'; */ const decoder = new TextDecoder(); +const CONNECTING = 0; // WebSocket.CONNECTING const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient /** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */ @@ -69,7 +70,18 @@ export function eventSocket(host: EventfulSocket): WsSocket { ac.abort(); }); - return neutralSocket(host, inbound, ac); + const socket = neutralSocket(host, inbound, ac); + const closeNow = socket.close; + + // Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in + // that state is a no-op, so a route that refuses straight away (1008) left the peer hanging. + // Deferring to 'open' is what lets that close reach the client at all. + return Object.assign(socket, { + close: (code?: number, reason?: string) => { + if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason)); + else closeNow(code, reason); + }, + }); } /** diff --git a/src/http/ws.ts b/src/http/ws.ts index b22d684..21a4dc8 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -3,6 +3,7 @@ import { channel } from '../channel'; import type { Bus } from '../bus'; import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import type { WsRouteDef, MeshControl } from './types'; +import { normalizeRequestPath } from './router'; import { nodeRequire } from '../node-require'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ @@ -16,9 +17,9 @@ function loadWss(): any | null { } } -/** Writes a 501 Not Implemented status to the raw socket and destroys it. */ -function reject501(socket: any): void { - socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); +/** Writes a bodyless HTTP status to the raw socket and destroys it. */ +function rejectUpgrade(socket: any, status: number, text: string): void { + socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); socket.destroy(); } @@ -35,7 +36,7 @@ function handleMeshUpgrade( if (path !== meshControl.path) return false; if (!wss) { - reject501(socket); + rejectUpgrade(socket, 501, 'Not Implemented'); return true; } @@ -102,24 +103,58 @@ export function attachWs( const WebSocketServer = loadWss(); const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null; server.on('upgrade', (req, socket, head) => { - const path = (req.url ?? '/').split('?')[0]; + // A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody + // else is listening to yet: that is as fatal as a throw. + socket.on('error', () => {}); - if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return; - - const route = matchWsRoute(wsRoutes, path); - - if (!route) { - socket.destroy(); - return; + // Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an + // uncaught exception that takes the whole process down, not a 500 for one client. + try { + routeUpgrade(wss, wsRoutes, req, socket, head, bus, meshControl, streams); + } catch { + if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error'); + else socket.destroy(); } + }); +} - if (!wss) { - reject501(socket); - return; - } +/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */ +function routeUpgrade( + wss: any, + wsRoutes: WsRouteDef[], + req: http.IncomingMessage, + socket: any, + head: Buffer, + bus?: Bus, + meshControl?: MeshControl, + streams?: Set<() => void>, +): void { + let path: string; - wss.handleUpgrade(req, socket, head, (ws: any) => { - void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); - }); + // The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed + // escape reaches `decodeURIComponent` in the matcher and throws, and `//` silently matches. + try { + path = normalizeRequestPath((req.url ?? '/').split('?')[0]); + } catch { + rejectUpgrade(socket, 400, 'Bad Request'); + return; + } + + if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return; + + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + rejectUpgrade(socket, 404, 'Not Found'); + return; + } + + if (!wss) { + rejectUpgrade(socket, 501, 'Not Implemented'); + return; + } + + wss.handleUpgrade(req, socket, head, (ws: any) => { + void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); }); } diff --git a/test/app-upgrade.test.ts b/test/app-upgrade.test.ts index 5bbd157..05a8eae 100644 --- a/test/app-upgrade.test.ts +++ b/test/app-upgrade.test.ts @@ -12,7 +12,16 @@ class Rt { })(); } } -@Module({ mountpoint: '/', controllers: [Rt] }) +@Route('/room') +class Room { + @Ws('/:name') + join(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `room:${msg}`; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Rt, Room] }) class M {} const app = createApp({ modules: [M] }); @@ -96,4 +105,18 @@ describe('app.upgrade', () => { await app.upgrade(req, socket); expect(closedCode).toBe(1008); }); + + it.each(['/rt/%E0%A4%A', '/room/%E0%A4%A', '//rt//echo'])( + 'closes 1008 on the malformed path %s instead of rejecting (#104)', + async (url) => { + const { socket } = fakeSocket(); + let closed: [number | undefined, string | undefined] | undefined; + socket.close = (c, r) => { + closed = [c, r]; + }; + const req: WsRequest = { url, headers: {}, protocol: 'http', ip: '' }; + await app.upgrade(req, socket); + expect(closed).toEqual([1008, 'invalid request path']); + }, + ); }); diff --git a/test/bun/ws.test.ts b/test/bun/ws.test.ts index 336fa7f..4b2ce97 100644 --- a/test/bun/ws.test.ts +++ b/test/bun/ws.test.ts @@ -20,6 +20,13 @@ class Rt { for await (const msg of inbound) yield `echo:${msg}`; })(); } + + @Ws('/room/:name') + room(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `room:${msg}`; + })(); + } } @Module({ mountpoint: '/', controllers: [Rt] }) class M {} @@ -47,3 +54,22 @@ test('serveBun: HTTP + WebSocket round-trip', async () => { server.stop(true); } }); + +// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011. +test('serveBun: a malformed upgrade path closes 1008 and the server keeps serving', async () => { + const app = createApp({ modules: [M] }); + const server = await serveBun(app, { port: 0 }); + const port = server.port; + try { + const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`); + const closed = await new Promise<{ code: number; reason: string }>((resolve) => { + ws.onclose = (e) => resolve({ code: e.code, reason: e.reason }); + }); + expect(closed).toEqual({ code: 1008, reason: 'invalid request path' }); + + const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`); + expect(httpRes.status).toBe(200); + } finally { + server.stop(true); + } +}); diff --git a/test/deno/ws.test.ts b/test/deno/ws.test.ts index 059d6d4..e0710f7 100644 --- a/test/deno/ws.test.ts +++ b/test/deno/ws.test.ts @@ -28,6 +28,13 @@ class Rt { for await (const msg of inbound) yield `echo:${msg}`; })(); } + + @Ws('/room/:name') + room(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `room:${msg}`; + })(); + } } @Module({ mountpoint: '/', controllers: [Rt] }) @@ -69,3 +76,32 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () = await server.shutdown(); } }); + +// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011. +Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps serving', async () => { + const app = createApp({ modules: [M] }); + + let port = 0; + const server = await serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + try { + const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`); + const closed = await new Promise<{ code: number; reason: string }>((resolve) => { + ws.onclose = (e) => resolve({ code: e.code, reason: e.reason }); + }); + assertEquals(closed, { code: 1008, reason: 'invalid request path' }); + + const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`); + assertEquals(httpRes.status, 200); + await httpRes.body?.cancel(); + } finally { + await server.shutdown(); + } +}); diff --git a/test/edge/run.ts b/test/edge/run.ts index 58dc066..7e72f3f 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -84,6 +84,19 @@ async function main() { }); assert.equal(got, 'echo:hi'); + // #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves. + const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', { + headers: { Upgrade: 'websocket' }, + }); + const bad = badRes.webSocket; + assert.ok(bad, 'expected a client webSocket on the 101 response'); + const closed = new Promise<{ code: number; reason: string }>((resolve) => + bad.addEventListener('close', (e: { code: number; reason: string }) => resolve({ code: e.code, reason: e.reason })), + ); + bad.accept(); + assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' }); + assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200); + console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS'); } finally { await mf.dispose(); diff --git a/test/edge/worker.ts b/test/edge/worker.ts index 33753b1..268bde2 100644 --- a/test/edge/worker.ts +++ b/test/edge/worker.ts @@ -17,6 +17,13 @@ class Rt { for await (const msg of inbound) yield `echo:${msg}`; })(); } + + @Ws('/room/:name') + room(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `room:${msg}`; + })(); + } } @Module({ mountpoint: '/', controllers: [Rt] }) diff --git a/test/ws-upgrade-reject.test.ts b/test/ws-upgrade-reject.test.ts new file mode 100644 index 0000000..385a2a5 --- /dev/null +++ b/test/ws-upgrade-reject.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'; +import net from 'net'; +import type http from 'http'; +import WebSocket from 'ws'; +import { createApp, Route, Get, Ws, Module, ctx } from '../src/index'; + +// Regression for #104: these drive the real Node `'upgrade'` listener through a `listen(0)` server, +// not `app.upgrade`. The requests are written by hand over a raw socket because a WebSocket client +// refuses or re-encodes the malformed URLs this is about. + +@Route('/rt') +class Rt { + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${msg}`; + })(); + } + + // A param route is what makes the bad escape fatal: only param segments are decoded on match. + @Ws('/room/:name') + room(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `room:${msg}`; + })(); + } +} +@Route('/health') +class Health { + @Get('/') + ok() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Rt, Health] }) +class M {} + +/** Writes a raw upgrade request for `path` and resolves with everything the server sent before closing. */ +function rawUpgrade(port: number, path: string): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1'); + let data = ''; + socket.on('connect', () => + socket.write( + `GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n', + ), + ); + socket.on('data', (chunk) => (data += chunk.toString())); + socket.on('close', () => resolve(data)); + socket.on('error', reject); + }); +} + +describe('Node upgrade listener rejects malformed upgrades (#104)', () => { + let server: http.Server; + let port: number; + const uncaught: unknown[] = []; + const onUncaught = (err: unknown) => uncaught.push(err); + + beforeAll(async () => { + process.on('uncaughtException', onUncaught); + process.on('unhandledRejection', onUncaught); + const app = createApp({ modules: [M] }); + server = await app.listen(0); + port = (server.address() as { port: number }).port; + }); + + afterAll(async () => { + process.off('uncaughtException', onUncaught); + process.off('unhandledRejection', onUncaught); + await new Promise((r) => server.close(r)); + }); + + afterEach(async () => { + // T6: a normal request on a new connection succeeds after every rejected upgrade. + const res = await fetch(`http://127.0.0.1:${port}/health`); + expect(res.status).toBe(200); + expect(uncaught).toEqual([]); + }); + + it('T1: malformed percent-encoding gets a 400 and the socket closes', async () => { + expect(await rawUpgrade(port, '/rt/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /); + }); + + it('T1: malformed percent-encoding in a param segment gets a 400 instead of crashing', async () => { + expect(await rawUpgrade(port, '/rt/room/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /); + }); + + it('T2: invalid hex in a percent escape gets a 400', async () => { + expect(await rawUpgrade(port, '/rt/room/%ZZ')).toMatch(/^HTTP\/1\.1 400 /); + }); + + it('T3: a repeated slash gets a 400 instead of matching /rt/echo', async () => { + expect(await rawUpgrade(port, '//rt//echo')).toMatch(/^HTTP\/1\.1 400 /); + }); + + it('T4: a long path below the header limit takes the normal miss path (404)', async () => { + expect(await rawUpgrade(port, `/rt/${'a'.repeat(8 * 1024)}`)).toMatch(/^HTTP\/1\.1 404 /); + }); + + it('T5: an unknown ws route gets a written 404, then close', async () => { + expect(await rawUpgrade(port, '/nope')).toMatch(/^HTTP\/1\.1 404 /); + }); + + it('T7: a valid upgrade still echoes', async () => { + const client = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`); + await new Promise((r) => client.on('open', r)); + const got = new Promise((r) => client.on('message', (d) => r(d.toString()))); + client.send('hi'); + expect(await got).toBe('echo:hi'); + client.close(); + }); +});