Skip to content

Commit 0808a72

Browse files
authored
websocket: fix close when no closing code is received (#2680)
1 parent 8220e7d commit 0808a72

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

lib/websocket/receiver.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,11 @@ class ByteParser extends Writable {
107107
// Close frame, the endpoint MUST send a Close frame in response. (When
108108
// sending a Close frame in response, the endpoint typically echos the
109109
// status code it received.)
110-
const body = Buffer.allocUnsafe(2)
111-
body.writeUInt16BE(this.#info.closeInfo.code, 0)
110+
let body = emptyBuffer
111+
if (this.#info.closeInfo.code) {
112+
body = Buffer.allocUnsafe(2)
113+
body.writeUInt16BE(this.#info.closeInfo.code, 0)
114+
}
112115
const closeFrame = new WebsocketFrameSend(body)
113116

114117
this.ws[kResponse].socket.write(

test/websocket/issue-2679.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict'
2+
3+
const { test } = require('node:test')
4+
const assert = require('node:assert')
5+
const { once } = require('node:events')
6+
const { WebSocketServer } = require('ws')
7+
const { WebSocket } = require('../..')
8+
9+
test('Close without receiving code does not send an invalid payload', async () => {
10+
const server = new WebSocketServer({ port: 0 })
11+
12+
await once(server, 'listening')
13+
14+
server.on('connection', (sock, request) => {
15+
setTimeout(() => {
16+
sock.close()
17+
}, 3000)
18+
})
19+
20+
server.on('error', (err) => assert.ifError(err))
21+
22+
const client = new WebSocket(`ws://127.0.0.1:${server.address().port}`)
23+
await once(client, 'open')
24+
25+
await once(client, 'close')
26+
27+
server.close()
28+
await once(server, 'close')
29+
})

0 commit comments

Comments
 (0)