@jskit-ai/realtime 0.2.49 → 0.2.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - **Breaking. Security.** Realtime connects over WebSocket only. `createSocketIoClient` and `createSocketIoServer`, which the client and server providers use, set Socket.IO's `transports` to `["websocket"]` whatever options they are given, as they fix its `path`, so the server refuses a long-polling request with a 400 (`Transport unknown`). Before, every connection opened with HTTP long-polling, which names the connection's Engine.IO session id in the address of each later request and of its upgrade (`/socket.io/?EIO=4&transport=polling&sid=...`): request logs, the application's and any proxy's, kept it, whoever read one could poll that connection's events while it lived, and a scanner reports it as a session id in the URL (OWASP ZAP rule 3, a CASA failure). A WebSocket carries it inside the connection. Each browser's connection is now one WebSocket, so several copies behind a load balancer need no sticky sessions for realtime, and `realtimeClient: { options: { transports } }` no longer changes the transport. Whatever runs in front of the app passes WebSocket upgrades on `/socket.io`, as the package's Vite proxy entry does; where a network blocks WebSockets, realtime stays disconnected and retries while pages and API calls keep working.
6
+ - Engine.IO's answers, its refusals and the 101 that opens a WebSocket, carry `X-Content-Type-Options: nosniff` and `Cache-Control: no-store, no-cache, must-revalidate`, as the kernel's API answers do. Socket.IO answers on the HTTP server itself, outside Fastify's hooks, so they had none of the security headers the kernel gives every other answer, and a scanner reports the missing nosniff (OWASP ZAP rule 10021) and Engine.IO's bare `no-store` (rule 10015). `createSocketIoServer` sets both in an Engine.IO middleware, which runs for every request before Engine.IO checks it.
5
7
  - The realtime application pattern asks whether staging or production needs a Redis backplane, where it said the deployment.
6
8
  - **Breaking.** The Redis backplane's address is read from `REALTIME_REDIS_URL`, the name the realtime guide, the `realtime/realtime-application` pattern and its `.env.example` give. It was read from `REDIS_URL`, so an app that set the documented name stayed on the in-process adapter, and each of its copies behind a load balancer delivered events only to the browsers connected to that copy. An app that set `REDIS_URL` for realtime sets `REALTIME_REDIS_URL` instead; `REDIS_NAMESPACE` is unchanged. The pattern's test now reads the name from the runtime, so the two cannot drift apart again.
7
9
  - A publish to a user or workspace room no longer reads the memberships of every online actor. It asks each audience contributor about the actors of the sockets outside its target rooms only for those rooms' scopes, `resolveActorsScopes(actorIds, { scopes })`, and keeps only those rooms of the answer, while the actors already inside are looked up in full for their checks. A contributor that ignores `scopes` still answers correctly. Before, every write action read the memberships of every signed-in socket's actor, so the cost grew with everyone online, also for an event to one user.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/realtime",
3
- "version": "0.2.49",
3
+ "version": "0.2.50",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -24,7 +24,7 @@
24
24
  "socket.io-client": "^4.8.3"
25
25
  },
26
26
  "peerDependencies": {
27
- "@jskit-ai/kernel": "0.2.30",
27
+ "@jskit-ai/kernel": "0.2.31",
28
28
  "vue": "^3.5.13"
29
29
  },
30
30
  "description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
@@ -34,6 +34,8 @@ staging or production needs a Redis backplane.
34
34
  - Event payloads do not become an undocumented second API.
35
35
  - Socket.IO owns `/socket.io`; other WebSocket routes keep their own upgrade
36
36
  and access-check lifecycle without Socket.IO's one-second cleanup timeout.
37
+ - Realtime connects over WebSocket only, so no address carries its session id;
38
+ whatever runs in front of the app passes WebSocket upgrades on `/socket.io`.
37
39
 
38
40
  ## Framework APIs
39
41
 
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/realtime": "0.2.49",
6
- "@jskit-ai/shell-web": "0.2.46"
5
+ "@jskit-ai/realtime": "0.2.50",
6
+ "@jskit-ai/shell-web": "0.2.47"
7
7
  }
8
8
  }
@@ -2,11 +2,15 @@ import { io as connectSocketIoClient } from "socket.io-client";
2
2
  import { normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
 
4
4
  const SOCKET_IO_PATH = "/socket.io";
5
+ // The server takes WebSocket only (server/runtime.js): long-polling would put the connection's session id in every
6
+ // request's address.
7
+ const SOCKET_IO_TRANSPORTS = Object.freeze(["websocket"]);
5
8
 
6
9
  /**
7
10
  * @param {object} client
8
11
  * @param {string} [client.url]
9
12
  * @param {Partial<import("socket.io-client").ManagerOptions & import("socket.io-client").SocketOptions>} [client.options]
13
+ * Socket.IO's options; its path (/socket.io) and transports (WebSocket only) are fixed.
10
14
  * @param {typeof connectSocketIoClient} [client.connect]
11
15
  */
12
16
  function createSocketIoClient({
@@ -17,7 +21,8 @@ function createSocketIoClient({
17
21
  const normalizedUrl = normalizeText(url);
18
22
  const normalizedOptions = {
19
23
  ...normalizeObject(options),
20
- path: SOCKET_IO_PATH
24
+ path: SOCKET_IO_PATH,
25
+ transports: [...SOCKET_IO_TRANSPORTS]
21
26
  };
22
27
  if (normalizedUrl) {
23
28
  return connect(normalizedUrl, normalizedOptions);
@@ -3,6 +3,11 @@ import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
  import { toRequestPathname } from "@jskit-ai/kernel/shared/surface/paths";
4
4
 
5
5
  const SOCKET_IO_PATH = "/socket.io";
6
+ // Long-polling names the connection's Engine.IO session id in every request's address after its handshake (sid=), which
7
+ // a request log keeps and which anyone who reads it could poll for that connection's events while it lives (OWASP ZAP
8
+ // rule 3, Session ID in URL). A WebSocket carries it inside the connection. Polling's requests must also all reach the
9
+ // server copy that opened the session; a WebSocket is one connection.
10
+ const SOCKET_IO_TRANSPORTS = Object.freeze(["websocket"]);
6
11
  // The name the realtime guide, the realtime-application pattern and its .env.example give.
7
12
  const REDIS_URL_ENV_KEY = "REALTIME_REDIS_URL";
8
13
  const REDIS_NAMESPACE_ENV_KEY = "REDIS_NAMESPACE";
@@ -34,7 +39,8 @@ function resolveHttpServer({ httpServer = null, fastify = null } = {}) {
34
39
  * @param {object} [options]
35
40
  * @param {import("node:http").Server | null} [options.httpServer] The HTTP server to attach to; Fastify's when absent.
36
41
  * @param {import("@jskit-ai/kernel/server/types").RuntimeFastify | null} [options.fastify]
37
- * @param {Partial<import("socket.io").ServerOptions>} [options.options]
42
+ * @param {Partial<import("socket.io").ServerOptions>} [options.options] Socket.IO's options; its path (/socket.io) and
43
+ * transports (WebSocket only) are fixed.
38
44
  * @param {typeof SocketIoServer} [options.ServerCtor]
39
45
  */
40
46
  function createSocketIoServer({
@@ -56,10 +62,31 @@ function createSocketIoServer({
56
62
  // Application WebSocket routes may still be authorizing their upgrades.
57
63
  destroyUpgrade: false,
58
64
  ...options,
59
- path: SOCKET_IO_PATH
65
+ path: SOCKET_IO_PATH,
66
+ transports: [...SOCKET_IO_TRANSPORTS]
60
67
  };
61
68
  registerSocketIoUpgradeHandoff(fastify);
62
- return new ServerCtor(server, normalizedOptions);
69
+ const io = new ServerCtor(server, normalizedOptions);
70
+ addEngineHeaders(io);
71
+ return io;
72
+ }
73
+
74
+ /**
75
+ * Engine.IO answers on the HTTP server itself, outside Fastify's hooks, so its answers miss the security headers every
76
+ * other answer gets (kernel registerSecurityHeaders). Taking WebSocket only, it answers a request for anything else,
77
+ * such as a long-polling handshake, with a 400 refusal. Each answer gets nosniff, so no browser reads it as another
78
+ * type, and the Cache-Control the kernel gives API answers (OWASP ZAP rule 10015 asks for all three).
79
+ * @param {import("socket.io").Server} io
80
+ */
81
+ function addEngineHeaders(io) {
82
+ if (!io?.engine) return;
83
+ // Engine.IO's middlewares run first for every request, an upgrade included (whose 101 answer then carries them too),
84
+ // before it checks the transport, and its refusals keep the headers set here.
85
+ io.engine.use((_request, response, next) => {
86
+ response.setHeader("X-Content-Type-Options", "nosniff");
87
+ response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
88
+ next();
89
+ });
63
90
  }
64
91
 
65
92
  // Socket.IO runs on an HTTP server its caller owns (Fastify's, for the
@@ -6,8 +6,9 @@ import { Server } from "socket.io";
6
6
 
7
7
  import { createSocketIoClient, disconnectSocketIoClient, reconnectSocketIoClient } from "../src/client/runtime.js";
8
8
  import { attachSocketConnectionRecovery } from "../src/client/connectionRecovery.js";
9
+ import { closeSocketIoServer, createSocketIoServer } from "../src/server/runtime.js";
9
10
 
10
- test("createSocketIoClient calls connect with fixed socket path", () => {
11
+ test("createSocketIoClient calls connect with fixed socket path and WebSocket only", () => {
11
12
  const calls = [];
12
13
  const socket = {
13
14
  id: "socket-1"
@@ -21,6 +22,7 @@ test("createSocketIoClient calls connect with fixed socket path", () => {
21
22
  url: " https://example.com ",
22
23
  options: {
23
24
  path: "realtime",
25
+ transports: ["polling", "websocket"],
24
26
  withCredentials: true
25
27
  },
26
28
  connect
@@ -32,6 +34,7 @@ test("createSocketIoClient calls connect with fixed socket path", () => {
32
34
  "https://example.com",
33
35
  {
34
36
  path: "/socket.io",
37
+ transports: ["websocket"],
35
38
  withCredentials: true
36
39
  }
37
40
  ]);
@@ -56,7 +59,8 @@ test("createSocketIoClient supports url-less connection with fixed socket path",
56
59
  assert.equal(calls.length, 1);
57
60
  assert.deepEqual(calls[0], [
58
61
  {
59
- path: "/socket.io"
62
+ path: "/socket.io",
63
+ transports: ["websocket"]
60
64
  }
61
65
  ]);
62
66
  });
@@ -211,9 +215,7 @@ test("a real server-forced disconnect reconnects through a fresh authenticated h
211
215
  });
212
216
  http.listen(0, "127.0.0.1");
213
217
  await once(http, "listening");
214
- // WebSocket only, like the other real-socket tests: a polling transport the server closes waits 30 s for a poll
215
- // that never comes, which keeps this file running long after its tests.
216
- const client = createSocketIoClient({ url: `http://127.0.0.1:${http.address().port}`, options: { transports: ["websocket"] } });
218
+ const client = createSocketIoClient({ url: `http://127.0.0.1:${http.address().port}` });
217
219
  const detach = attachSocketConnectionRecovery(client, { prepareReconnect: prepareNothing });
218
220
  t.after(async () => {
219
221
  detach();
@@ -238,7 +240,7 @@ test("reconnect now opens a fresh transport while Socket.IO waits out its backof
238
240
  await once(http, "listening");
239
241
  const client = createSocketIoClient({
240
242
  url: `http://127.0.0.1:${http.address().port}`,
241
- options: { transports: ["websocket"], randomizationFactor: 0, reconnectionDelay: 60_000, reconnectionDelayMax: 60_000 }
243
+ options: { randomizationFactor: 0, reconnectionDelay: 60_000, reconnectionDelayMax: 60_000 }
242
244
  });
243
245
  t.after(async () => {
244
246
  client.disconnect();
@@ -258,6 +260,79 @@ test("reconnect now opens a fresh transport while Socket.IO waits out its backof
258
260
  assert.equal(client.connected, true);
259
261
  });
260
262
 
263
+ /**
264
+ * A JSKIT realtime server on the port given (a free one for 0). It records the address of every HTTP request and
265
+ * upgrade that reaches it, the line a request log records, the application's own or a proxy's in front of it.
266
+ * @param {number} port
267
+ * @param {string[]} addresses
268
+ */
269
+ async function recordingRealtimeServer(port, addresses) {
270
+ const http = createServer();
271
+ const io = createSocketIoServer({ httpServer: http });
272
+ for (const event of ["request", "upgrade"]) http.prependListener(event, (request) => addresses.push(request.url));
273
+ http.listen(port, "127.0.0.1");
274
+ await once(http, "listening");
275
+ let closing = null;
276
+ return {
277
+ port: http.address().port,
278
+ close() {
279
+ closing ??= (async () => {
280
+ await closeSocketIoServer(io);
281
+ http.closeAllConnections();
282
+ await new Promise((resolve) => http.close(resolve));
283
+ })();
284
+ return closing;
285
+ }
286
+ };
287
+ }
288
+
289
+ /**
290
+ * Asserts that no address carries an Engine.IO session id and that every one went to Socket.IO by WebSocket.
291
+ * @param {string[]} addresses
292
+ * @param {string[]} sessionIds
293
+ */
294
+ function assertNoSessionIdIn(addresses, sessionIds) {
295
+ assert.ok(addresses.length > 0);
296
+ const leaking = addresses.filter((address) =>
297
+ /[?&]sid=/u.test(address) || sessionIds.some((sessionId) => address.includes(sessionId)));
298
+ assert.deepEqual(leaking, []);
299
+ for (const address of addresses) {
300
+ assert.match(address, /^\/socket\.io\/\?EIO=4&transport=websocket(?:&|$)/u, address);
301
+ }
302
+ }
303
+
304
+ test("the client connects, and reconnects to a restarted server, by WebSocket only: no address carries its session id", { timeout: 10_000 }, async (t) => {
305
+ const addresses = [];
306
+ const first = await recordingRealtimeServer(0, addresses);
307
+ let second = null;
308
+ const client = createSocketIoClient({ url: `http://127.0.0.1:${first.port}`,
309
+ options: { randomizationFactor: 0, reconnectionDelay: 100, reconnectionDelayMax: 200 } });
310
+ t.after(async () => {
311
+ client.disconnect();
312
+ await second?.close();
313
+ await first.close();
314
+ });
315
+ await once(client, "connect", { signal: AbortSignal.timeout(4_000) });
316
+ const sessionIds = [client.io.engine.id];
317
+ assertNoSessionIdIn(addresses, sessionIds);
318
+ assert.equal(client.io.engine.transport.name, "websocket");
319
+ // A release: the server goes away, Socket.IO's reconnection fails while nothing listens, then the new one answers.
320
+ const disconnected = once(client, "disconnect");
321
+ // Not events.once(), which rejects on the "error" the manager also emits for each failed attempt.
322
+ const failedAttempt = new Promise((resolve) => client.io.once("reconnect_error", resolve));
323
+ await first.close();
324
+ assert.equal((await disconnected)[0], "transport close");
325
+ assert.match(String((await failedAttempt)?.message), /websocket error/u);
326
+ assert.equal(client.connected, false);
327
+ second = await recordingRealtimeServer(first.port, addresses);
328
+ await once(client, "connect", { signal: AbortSignal.timeout(4_000) });
329
+ sessionIds.push(client.io.engine.id);
330
+ assert.equal(client.io.engine.transport.name, "websocket");
331
+ assert.notEqual(sessionIds[1], sessionIds[0]);
332
+ assert.ok(addresses.length >= 2, addresses.join(" "));
333
+ assertNoSessionIdIn(addresses, sessionIds);
334
+ });
335
+
261
336
  test("a page that wakes mid-backoff reconnects now unless the app disconnected on purpose", (t) => {
262
337
  const previousDocument = globalThis.document;
263
338
  const document = Object.assign(new EventTarget(), { hidden: false });
@@ -1,4 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
+ import { randomBytes } from "node:crypto";
2
3
  import { once } from "node:events";
3
4
  import { createServer, get } from "node:http";
4
5
  import test from "node:test";
@@ -33,6 +34,7 @@ test("createSocketIoServer uses provided http server and fixed socket path", ()
33
34
  httpServer,
34
35
  options: {
35
36
  path: "ws",
37
+ transports: ["polling", "websocket"],
36
38
  cors: {
37
39
  origin: "*"
38
40
  }
@@ -45,6 +47,7 @@ test("createSocketIoServer uses provided http server and fixed socket path", ()
45
47
  assert.deepEqual(calls[0].options, {
46
48
  destroyUpgrade: false,
47
49
  path: "/socket.io",
50
+ transports: ["websocket"],
48
51
  cors: {
49
52
  origin: "*"
50
53
  }
@@ -132,6 +135,42 @@ test("realtime leaves slow application upgrades and access denials to their rout
132
135
  assert.equal(client.connected, true, "Socket.IO still owns its own upgrade route");
133
136
  });
134
137
 
138
+ test("a JSKIT realtime server takes WebSocket only: it refuses long-polling, with nosniff and no-store", { timeout: 5_000 }, async (t) => {
139
+ const server = createServer();
140
+ const realtime = createSocketIoServer({ httpServer: server });
141
+ let client;
142
+ t.after(async () => {
143
+ client?.disconnect();
144
+ await closeSocketIoServer(realtime);
145
+ server.closeAllConnections();
146
+ await new Promise((resolve) => server.close(resolve));
147
+ });
148
+ server.listen(0, "127.0.0.1");
149
+ await once(server, "listening");
150
+ const origin = `http://127.0.0.1:${server.address().port}`;
151
+ // A long-polling handshake would answer a session id that every later request of the session carries in its URL
152
+ // (OWASP ZAP rule 3, Session ID in URL). Engine.IO answers its refusals on the HTTP server itself, outside Fastify's
153
+ // hooks, so they get the headers the kernel gives API answers here.
154
+ const polling = await fetch(`${origin}/socket.io/?EIO=4&transport=polling`);
155
+ assert.equal(polling.status, 400);
156
+ assert.deepEqual(await polling.json(), { code: 0, message: "Transport unknown" });
157
+ assert.equal(polling.headers.get("x-content-type-options"), "nosniff");
158
+ assert.equal(polling.headers.get("cache-control"), "no-store, no-cache, must-revalidate");
159
+ const upgrade = await new Promise((resolve, reject) => {
160
+ const request = get(`${origin}/socket.io/?EIO=4&transport=websocket`, { headers: { Connection: "Upgrade",
161
+ Upgrade: "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": randomBytes(16).toString("base64") } });
162
+ request.on("error", reject);
163
+ request.on("response", (reply) => { reply.resume(); reject(new Error(`No upgrade: ${reply.statusCode}`)); });
164
+ request.on("upgrade", (reply, socket) => { socket.destroy(); resolve(reply); });
165
+ });
166
+ assert.equal(upgrade.statusCode, 101);
167
+ assert.equal(upgrade.headers["x-content-type-options"], "nosniff");
168
+ assert.equal(upgrade.headers["cache-control"], "no-store, no-cache, must-revalidate");
169
+ client = connectSocketIo(origin, { transports: ["websocket"], reconnection: false });
170
+ await once(client, "connect", { signal: AbortSignal.timeout(4_000) });
171
+ assert.equal(client.io.engine.transport.name, "websocket");
172
+ });
173
+
135
174
  test("createSocketIoServer falls back to fastify.server", () => {
136
175
  const fastifyServer = {
137
176
  id: "fastify-server"