Commit Graph

251 Commits

Author SHA1 Message Date
Damien Arrachequesne
362bc78191 fix: properly call the send callback during upgrade
The "drain" event (added in [1]) had two different meanings:

- the transport is ready to be written
- the packets are sent over the wire

For the WebSocket and the WebTransport transports, those two events
happen at the same time, but this is not the case for the HTTP
long-polling transport:

- the transport is ready to be written when the client sends a GET request
- the packets are sent over the wire when the server responds to the GET request

Which caused an issue with send callbacks during an upgrade, since the
packets were written but the client would not open a new GET request.

There are now two distinct events: "ready" and "drain"

Related: https://github.com/socketio/engine.io/issues/695

[1]: 2a93f06e27
2024-06-21 11:47:41 +02:00
Damien Arrachequesne
9a68c8ce93 perf(websocket): use bound callbacks
Instead of allocating one temporary function for each WebSocket
`send()` call.

Regarding the test removal, the permessage-deflate threshold was
implemented in the "ws" package in [1], so it's not needed anymore.

[1]: 6b3904b42d
2024-06-17 17:47:46 +02:00
Damien Arrachequesne
ef1c4c8bb7 refactor: remove the wsPreEncoded option
The wsPreEncoded option was added in the `socket.io-adapter` package
when broadcasting a message to multiple clients.

It was removed in [1] and is now superseded by the `wsPreEncodedFrame`
option, which directly computes the WebSocket frame once for all
clients (see [2]).

[1]: 88eee5948a
[2]: 5f7b47d40f
2024-06-13 23:55:16 +02:00
Jonathan Perret
fc21c4a05f fix: fix websocket and webtransport send callbacks (#699)
With the `websocket` transport, the callbacks which indicate that the
packets are actually written were not properly called.

Example:

```js
socket.send("hello", () => {
  // the message has been written to the underlying transport
});
```

The bug was caused by the `websocket` transport (and `webtransport` as
well) having its `supportsFraming` property set to `true`, despite
having been changed in [1] to emit a single `drain` event for each
batch of messages written to the transport like the `polling` transport
always did. Note that although [1] is partially reverted in [2], the
new `drain` event behavior is preserved as called out in that commit's
message.

The `supportsFraming` attribute was introduced in [3] (amended by [4])
as a way to distinguish transports that emit one `drain` per message
from those that emit one `drain` per batch. Since the delivery of
`send` callbacks depends on matching `drain` events with
`transport.send` calls, that distinction is vital to correct behavior.

However, now that all transports have converged to "one `drain` per
batch" behavior, this `supportsFraming` property can be retired (and
the code for calling callbacks simplified).

[1]: https://github.com/socketio/engine.io/pull/618
[2]: a65a047526
[3]: https://github.com/socketio/engine.io/pull/130
[4]: https://github.com/socketio/engine.io/pull/132

Related: https://github.com/socketio/engine.io/issues/698
2024-06-13 23:02:22 +02:00
Damien Arrachequesne
9545b44b3c refactor: add cache-control header in the polling response
This header should not be needed since the client already includes a
cache busting query parameter ("t"), but a misconfigured CDN could
ignore the query parameters and cache the server response.

Related: https://github.com/socketio/socket.io/issues/4842
2023-10-05 17:19:08 +02:00
Damien Arrachequesne
a306db09e8 fix(webtransport): add proper framing
WebTransport being a stream-based protocol, the chunking boundaries are
not necessarily preserved. That's why we need a header indicating the
type of the payload (plain text or binary) and its length.

We will use a format inspired by the WebSocket frame:

- first bit indicates whether the payload is binary
- the next 7 bits are either:
  - 125 or less: that's the length of the payload
  - 126: the next 2 bytes represent the length of the payload
  - 127: the next 8 bytes represent the length of the payload

Reference: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length

Related:

- https://github.com/socketio/engine.io/issues/687
- https://github.com/socketio/engine.io/issues/688
2023-08-02 01:00:42 +02:00
Damien Arrachequesne
123b68c04f feat: add support for WebTransport
Reference: https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
2023-06-11 09:42:45 +02:00
Damien Arrachequesne
fc480b4f30 fix: prevent crash when provided with an invalid query param
A specially crafted request could lead to the following exception:

> TypeError: Cannot read properties of undefined (reading 'handlesUpgrades')
>    at Server.onWebSocket (build/server.js:515:67)

This bug was introduced in [1], released in version 5.1.0 and included
in version 4.1.0 of the `socket.io` parent package. Older versions are
not impacted.

[1]: 7096e98a02
2023-05-02 01:07:40 +02:00
Damien Arrachequesne
8b22162903 fix(uws): prevent crash when using with middlewares
The class used to accumulate the response headers did not expose the
exact same API as its wrapped type, which could lead to the following
error in some rare cases:

> TypeError: Cannot read properties of undefined (reading 'end')
>    at Polling.onDataRequest (build/transports-uws/polling.js:109:53)
>    at Polling.onRequest (build/transports-uws/polling.js:47:18)
>    at callback (build/userver.js:94:56)
>    at uServer.verify (build/server.js:152:9)

Related: https://github.com/socketio/socket.io/issues/4643
2023-05-02 00:50:34 +02:00
Ciel
93957828be fix: include error handling for Express middlewares (#674)
Following 24786e77c5.

Reference: https://expressjs.com/en/guide/error-handling.html
2023-05-02 00:00:47 +02:00
Damien Arrachequesne
7033c0ed27 chore(release): 6.4.1
Diff: https://github.com/socketio/engine.io/compare/6.4.0...6.4.1
2023-02-20 00:54:54 +01:00
Damien Arrachequesne
898bd1c9df chore(release): 6.4.0
Diff: https://github.com/socketio/engine.io/compare/6.3.1...6.4.0
2023-02-06 17:16:32 +01:00
Damien Arrachequesne
24786e77c5 feat: add support for Express middlewares
This commit implements middlewares at the Engine.IO level, because
Socket.IO middlewares are meant for namespace authorization and are not
executed during a classic HTTP request/response cycle.

A workaround was possible by using the allowRequest option and the
"headers" event, but this feels way cleaner and works with upgrade
requests too.

Syntax:

```js
engine.use((req, res, next) => {
  // do something

  next();
});

// with express-session
import session from "express-session";

engine.use(session({
  secret: "keyboard cat",
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
});

// with helmet
import helmet from "helmet";

engine.use(helmet());
```

Related:

- https://github.com/socketio/engine.io/issues/668
- https://github.com/socketio/engine.io/issues/651
- https://github.com/socketio/socket.io/issues/4609
- https://github.com/socketio/socket.io/issues/3933
- a lot of other issues asking for compatibility with express-session
2023-02-06 17:01:27 +01:00
Damien Arrachequesne
4d6f4541c3 chore(release): 6.3.1
Diff: https://github.com/socketio/engine.io/compare/6.3.0...6.3.1
2023-01-12 08:23:07 +01:00
Damien Arrachequesne
ae1ea77991 chore(release): 6.3.0
Diff: https://github.com/socketio/engine.io/compare/6.2.1...6.3.0
2023-01-10 17:28:24 +01:00
Damien Arrachequesne
a65a047526 fix: wait for all packets to be sent before closing the WebSocket connection
This reverts commit [1], which was included in `engine.io@5.1.0` and
`socket.io@4.1.0`.

The WebSocket connection was closed before all packets were written
out, so for example when calling `socket.disconnect(true)` on the
Socket.IO server (which disconnect from all namespaces and close the
connection), the client would receive only the first disconnect packet
and kept trying to reconnect to the other namespaces.

The only difference with the previous implementation (pre 5.1.0) is
that the "drain" event gets only called once at the end, and not after
each packet.

[1]: ad5306aeae

Related: https://github.com/socketio/engine.io/issues/648
2023-01-10 16:42:12 +01:00
Damien Arrachequesne
bc98bf1232 refactor: bump prettier to version 2.8.1
This major bump creates a lot of noise, but it is necessary for
prettier to be able to parse new syntax such as:

- typed imports: `import { type xxx } from ...`
- private attributes: `class A { #b; #c() {} }`
2023-01-10 15:22:57 +01:00
iifawzi
d0fd4746af feat: add the "addTrailingSlash" option (#655)
The "addTrailingSlash" option allows to control whether a trailing
slash is added to the path of the HTTP requests:

- true (default): "/engine.io/"
- false: "/engine.io"

Related: 21a6e1219a

Signed-off-by: iifawzi <iifawzie@gmail.com>
2023-01-10 14:51:31 +01:00
Damien Arrachequesne
5e34722b0b perf: add the wsPreEncodedFrame option
This optimization is only applied if:

- the permessage-deflate extension is disabled (which is the default)
- the "ws" package is used (which is the default)

In that case, the WebSocket frame will only be computed once, when
broadcasting to multiple clients.

Related: 5f7b47d40f
2023-01-09 10:34:25 +01:00
Damien Arrachequesne
535a01d889 ci: add Node.js 18 in the test matrix
A few notes:

- the certificates were recreated because Node.js 18 includes OpenSSL
v3, which has deprecated support for some legacy ciphers (like RC2)

- eiows currently fails to build on Node.js 18, so the tests are
temporarily skipped

See also: https://github.com/nodejs/Release
2022-11-20 00:20:30 +01:00
Lam Wei Li
917d1d29e1 refactor: replace deprecated String.prototype.substr() (#646)
`.substr()` is deprecated so we replace it with `.slice()` which works
similarily but isn't deprecated.

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

Signed-off-by: Lam Wei Li <peteriman@mail.com>
2022-06-06 08:42:45 +02:00
Damien Arrachequesne
088dcb4dff feat: add the "maxPayload" field in the handshake details
So that clients in HTTP long-polling can decide how many packets they
have to send to stay under the maxHttpBufferSize value.

This is a backward compatible change which should not mandate a new
major revision of the protocol (we stay in v4), as we only add a field
in the JSON-encoded handshake data:

```
0{"sid":"lv_VI97HAXpY6yYWAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000,"maxPayload":1000000}
```

Related: https://github.com/socketio/socket.io-client/issues/1531
2022-03-10 14:20:54 +01:00
e3dio
3367440308 fix(uws): properly handle chunked content (#642)
With the engine based on µWebSockets.js (introduced in version 6.1.0),
a huge request body split in multiple chunks would throw the following
error:

> node:buffer:254
>   TypedArrayPrototypeSet(target, source, targetStart);
>   ^
>
> TypeError: Cannot perform %TypedArray%.prototype.set on a detached ArrayBuffer
>     at Buffer.set (<anonymous>)
>     at _copyActual (node:buffer:254:3)
> node:buffer:254
>   TypedArrayPrototypeSet(target, source, targetStart);
>   ^
>
> TypeError: Cannot perform %TypedArray%.prototype.set on a detached ArrayBuffer
>     at Buffer.set (<anonymous>)
>     at _copyActual (node:buffer:254:3)
>     at Function.concat (node:buffer:562:12)
>     at onEnd (.../node_modules/engine.io/build/transports-uws/polling.js:126:32)
>     at .../node_modules/engine.io/build/transports-uws/polling.js:143:17

Note: µWebSockets.js does not currently support chunked transfer
encoding.
2022-02-23 07:16:25 +01:00
Damien Arrachequesne
45112a30d1 fix(uws): fix HTTP long-polling with CORS
When binding to an uWebSockets.js application, the server could crash
with the following error:

```
TypeError: res.onData is not a function
    at Polling.onDataRequest (build/transports-uws/polling.js:133:13)
    at Polling.onRequest (build/transports-uws/polling.js:47:18)
    at callback (build/userver.js:80:56)
```

Related: https://github.com/socketio/engine.io/issues/637
2022-01-18 17:49:28 +01:00
Damien Arrachequesne
8b4d6a8176 fix(uws): handle invalid websocket upgrades
When binding to an uWebSockets.js App, there was an unhandled case that
could crash the server:

```
curl "http://localhost:3000/engine.io/?EIO=4&transport=websocket"
```

would result in:

```
Error: Returning from a request handler without responding or attaching an abort handler is forbidden!
terminate called without an active exception
```

Note: this does not apply to the default server based on ws, because
the error was caught elsewhere in the source code.

Related: https://github.com/socketio/socket.io/issues/4250
2022-01-14 08:18:03 +01:00
Damien Arrachequesne
f3b761dc56 chore(release): 6.1.1
Diff: https://github.com/socketio/engine.io/compare/6.1.0...6.1.1
2022-01-11 16:08:20 +01:00
Damien Arrachequesne
c0e194d449 fix: properly handle invalid data sent by a malicious websocket client
**IMPORTANT SECURITY FIX**

A malicious client could send a specially crafted HTTP request,
triggering an uncaught exception and killing the Node.js process:

> RangeError: Invalid WebSocket frame: RSV2 and RSV3 must be clear
>   at Receiver.getInfo (/.../node_modules/ws/lib/receiver.js:176:14)
>   at Receiver.startLoop (/.../node_modules/ws/lib/receiver.js:136:22)
>   at Receiver._write (/.../node_modules/ws/lib/receiver.js:83:10)
>   at writeOrBuffer (internal/streams/writable.js:358:12)

This bug was introduced by [1], included in `engine.io@4.0.0`, so
previous releases are not impacted.

[1]: f3c291fa61

Thanks to Marcus Wejderot from Mevisio for the responsible disclosure.
2022-01-11 15:52:15 +01:00
Damien Arrachequesne
4c306af945 chore(release): 6.1.0
Diff: https://github.com/socketio/engine.io/compare/6.0.0...6.1.0
2021-11-08 08:37:22 +01:00
Damien Arrachequesne
35b6b505df test: replace "s" package by string interpolation 2021-11-08 08:17:25 +01:00
Damien Arrachequesne
ed50fc346b fix: fix payload encoding for v3 clients
The v3 parser (used for compatibility with older clients) was broken
during the migration to TypeScript ([1]).

This was not caught in the test suite because the Node.js client does
not support binary packet in polling mode (packets are base64-encoded).

[1]: c0d6eaa1ba

Backported from 6.0.x branch: 3f42262fd2
2021-11-06 08:03:57 +01:00
Damien Arrachequesne
271e2df94d feat: add an implementation based on uWebSockets.js
```js
const { App } = require("uWebSockets.js");
const { uServer } = require("engine.io");

const app = new App();
const server = new uServer();

server.attach(app);

app.listen(3000);
```

Reference: https://github.com/uNetworking/uWebSockets.js

Related: https://github.com/socketio/engine.io/issues/578
2021-11-02 22:46:09 +01:00
Damien Arrachequesne
fe5d97fc3d chore(release): 6.0.0
Diff: https://github.com/socketio/engine.io/compare/5.2.0...6.0.0
2021-10-08 16:12:32 +02:00
Damien Arrachequesne
c0d6eaa1ba chore: migrate to TypeScript
Related: https://github.com/socketio/engine.io/issues/510
2021-10-08 14:55:30 +02:00
Damien Arrachequesne
43606865e5 fix: properly close the websocket connection upon handshake error
This should fix the following error:

> TypeError: Cannot read property 'writeHead' of undefined

This bug was introduced by [1], because the `if (res !== undefined) { ... }`
check was removed.

But `res` is indeed undefined when the client connects with WebSocket
directly, in that case we need to manually write the response content
(in the abortUpgrade method).

Please note that the previous behavior was invalid too, since the
WebSocket connection was left open when an error occurred during the
handshake.

[1]: 7096e98a02
2021-05-17 00:22:39 +02:00
Damien Arrachequesne
8c9bd9262f chore(release): 5.1.0
Diff: https://github.com/socketio/engine.io/compare/5.0.0...5.1.0
2021-05-04 10:31:23 +02:00
Damien Arrachequesne
7706b123df perf: add a "wsPreEncoded" writing option
This option will be used when broadcasting a packet to multiple clients,
in order to only encode the packet once.

Usage:

```js
socket.write("test", {
  wsPreEncoded: "4test"
});
```

Note: pre-encoding the content with HTTP long-polling is a bit harder,
since the concatenation of the packets is specific to each client.
2021-05-04 08:44:06 +02:00
Branislav Katreniak
ad5306aeae perf(websocket): fix write back-pressure (#618)
This change should reduce memory usage when many packets are emitted to
many clients in a burst.

Co-authored-by: Branislav Katreniak <bkatreniak@slido.com>
2021-05-04 08:35:23 +02:00
Damien Arrachequesne
252754353a feat: add the "initial_headers" and "headers" events
Those events will be emitted before the response headers are written to
the socket:

- "initial_headers": on the first request of the connection
- "headers": on all requests (HTTP long-polling and WebSocket upgrade)

Syntax:

```js

server.on("initial_headers", (headers, req) => {
  headers["test"] = "123";
  headers["set-cookie"] = "mycookie=456";
});

server.on("headers", (headers, req) => {
  headers["test"] = "789";
});
```

Related:

- https://github.com/socketio/engine.io/issues/557
- https://github.com/socketio/socket.io/issues/3630
2021-04-30 14:38:11 +02:00
Damien Arrachequesne
7096e98a02 feat: add a "connection_error" event
The "connection_error" event will be emitted when one of the following
errors occurs:

- Transport unknown
- Session ID unknown
- Bad handshake method
- Bad request
- Forbidden
- Unsupported protocol version

Syntax:

```js
server.on("connection_error", (err) => {
  console.log(err.req);		// the request object
  console.log(err.code);	// the error code, for example 1
  console.log(err.message);	// the error message, for example "Session ID unknown"
  console.log(err.context);     // some additional error context
});
```

Related:

- https://github.com/socketio/socket.io/issues/3819
- https://github.com/socketio/engine.io/issues/576
2021-04-30 13:04:28 +02:00
Damien Arrachequesne
edb734316f feat: remove dynamic require() with wsEngine
This change is necessary to get rid of:

> Critical dependency: the request of a dependency is an expression

when bundling the server with webpack.

BREAKING CHANGE: the syntax of the "wsEngine" option is updated

Before:

```js
const eioServer = require("engine.io")(httpServer, {
  wsEngine: "eiows"
});
```

After:

```js
const eioServer = require("engine.io")(httpServer, {
  wsEngine: require("eiows").Server
});
```

Related: https://github.com/socketio/engine.io/issues/609
2021-03-09 08:30:05 +01:00
Damien Arrachequesne
ff2b8aba48 fix: do not reset the ping timer after upgrade
There was two issues with this behavior:

- v3 clients (with allowEIO3: true) were also receiving a "ping" after
a successful upgrade, which is incorrect (in v3, it's the client that
sends the "ping", and the server answers with a "pong")

- the ping timer is not reset after upgrade on the client-side, so an
upgrade which took longer than the `pingTimeout` duration could lead to
a "ping timeout" error on the client-side

I think the latter issue is present since the initial implementation.

Related: https://github.com/socketio/socket.io-client-swift/pull/1309#issuecomment-768475704
2021-02-02 10:48:02 +01:00
Damien Arrachequesne
663d326d18 feat: add support for v3.x clients
In order to ease the migration to Socket.IO v3, the Engine.IO server
can now communicate with v3.x clients.

```js
const eioServer = require("engine.io")(httpServer, {
  allowEIO3: true // false by default
});
```

If `allowEIO3` is false, the v3.x clients will now receive an HTTP 400
response ("Unsupported protocol version").

Note: the code of the v3 parser has been imported from [1] and
browser-related dependencies were removed.

[1]: https://github.com/socketio/engine.io-parser/tree/2.2.1

Related:

- https://github.com/socketio/engine.io-protocol/issues/35
- https://github.com/socketio/socket.io-protocol/issues/21
2021-01-14 01:44:52 +01:00
Marko Žarković
cec27502f5 fix: correctly pass the options when using the Server constructor (#610)
Fixes https://github.com/socketio/engine.io/issues/580
2020-12-30 10:04:47 +01:00
Damien Arrachequesne
f5efa1e02a refactor: use ES6 syntax for the tests 2020-12-07 10:57:28 +01:00
Damien Arrachequesne
312bd356c7 ci: migrate to GitHub Actions
Due to the recent changes to the Travis CI platform (see [1]), we will
now use GitHub Actions to run the tests.

Reference: https://docs.github.com/en/free-pro-team@latest/actions/guides/building-and-testing-nodejs

[1]: https://blog.travis-ci.com/2020-11-02-travis-ci-new-billing
2020-12-07 10:52:08 +01:00
Damien Arrachequesne
fe093bae1a fix: do not overwrite CORS headers upon error
The Access-Control-Allow-xxx headers added by the cors middleware were
overwritten when sending an error response.

Those lines should have been removed in [1].

[1]: 61b949259e

Related: https://github.com/socketio/engine.io/issues/605
2020-10-22 00:11:06 +02:00
Damien Arrachequesne
a05379b1e8 test: use eiows
The eiows package is the published version of [1], which is a fork of
uws (a performant WebSocket server written in C++ with bindings for
Node.js).

[1] https://github.com/mmdevries/uws
2020-09-14 22:20:36 +02:00
Damien Arrachequesne
078527a384 feat: disable perMessageDeflate by default
The WebSocket permessage-deflate extension, while useful is some cases,
adds some extra memory overhead for each WebSocket connection, and
results in huge memory usage in production deployments.

It will now be disabled by default.
2020-09-10 15:46:04 +02:00
Damien Arrachequesne
dcdbccb3dd fix: ignore errors when forcefully closing the socket (#601)
In order to catch the following errors:

```
events.js:288
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at afterWriteDispatched (internal/stream_base_commons.js:154:25)
    at writeGeneric (internal/stream_base_commons.js:145:3)
    at Socket._writeGeneric (net.js:780:11)
    at Socket._write (net.js:792:8)
    at doWrite (_stream_writable.js:441:12)
    at writeOrBuffer (_stream_writable.js:425:5)
    at Socket.Writable.write (_stream_writable.js:316:11)
    at abortConnection (<myproject>/node_modules/engine.io/lib/server.js:506:12)
    at <myproject>/node_modules/engine.io/lib/server.js:353:7
    at Server.verify (<myproject>/node_modules/engine.io/lib/server.js:158:14)
    at Server.handleUpgrade (<myproject>/node_modules/engine.io/lib/server.js:351:8)
```

Closes https://github.com/socketio/engine.io/issues/596, https://github.com/socketio/engine.io/pull/598
2020-04-15 11:42:31 +02:00
Damien Arrachequesne
61b949259e feat: use the cors module to handle cross-origin requests
We'll now rely on the standard cors module (https://github.com/expressjs/cors),
instead of the custom implementation that is error-prone and not
really user-friendly.

Breaking change: the handlePreflightRequest option is removed by the
change.

Before:

```
new Server({
  handlePreflightRequest: (req, res) => {
    res.writeHead(200, {
      "Access-Control-Allow-Origin": 'https://example.com',
      "Access-Control-Allow-Methods": 'GET',
      "Access-Control-Allow-Headers": 'Authorization',
      "Access-Control-Allow-Credentials": true
    });
    res.end();
  }
})
```

After:

```
new Server({
  cors: {
    origin: "https://example.com",
    methods: ["GET"],
    allowedHeaders: ["Authorization"],
    credentials: true
  }
})
```
2020-02-11 07:54:25 +01:00