websockets / ws

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
MIT License
21.34k stars 2.3k forks source link

Catching message exceeding maxPayload without automatically closing the connection #2224

Closed tomtomau closed 2 months ago

tomtomau commented 2 months ago

Is there an existing issue for this?

Description

Hey there, I've searched high and low in the docs/issues and haven't quite found an answer to my issues.

Ideally, I'm wanting to handle the receiving a maxPayload message such that I can keep the connection to the client open and send it a message to tell it the message was too large.

I've tried adding on('error') listeners, and I can successfully "catch" the Error on the server side, but it seems like the library automatically closes the connection when this occurs? Is this the intended behaviour or am I likely not holding it correctly?

ws version

8.16.0

Node.js Version

v18

System

  System:
    OS: macOS 14.4.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 64.38 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh

Expected result

Don't close the connection when the error occurs

Actual result

It closes the connection when the error occurs

Attachments

No response

lpinca commented 2 months ago

I've tried adding on('error') listeners, and I can successfully "catch" the Error on the server side, but it seems like the library automatically closes the connection when this occurs? Is this the intended behaviour or am I likely not holding it correctly?

Yes, it is. The connection is closed with the 1009 status code when this happens. See https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1.

tomtomau commented 2 months ago

Ok, thanks for clarify that I'm at least not holding it incorrectly!

I'm not familiar with the rest of the specs, do they prescribe that a server must close the connection with 1009? Or just that if the server closes the connection due to exceeding the maximum payload size then it should use the 1009 code, and the only valid condition for returning 1009 code is due to exceeding the maximum payload size (i.e. don't use it for other reasons)

It seems unnecessary to have the server close the connection when it receives a message that is too large, when being able to handle it internally on the server as an "error" (in my case, sending back a message to the client to tell them it was too large) but continue to keep the connection open for more messages, but I'm not sure if that's just a fundamental misunderstanding of mine of the websocket protocol

lpinca commented 2 months ago

I think it is not mandatory but the behavior is common in the WebSocket implementations.

  1. It is a measure against a possibile DoS attack.
  2. If the connection is not closed, how do you handle these messages? Discarding them?
  3. The size is configurable.
  4. The endpoint is still informed of the problem via the close code.
lpinca commented 2 months ago

I'm closing this as answered.