feat: WS connections rejected by an HttpError close with 4000+status
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+23
-2
No files matched your search
+7
-2
@@ -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 });
|
||||
|
||||
@@ -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<void>((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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user