Skip to content

Commit

Permalink
websocket: fix close when no closing code is received (#2680)
Browse files Browse the repository at this point in the history
  • Loading branch information
KhafraDev committed Feb 1, 2024
1 parent 8220e7d commit 0808a72
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/websocket/receiver.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,11 @@ class ByteParser extends Writable {
// Close frame, the endpoint MUST send a Close frame in response. (When
// sending a Close frame in response, the endpoint typically echos the
// status code it received.)
const body = Buffer.allocUnsafe(2)
body.writeUInt16BE(this.#info.closeInfo.code, 0)
let body = emptyBuffer
if (this.#info.closeInfo.code) {
body = Buffer.allocUnsafe(2)
body.writeUInt16BE(this.#info.closeInfo.code, 0)
}
const closeFrame = new WebsocketFrameSend(body)

this.ws[kResponse].socket.write(
Expand Down
29 changes: 29 additions & 0 deletions test/websocket/issue-2679.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict'

const { test } = require('node:test')
const assert = require('node:assert')
const { once } = require('node:events')
const { WebSocketServer } = require('ws')
const { WebSocket } = require('../..')

test('Close without receiving code does not send an invalid payload', async () => {
const server = new WebSocketServer({ port: 0 })

await once(server, 'listening')

server.on('connection', (sock, request) => {
setTimeout(() => {
sock.close()
}, 3000)
})

server.on('error', (err) => assert.ifError(err))

const client = new WebSocket(`ws://127.0.0.1:${server.address().port}`)
await once(client, 'open')

await once(client, 'close')

server.close()
await once(server, 'close')
})

0 comments on commit 0808a72

Please sign in to comment.