Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

websocket: fix close when no closing code is received #2680

Merged
merged 1 commit into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')
})
Loading