@bymax-one/nest-realtime 1.2.9 → 1.2.10

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
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.10] - 2026-11-09
11
+
12
+ ### Fixed
13
+
14
+ - **A WebSocket handshake that arrives while the application is closing is refused.** The handshake
15
+ middleware authenticated every handshake and accepted it, however late it came, so a handshake
16
+ that arrived once shutdown had begun reached an authenticator whose store the host may already
17
+ have closed, and was accepted into a server that was about to close. From
18
+ `beforeApplicationShutdown` on, the middleware refuses it with a `connect_error` whose
19
+ `data.code` is `REALTIME_TRANSPORT_UNAVAILABLE`, before the authenticator runs and again if
20
+ shutdown began while the authenticator was running; this is the refusal SSE gives with a 503.
21
+ The code differs from `REALTIME_AUTH_FAILED`, which the same middleware uses for a refused
22
+ credential, so a client can tell the two apart.
23
+
24
+ #### Apply to a derived backend
25
+
26
+ `WebSocketTransport` gains a public `beforeApplicationShutdown()` hook and a `shuttingDown` getter,
27
+ and `RealtimeGateway` gains a private `unavailable` method. A class that extends either and already
28
+ declares a member with one of those names has to rename it or override it on purpose. A subclass
29
+ of `WebSocketTransport` that overrides `beforeApplicationShutdown` has to call
30
+ `super.beforeApplicationShutdown()`, or the gateway keeps accepting handshakes while the
31
+ application closes. A gateway that replaces `RealtimeGateway`'s handshake middleware gets no
32
+ refusal from this change; it can read `transport.shuttingDown` itself.
33
+
10
34
  ## [1.2.9] - 2026-11-06
11
35
 
12
36
  ### Changed
@@ -913,7 +937,8 @@ First published release.
913
937
  rather than by the manual sweep that raised the NestJS floors — that sweep
914
938
  asked about NestJS and never put the same question to the other ten peers.
915
939
 
916
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...HEAD
940
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...HEAD
941
+ [1.2.10]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...v1.2.10
917
942
  [1.2.9]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...v1.2.9
918
943
  [1.2.8]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...v1.2.8
919
944
  [1.2.7]: https://github.com/bymaxone/nest-realtime/compare/v1.2.6...v1.2.7
package/README.md CHANGED
@@ -871,19 +871,19 @@ These names belong to the library. Do not reuse them for application events. The
871
871
 
872
872
  ### Error Codes
873
873
 
874
- | Code | Status |
875
- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
876
- | `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
877
- | `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
878
- | `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
879
- | `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
880
- | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
881
- | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
882
- | `REALTIME_PUBSUB_UNAVAILABLE` | Raised as the rejection of a disconnect when the bus refuses the revocation; an emit's publish failure is logged and passed to the delivery-failure hook |
883
- | `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left |
884
- | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
885
- | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
886
- | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
874
+ | Code | Status |
875
+ | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
876
+ | `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
877
+ | `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
878
+ | `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
879
+ | `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
880
+ | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
881
+ | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
882
+ | `REALTIME_PUBSUB_UNAVAILABLE` | Raised as the rejection of a disconnect when the bus refuses the revocation; an emit's publish failure is logged and passed to the delivery-failure hook |
883
+ | `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left. Also what a new SSE stream or WebSocket handshake is refused with once shutdown has begun: a 503 whose message is the code, and a connect_error whose data.code is the code |
884
+ | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
885
+ | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
886
+ | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
887
887
 
888
888
  ### DI Tokens
889
889
 
@@ -7,6 +7,9 @@ var platformSocket_io = require('@nestjs/platform-socket.io');
7
7
 
8
8
  var __defProp = Object.defineProperty;
9
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __typeError = (msg) => {
11
+ throw TypeError(msg);
12
+ };
10
13
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
14
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
12
15
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -23,8 +26,13 @@ var __decorateClass = (decorators, target, key, kind) => {
23
26
  return result;
24
27
  };
25
28
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
26
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
29
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
30
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
31
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
32
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
27
34
  var CONNECTION_ROOM_PREFIX = "connection";
35
+ var _shuttingDown;
28
36
  exports.WebSocketTransport = class WebSocketTransport {
29
37
  constructor(connections, rooms, auth, hooks, options) {
30
38
  this.connections = connections;
@@ -32,16 +40,23 @@ exports.WebSocketTransport = class WebSocketTransport {
32
40
  this.auth = auth;
33
41
  this.hooks = hooks;
34
42
  this.options = options;
43
+ __publicField(this, "kind", "websocket");
44
+ __publicField(this, "logger", new common.Logger(exports.WebSocketTransport.name));
45
+ __publicField(this, "server", null);
46
+ __publicField(this, "warnedUnattached", false);
47
+ __privateAdd(this, _shuttingDown, false);
35
48
  }
36
49
  connections;
37
50
  rooms;
38
51
  auth;
39
52
  hooks;
40
53
  options;
41
- kind = "websocket";
42
- logger = new common.Logger(exports.WebSocketTransport.name);
43
- server = null;
44
- warnedUnattached = false;
54
+ async beforeApplicationShutdown() {
55
+ __privateSet(this, _shuttingDown, true);
56
+ }
57
+ get shuttingDown() {
58
+ return __privateGet(this, _shuttingDown);
59
+ }
45
60
  setServer(server) {
46
61
  this.server = server;
47
62
  this.logger.log("Socket.IO server wired to WebSocketTransport");
@@ -181,6 +196,7 @@ exports.WebSocketTransport = class WebSocketTransport {
181
196
  }
182
197
  }
183
198
  };
199
+ _shuttingDown = new WeakMap();
184
200
  exports.WebSocketTransport = __decorateClass([
185
201
  common.Injectable(),
186
202
  __decorateParam(0, common.Inject(internal.ConnectionRegistry)),
@@ -353,7 +369,15 @@ exports.RealtimeGateway = class RealtimeGateway {
353
369
  authenticated = /* @__PURE__ */ new WeakMap();
354
370
  authenticateHandshake = async (socket, next) => {
355
371
  try {
372
+ if (this.transport.shuttingDown) {
373
+ next(this.unavailable());
374
+ return;
375
+ }
356
376
  const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
377
+ if (this.transport.shuttingDown) {
378
+ next(this.unavailable());
379
+ return;
380
+ }
357
381
  if (!auth) {
358
382
  const refusal = new Error(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
359
383
  refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
@@ -369,6 +393,11 @@ exports.RealtimeGateway = class RealtimeGateway {
369
393
  next(new Error("Internal Server Error"));
370
394
  }
371
395
  };
396
+ unavailable() {
397
+ const refusal = new Error(internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
398
+ refusal.data = { code: internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE };
399
+ return refusal;
400
+ }
372
401
  afterInit(server) {
373
402
  server.use(this.authenticateHandshake);
374
403
  this.transport.setServer(server);
@@ -405,6 +434,10 @@ exports.RealtimeGateway = class RealtimeGateway {
405
434
  let resolvedAuth = this.authenticated.get(socket);
406
435
  this.authenticated.delete(socket);
407
436
  if (!resolvedAuth) {
437
+ if (this.transport.shuttingDown) {
438
+ socket.disconnect(true);
439
+ return;
440
+ }
408
441
  const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
409
442
  if (!auth) {
410
443
  socket.disconnect(true);
@@ -72,6 +72,7 @@ declare class BymaxRealtimeWebSocketModule {
72
72
  * the gateway. All emit methods are safe no-ops while the server is unset.
73
73
  */
74
74
  declare class WebSocketTransport implements ITransport {
75
+ #private;
75
76
  private readonly connections;
76
77
  private readonly rooms;
77
78
  private readonly auth;
@@ -83,6 +84,16 @@ declare class WebSocketTransport implements ITransport {
83
84
  private server;
84
85
  private warnedUnattached;
85
86
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
+ /**
88
+ * Mark shutdown as begun, so the gateway refuses a handshake from here on.
89
+ *
90
+ * Socket.IO closes every connection that is open when the server closes, so no connection is
91
+ * torn down here; a socket accepted after this point would only be closed a moment later, and
92
+ * its authenticator may already depend on a store the host has closed.
93
+ */
94
+ beforeApplicationShutdown(): Promise<void>;
95
+ /** Whether shutdown has begun, after which a new handshake is refused. */
96
+ get shuttingDown(): boolean;
86
97
  /**
87
98
  * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
88
99
  *
@@ -238,6 +249,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
238
249
  private readonly authenticated;
239
250
  /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
240
251
  private readonly authenticateHandshake;
252
+ /** The refusal for a handshake that arrives once shutdown has begun: a `connect_error` carrying `data.code`. */
253
+ private unavailable;
241
254
  /** Wire the resolved Socket.IO server to the transport after gateway init. */
242
255
  afterInit(server: Server): void;
243
256
  /** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
@@ -72,6 +72,7 @@ declare class BymaxRealtimeWebSocketModule {
72
72
  * the gateway. All emit methods are safe no-ops while the server is unset.
73
73
  */
74
74
  declare class WebSocketTransport implements ITransport {
75
+ #private;
75
76
  private readonly connections;
76
77
  private readonly rooms;
77
78
  private readonly auth;
@@ -83,6 +84,16 @@ declare class WebSocketTransport implements ITransport {
83
84
  private server;
84
85
  private warnedUnattached;
85
86
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
+ /**
88
+ * Mark shutdown as begun, so the gateway refuses a handshake from here on.
89
+ *
90
+ * Socket.IO closes every connection that is open when the server closes, so no connection is
91
+ * torn down here; a socket accepted after this point would only be closed a moment later, and
92
+ * its authenticator may already depend on a store the host has closed.
93
+ */
94
+ beforeApplicationShutdown(): Promise<void>;
95
+ /** Whether shutdown has begun, after which a new handshake is refused. */
96
+ get shuttingDown(): boolean;
86
97
  /**
87
98
  * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
88
99
  *
@@ -238,6 +249,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
238
249
  private readonly authenticated;
239
250
  /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
240
251
  private readonly authenticateHandshake;
252
+ /** The refusal for a handshake that arrives once shutdown has begun: a `connect_error` carrying `data.code`. */
253
+ private unavailable;
241
254
  /** Wire the resolved Socket.IO server to the transport after gateway init. */
242
255
  afterInit(server: Server): void;
243
256
  /** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
@@ -7,6 +7,9 @@ import { IoAdapter } from '@nestjs/platform-socket.io';
7
7
  const require$1 = createRequire(import.meta.url || __filename);
8
8
  var __defProp = Object.defineProperty;
9
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __typeError = (msg) => {
11
+ throw TypeError(msg);
12
+ };
10
13
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
14
  var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
12
15
  get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
@@ -23,8 +26,13 @@ var __decorateClass = (decorators, target, key, kind) => {
23
26
  return result;
24
27
  };
25
28
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
26
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
29
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
30
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
31
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
32
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
27
34
  var CONNECTION_ROOM_PREFIX = "connection";
35
+ var _shuttingDown;
28
36
  var WebSocketTransport = class {
29
37
  constructor(connections, rooms, auth, hooks, options) {
30
38
  this.connections = connections;
@@ -32,16 +40,23 @@ var WebSocketTransport = class {
32
40
  this.auth = auth;
33
41
  this.hooks = hooks;
34
42
  this.options = options;
43
+ __publicField(this, "kind", "websocket");
44
+ __publicField(this, "logger", new Logger(WebSocketTransport.name));
45
+ __publicField(this, "server", null);
46
+ __publicField(this, "warnedUnattached", false);
47
+ __privateAdd(this, _shuttingDown, false);
35
48
  }
36
49
  connections;
37
50
  rooms;
38
51
  auth;
39
52
  hooks;
40
53
  options;
41
- kind = "websocket";
42
- logger = new Logger(WebSocketTransport.name);
43
- server = null;
44
- warnedUnattached = false;
54
+ async beforeApplicationShutdown() {
55
+ __privateSet(this, _shuttingDown, true);
56
+ }
57
+ get shuttingDown() {
58
+ return __privateGet(this, _shuttingDown);
59
+ }
45
60
  setServer(server) {
46
61
  this.server = server;
47
62
  this.logger.log("Socket.IO server wired to WebSocketTransport");
@@ -181,6 +196,7 @@ var WebSocketTransport = class {
181
196
  }
182
197
  }
183
198
  };
199
+ _shuttingDown = new WeakMap();
184
200
  WebSocketTransport = __decorateClass([
185
201
  Injectable(),
186
202
  __decorateParam(0, Inject(ConnectionRegistry)),
@@ -353,7 +369,15 @@ var RealtimeGateway = class {
353
369
  authenticated = /* @__PURE__ */ new WeakMap();
354
370
  authenticateHandshake = async (socket, next) => {
355
371
  try {
372
+ if (this.transport.shuttingDown) {
373
+ next(this.unavailable());
374
+ return;
375
+ }
356
376
  const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
377
+ if (this.transport.shuttingDown) {
378
+ next(this.unavailable());
379
+ return;
380
+ }
357
381
  if (!auth) {
358
382
  const refusal = new Error(REALTIME_ERROR_CODES.AUTH_FAILED);
359
383
  refusal.data = { code: REALTIME_ERROR_CODES.AUTH_FAILED };
@@ -369,6 +393,11 @@ var RealtimeGateway = class {
369
393
  next(new Error("Internal Server Error"));
370
394
  }
371
395
  };
396
+ unavailable() {
397
+ const refusal = new Error(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
398
+ refusal.data = { code: REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE };
399
+ return refusal;
400
+ }
372
401
  afterInit(server) {
373
402
  server.use(this.authenticateHandshake);
374
403
  this.transport.setServer(server);
@@ -405,6 +434,10 @@ var RealtimeGateway = class {
405
434
  let resolvedAuth = this.authenticated.get(socket);
406
435
  this.authenticated.delete(socket);
407
436
  if (!resolvedAuth) {
437
+ if (this.transport.shuttingDown) {
438
+ socket.disconnect(true);
439
+ return;
440
+ }
408
441
  const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
409
442
  if (!auth) {
410
443
  socket.disconnect(true);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.9",
3
+ "version": "1.2.10",
4
4
  "description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -96,7 +96,7 @@
96
96
  "build": "pnpm clean && tsup && node scripts/strip-bundle-comments.mjs",
97
97
  "check:exports": "attw --pack . --profile strict",
98
98
  "check:mutants": "node scripts/check-mutation-directives.mjs",
99
- "check:file-size": "node scripts/check-file-size.mjs",
99
+ "check:file-length": "node scripts/check-file-length.mjs",
100
100
  "check:api": "node scripts/check-api-surface.mjs",
101
101
  "check:published": "node scripts/check-published-surface.mjs",
102
102
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
@@ -108,7 +108,7 @@
108
108
  "mutation": "stryker run",
109
109
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
110
110
  "mutation:dry-run": "stryker run --dryRunOnly",
111
- "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:file-size && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
111
+ "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:file-length && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
112
112
  "release": "npm publish --provenance --access public",
113
113
  "size": "node scripts/check-size.mjs",
114
114
  "test": "jest",