From 9050a7e5d920ff888279d8a6dcffee0f92947303 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:25:24 -0500 Subject: [PATCH] feat: WS connections rejected by an HttpError close with 4000+status Signed-off-by: Diego Resendez --- src/http.ts | 9 +++++++-- test/ws.test.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/http.ts b/src/http.ts index f08a63e..840a9be 100644 --- a/src/http.ts +++ b/src/http.ts @@ -2,7 +2,7 @@ import http from 'http'; import { once } from 'events'; import { channel } from './channel'; import { errorToResponse } from './transformers'; -import { HttpError } from './signals'; +import { HttpError, isHttpError } from './signals'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; import type { Transport } from './metadata'; @@ -167,7 +167,12 @@ function attachWs( try { ws.close(); } catch { /* already closed */ } } catch (err) { bus?.emit('stream:error', { name, error: err }); - try { ws.close(1011); } catch { /* already closed */ } + if (isHttpError(err)) { + const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + try { ws.close(4000 + err.status, reason); } catch { /* already closed */ } + } else { + try { ws.close(1011); } catch { /* already closed */ } + } } finally { ac.abort(); bus?.emit('stream:close', { name }); diff --git a/test/ws.test.ts b/test/ws.test.ts index 571e9c3..ec58541 100644 --- a/test/ws.test.ts +++ b/test/ws.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'; import WebSocket from 'ws'; import { channel } from '../src/channel'; import { createHttpServer, type WsRouteDef } from '../src/http'; +import { Unauthorized } from '../src/signals'; const url = (server: import('http').Server, path: string) => { const a = server.address(); @@ -34,4 +35,19 @@ describe('ws upgrade', () => { expect(aborted).toBe(true); server.close(); }); + + it('closes with a 4000+status code when the WS open() throws an HttpError', async () => { + const wsRoutes = [{ pattern: '/secure', open: async () => { throw new Unauthorized('no token'); } }]; + const server = createHttpServer([], wsRoutes as any); + await new Promise((r) => server.listen(0, r)); + const port = (server.address() as any).port; + const WebSocket = (await import('ws')).default; + const client = new WebSocket(`ws://127.0.0.1:${port}/secure`); + const { code, reason } = await new Promise<{ code: number; reason: string }>((res) => { + client.on('close', (code: number, reason: Buffer) => res({ code, reason: reason.toString() })); + }); + expect(code).toBe(4401); + expect(reason).toContain('no token'); + server.close(); + }); });