@bymax-one/nest-realtime 1.2.13 → 1.2.15

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.
@@ -1,5 +1,5 @@
1
1
  import { DynamicModule, INestApplicationContext } from '@nestjs/common';
2
- import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, IConnectionAuthenticator, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, AuthenticationResult, SseTransport } from '@bymax-one/nest-realtime/internal';
2
+ import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, AuthenticationGate, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, ConnectionAdmission, ConnectionAuthContext, AuthenticationResult, AdmissionTicket, SseTransport } from '@bymax-one/nest-realtime/internal';
3
3
  export { WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions } from '@bymax-one/nest-realtime/internal';
4
4
  import { Server, Socket, ServerOptions } from 'socket.io';
5
5
  import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
@@ -75,15 +75,16 @@ declare class WebSocketTransport implements ITransport {
75
75
  #private;
76
76
  private readonly connections;
77
77
  private readonly rooms;
78
- private readonly auth;
78
+ private readonly gate;
79
79
  private readonly hooks;
80
80
  private readonly options;
81
+ private readonly admission?;
81
82
  readonly kind: "websocket";
82
83
  private readonly logger;
83
84
  /** Nullable until the gateway's afterInit wires the instance. */
84
85
  private server;
85
86
  private warnedUnattached;
86
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, gate: AuthenticationGate, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, admission?: ConnectionAdmission | undefined);
87
88
  /**
88
89
  * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
89
90
  * nearer the root than the realtime module still runs first, and until it returns a handshake is
@@ -129,15 +130,14 @@ declare class WebSocketTransport implements ITransport {
129
130
  */
130
131
  private localSockets;
131
132
  /**
132
- * Expose the configured authenticator to the gateway.
133
+ * Authenticate a handshake through the gate both transports share: bounded in time, and in how
134
+ * many are waiting at once. The gateway calls this rather than the authenticator, which also
135
+ * avoids injecting the token in it.
133
136
  *
134
- * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
135
- * `WebSocketTransport` → authenticator, rather than injecting the token
136
- * directly in the gateway.
137
- *
138
- * @returns The consumer-provided `IConnectionAuthenticator` instance.
137
+ * @throws AuthenticationUnavailableError when too many handshakes are waiting, or this one did
138
+ * not settle in time.
139
139
  */
140
- authenticator(): IConnectionAuthenticator;
140
+ authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
141
141
  /**
142
142
  * Register a freshly-authenticated WebSocket connection.
143
143
  *
@@ -224,9 +224,16 @@ declare class WebSocketTransport implements ITransport {
224
224
  * fan-out throws: the revocation did not leave this node.
225
225
  */
226
226
  disconnect(connectionId: string, _reason?: string): Promise<void>;
227
+ /**
228
+ * Take a place for a connection before it is authenticated.
229
+ *
230
+ * @throws ConnectionLimitError when the instance already holds `maxConnections`.
231
+ */
232
+ admit(): AdmissionTicket;
227
233
  /**
228
234
  * Evict the user's oldest WebSocket connections (FIFO) when over
229
- * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
235
+ * `websocket.maxConnectionsPerUser`, which is {@link DEFAULT_MAX_CONNECTIONS_PER_USER} when
236
+ * unset and unbounded when `0`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
230
237
  * as the disconnect reason — never rejects the new connection with HTTP 429.
231
238
  */
232
239
  private evictBeyondLimit;
@@ -257,9 +264,20 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
257
264
  constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
258
265
  /** Identities the handshake middleware resolved, until `handleConnection` takes them. */
259
266
  private readonly authenticated;
267
+ /** The place held for a socket from before its handshake is authenticated until it is registered. */
268
+ private readonly tickets;
260
269
  /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
261
270
  private readonly authenticateHandshake;
262
- /** The refusal for a handshake that arrives once shutdown has begun: a `connect_error` carrying `data.code`. */
271
+ /**
272
+ * The error a handshake that failed is answered with, after the log line the failure earns.
273
+ *
274
+ * The gate and the admission count and log their own refusals once for each window; one line for
275
+ * each handshake would let an attack flood the log. The message stays generic. A refusal that is
276
+ * the instance's capacity or the authenticator's availability carries the transport code, so a
277
+ * client can retry it; any other failure is not something a client can act on and carries none.
278
+ */
279
+ private refusalFor;
280
+ /** A `connect_error` carrying `data.code` `REALTIME_TRANSPORT_UNAVAILABLE`, for a handshake the instance cannot take now. */
263
281
  private unavailable;
264
282
  /** Wire the resolved Socket.IO server to the transport after gateway init. */
265
283
  afterInit(server: Server): void;
@@ -299,6 +317,18 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
299
317
  */
300
318
  private buildAuthContext;
301
319
  handleConnection(socket: Socket): Promise<void>;
320
+ /**
321
+ * Take a place for a socket, given back when it is released or when the socket's engine connection
322
+ * closes. Several namespaces share one engine connection, so the listener is removed on release:
323
+ * left attached, every handshake that is refused would add one for as long as the connection lives.
324
+ */
325
+ private admit;
326
+ /**
327
+ * The identity of a socket and the place held for it: what the handshake middleware kept, or, for a
328
+ * socket it never saw, a fresh authentication, failing closed. Resolves to nothing for a socket that
329
+ * has been disconnected here.
330
+ */
331
+ private takeHandshake;
302
332
  /** Handle a WebSocket disconnection — unregister the connection. */
303
333
  handleDisconnect(socket: Socket): Promise<void>;
304
334
  /**
@@ -337,6 +367,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
337
367
  declare class RealtimeIoAdapter extends IoAdapter {
338
368
  private readonly adapterLogger;
339
369
  private readonly options;
370
+ /** The subscriber connections this adapter opened for the Redis adapter, closed with it. */
371
+ private readonly subscribers;
340
372
  constructor(app: INestApplicationContext);
341
373
  /**
342
374
  * Bind the gateway to `websocket.namespace` when configured.
@@ -360,6 +392,25 @@ declare class RealtimeIoAdapter extends IoAdapter {
360
392
  * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
361
393
  */
362
394
  createIOServer(port: number, opts?: ServerOptions): unknown;
395
+ /**
396
+ * Closes the subscriber connections this adapter opened, after Nest has closed every server.
397
+ *
398
+ * The caller's `pubClient` is not touched: it belongs to the caller. Each connection is quit with
399
+ * a bound, and all of them at once, so a Redis that stopped answering costs one bound and not one
400
+ * per connection.
401
+ */
402
+ dispose(): Promise<void>;
403
+ /**
404
+ * Handles the rejection of the subscriber commands the Socket.IO Redis adapter sends and never
405
+ * awaits. Its `subscribe` at boot and its `unsubscribe` at close discard their promises, so a
406
+ * command that fails, as every pending one does when the connection is closed or gives up,
407
+ * would be an unhandled rejection that ends the process.
408
+ *
409
+ * Each command still returns its own promise, so anything that awaits it sees the rejection; a
410
+ * handler is attached beside it. The failure is logged once per connection, by its class only: the
411
+ * message of a connection error can carry the host or a credential.
412
+ */
413
+ private guardCommands;
363
414
  /**
364
415
  * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
365
416
  * silent single-instance server drops cross-node messages. An unreachable Redis
@@ -1,5 +1,5 @@
1
1
  import { DynamicModule, INestApplicationContext } from '@nestjs/common';
2
- import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, IConnectionAuthenticator, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, AuthenticationResult, SseTransport } from '@bymax-one/nest-realtime/internal';
2
+ import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, AuthenticationGate, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, ConnectionAdmission, ConnectionAuthContext, AuthenticationResult, AdmissionTicket, SseTransport } from '@bymax-one/nest-realtime/internal';
3
3
  export { WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions } from '@bymax-one/nest-realtime/internal';
4
4
  import { Server, Socket, ServerOptions } from 'socket.io';
5
5
  import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
@@ -75,15 +75,16 @@ declare class WebSocketTransport implements ITransport {
75
75
  #private;
76
76
  private readonly connections;
77
77
  private readonly rooms;
78
- private readonly auth;
78
+ private readonly gate;
79
79
  private readonly hooks;
80
80
  private readonly options;
81
+ private readonly admission?;
81
82
  readonly kind: "websocket";
82
83
  private readonly logger;
83
84
  /** Nullable until the gateway's afterInit wires the instance. */
84
85
  private server;
85
86
  private warnedUnattached;
86
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, gate: AuthenticationGate, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, admission?: ConnectionAdmission | undefined);
87
88
  /**
88
89
  * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
89
90
  * nearer the root than the realtime module still runs first, and until it returns a handshake is
@@ -129,15 +130,14 @@ declare class WebSocketTransport implements ITransport {
129
130
  */
130
131
  private localSockets;
131
132
  /**
132
- * Expose the configured authenticator to the gateway.
133
+ * Authenticate a handshake through the gate both transports share: bounded in time, and in how
134
+ * many are waiting at once. The gateway calls this rather than the authenticator, which also
135
+ * avoids injecting the token in it.
133
136
  *
134
- * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
135
- * `WebSocketTransport` → authenticator, rather than injecting the token
136
- * directly in the gateway.
137
- *
138
- * @returns The consumer-provided `IConnectionAuthenticator` instance.
137
+ * @throws AuthenticationUnavailableError when too many handshakes are waiting, or this one did
138
+ * not settle in time.
139
139
  */
140
- authenticator(): IConnectionAuthenticator;
140
+ authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
141
141
  /**
142
142
  * Register a freshly-authenticated WebSocket connection.
143
143
  *
@@ -224,9 +224,16 @@ declare class WebSocketTransport implements ITransport {
224
224
  * fan-out throws: the revocation did not leave this node.
225
225
  */
226
226
  disconnect(connectionId: string, _reason?: string): Promise<void>;
227
+ /**
228
+ * Take a place for a connection before it is authenticated.
229
+ *
230
+ * @throws ConnectionLimitError when the instance already holds `maxConnections`.
231
+ */
232
+ admit(): AdmissionTicket;
227
233
  /**
228
234
  * Evict the user's oldest WebSocket connections (FIFO) when over
229
- * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
235
+ * `websocket.maxConnectionsPerUser`, which is {@link DEFAULT_MAX_CONNECTIONS_PER_USER} when
236
+ * unset and unbounded when `0`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
230
237
  * as the disconnect reason — never rejects the new connection with HTTP 429.
231
238
  */
232
239
  private evictBeyondLimit;
@@ -257,9 +264,20 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
257
264
  constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
258
265
  /** Identities the handshake middleware resolved, until `handleConnection` takes them. */
259
266
  private readonly authenticated;
267
+ /** The place held for a socket from before its handshake is authenticated until it is registered. */
268
+ private readonly tickets;
260
269
  /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
261
270
  private readonly authenticateHandshake;
262
- /** The refusal for a handshake that arrives once shutdown has begun: a `connect_error` carrying `data.code`. */
271
+ /**
272
+ * The error a handshake that failed is answered with, after the log line the failure earns.
273
+ *
274
+ * The gate and the admission count and log their own refusals once for each window; one line for
275
+ * each handshake would let an attack flood the log. The message stays generic. A refusal that is
276
+ * the instance's capacity or the authenticator's availability carries the transport code, so a
277
+ * client can retry it; any other failure is not something a client can act on and carries none.
278
+ */
279
+ private refusalFor;
280
+ /** A `connect_error` carrying `data.code` `REALTIME_TRANSPORT_UNAVAILABLE`, for a handshake the instance cannot take now. */
263
281
  private unavailable;
264
282
  /** Wire the resolved Socket.IO server to the transport after gateway init. */
265
283
  afterInit(server: Server): void;
@@ -299,6 +317,18 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
299
317
  */
300
318
  private buildAuthContext;
301
319
  handleConnection(socket: Socket): Promise<void>;
320
+ /**
321
+ * Take a place for a socket, given back when it is released or when the socket's engine connection
322
+ * closes. Several namespaces share one engine connection, so the listener is removed on release:
323
+ * left attached, every handshake that is refused would add one for as long as the connection lives.
324
+ */
325
+ private admit;
326
+ /**
327
+ * The identity of a socket and the place held for it: what the handshake middleware kept, or, for a
328
+ * socket it never saw, a fresh authentication, failing closed. Resolves to nothing for a socket that
329
+ * has been disconnected here.
330
+ */
331
+ private takeHandshake;
302
332
  /** Handle a WebSocket disconnection — unregister the connection. */
303
333
  handleDisconnect(socket: Socket): Promise<void>;
304
334
  /**
@@ -337,6 +367,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
337
367
  declare class RealtimeIoAdapter extends IoAdapter {
338
368
  private readonly adapterLogger;
339
369
  private readonly options;
370
+ /** The subscriber connections this adapter opened for the Redis adapter, closed with it. */
371
+ private readonly subscribers;
340
372
  constructor(app: INestApplicationContext);
341
373
  /**
342
374
  * Bind the gateway to `websocket.namespace` when configured.
@@ -360,6 +392,25 @@ declare class RealtimeIoAdapter extends IoAdapter {
360
392
  * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
361
393
  */
362
394
  createIOServer(port: number, opts?: ServerOptions): unknown;
395
+ /**
396
+ * Closes the subscriber connections this adapter opened, after Nest has closed every server.
397
+ *
398
+ * The caller's `pubClient` is not touched: it belongs to the caller. Each connection is quit with
399
+ * a bound, and all of them at once, so a Redis that stopped answering costs one bound and not one
400
+ * per connection.
401
+ */
402
+ dispose(): Promise<void>;
403
+ /**
404
+ * Handles the rejection of the subscriber commands the Socket.IO Redis adapter sends and never
405
+ * awaits. Its `subscribe` at boot and its `unsubscribe` at close discard their promises, so a
406
+ * command that fails, as every pending one does when the connection is closed or gives up,
407
+ * would be an unhandled rejection that ends the process.
408
+ *
409
+ * Each command still returns its own promise, so anything that awaits it sees the rejection; a
410
+ * handler is attached beside it. The failure is logged once per connection, by its class only: the
411
+ * message of a connection error can carry the host or a credential.
412
+ */
413
+ private guardCommands;
363
414
  /**
364
415
  * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
365
416
  * silent single-instance server drops cross-node messages. An unreachable Redis
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
- import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
3
- import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, assertAdmissionRooms, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
2
+ import { Injectable, Inject, Optional, Logger, Global, Module } from '@nestjs/common';
3
+ import { ConnectionRegistry, RoomRegistry, AuthenticationGate, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, ConnectionAdmission, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, runHook, DEFAULT_HOOK_TIMEOUT_MS, describeError, unavailableError, UNBOUNDED_TICKET, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, admitRooms, AuthenticationUnavailableError, ConnectionLimitError, parseCookieHeader, RESERVED_EVENT_NAMES, quitWithin, realtimeError } from '@bymax-one/nest-realtime/internal';
4
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
5
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
6
6
 
@@ -32,14 +32,16 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
32
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
33
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
34
34
  var CONNECTION_ROOM_PREFIX = "connection";
35
+ var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
35
36
  var _shuttingDown;
36
37
  var WebSocketTransport = class {
37
- constructor(connections, rooms, auth, hooks, options) {
38
+ constructor(connections, rooms, gate, hooks, options, admission) {
38
39
  this.connections = connections;
39
40
  this.rooms = rooms;
40
- this.auth = auth;
41
+ this.gate = gate;
41
42
  this.hooks = hooks;
42
43
  this.options = options;
44
+ this.admission = admission;
43
45
  __publicField(this, "kind", "websocket");
44
46
  __publicField(this, "logger", new Logger(WebSocketTransport.name));
45
47
  __publicField(this, "server", null);
@@ -48,9 +50,10 @@ var WebSocketTransport = class {
48
50
  }
49
51
  connections;
50
52
  rooms;
51
- auth;
53
+ gate;
52
54
  hooks;
53
55
  options;
56
+ admission;
54
57
  onModuleDestroy() {
55
58
  __privateSet(this, _shuttingDown, true);
56
59
  }
@@ -79,8 +82,8 @@ var WebSocketTransport = class {
79
82
  const sockets = server.sockets;
80
83
  return sockets instanceof Map ? sockets : sockets.sockets;
81
84
  }
82
- authenticator() {
83
- return this.auth;
85
+ authenticate(context) {
86
+ return this.gate.authenticate(context);
84
87
  }
85
88
  async registerSocket(socket, auth) {
86
89
  const connectedAt = /* @__PURE__ */ new Date();
@@ -110,17 +113,21 @@ var WebSocketTransport = class {
110
113
  if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
111
114
  for (const room of auth.rooms ?? []) this.rooms.join(socket.id, room);
112
115
  await this.evictBeyondLimit(auth.userId);
113
- await this.hooks.onConnect?.({
114
- connectionId: socket.id,
115
- userId: auth.userId,
116
- tenantId: auth.tenantId,
117
- roles: auth.roles,
118
- metadata: auth.metadata,
119
- transport: "websocket",
120
- ip: socket.handshake.address,
121
- userAgent: socket.handshake.headers["user-agent"],
122
- connectedAt
123
- });
116
+ const failed = await runHook(
117
+ () => this.hooks.onConnect?.({
118
+ connectionId: socket.id,
119
+ userId: auth.userId,
120
+ tenantId: auth.tenantId,
121
+ roles: auth.roles,
122
+ metadata: auth.metadata,
123
+ transport: "websocket",
124
+ ip: socket.handshake.address,
125
+ userAgent: socket.handshake.headers["user-agent"],
126
+ connectedAt
127
+ }),
128
+ this.options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
129
+ );
130
+ if (failed) this.logger.error(`onConnect hook failed: ${describeError(failed.error)}`);
124
131
  }
125
132
  async unregisterSocket(connectionId, reason) {
126
133
  const record = this.connections.unregister(connectionId);
@@ -139,7 +146,11 @@ var WebSocketTransport = class {
139
146
  durationMs: Date.now() - record.connectedAt.getTime(),
140
147
  ...reason !== void 0 ? { reason } : {}
141
148
  };
142
- await this.hooks.onDisconnect?.(disconnectMeta);
149
+ const failed = await runHook(
150
+ () => this.hooks.onDisconnect?.(disconnectMeta),
151
+ this.options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
152
+ );
153
+ if (failed) this.logger.error(`onDisconnect hook failed: ${describeError(failed.error)}`);
143
154
  }
144
155
  async emitToUser(userId, event, data) {
145
156
  this.attached("emitToUser")?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
@@ -190,9 +201,12 @@ var WebSocketTransport = class {
190
201
  );
191
202
  }
192
203
  }
204
+ admit() {
205
+ return this.admission?.admit() ?? UNBOUNDED_TICKET;
206
+ }
193
207
  async evictBeyondLimit(userId) {
194
- const max = this.options.websocket?.maxConnectionsPerUser;
195
- if (max === void 0 || max <= 0) return;
208
+ const max = this.options.websocket?.maxConnectionsPerUser ?? DEFAULT_MAX_CONNECTIONS_PER_USER;
209
+ if (max <= 0) return;
196
210
  let userConnections = this.connections.byUser(userId, "websocket");
197
211
  while (userConnections.length > max) {
198
212
  const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
@@ -207,9 +221,11 @@ WebSocketTransport = __decorateClass([
207
221
  Injectable(),
208
222
  __decorateParam(0, Inject(ConnectionRegistry)),
209
223
  __decorateParam(1, Inject(RoomRegistry)),
210
- __decorateParam(2, Inject(REALTIME_AUTHENTICATOR_TOKEN)),
224
+ __decorateParam(2, Inject(AuthenticationGate)),
211
225
  __decorateParam(3, Inject(REALTIME_HOOKS_TOKEN)),
212
- __decorateParam(4, Inject(REALTIME_OPTIONS_TOKEN))
226
+ __decorateParam(4, Inject(REALTIME_OPTIONS_TOKEN)),
227
+ __decorateParam(5, Optional()),
228
+ __decorateParam(5, Inject(ConnectionAdmission))
213
229
  ], WebSocketTransport);
214
230
 
215
231
  // src/websocket/transports/composite/composite.transport.ts
@@ -297,6 +313,7 @@ CompositeTransport = __decorateClass([
297
313
  __decorateParam(0, Inject(SseTransport)),
298
314
  __decorateParam(1, Inject(WebSocketTransport))
299
315
  ], CompositeTransport);
316
+ var ADAPTER_COMMANDS = ["subscribe", "psubscribe", "unsubscribe", "punsubscribe"];
300
317
  var realtimeServers = /* @__PURE__ */ new WeakSet();
301
318
  function isRealtimeIoServer(server) {
302
319
  return typeof server === "object" && server !== null && realtimeServers.has(server);
@@ -304,6 +321,7 @@ function isRealtimeIoServer(server) {
304
321
  var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
305
322
  adapterLogger = new Logger(_RealtimeIoAdapter.name);
306
323
  options;
324
+ subscribers = /* @__PURE__ */ new Set();
307
325
  constructor(app) {
308
326
  super(app);
309
327
  this.options = app.get(REALTIME_OPTIONS_TOKEN);
@@ -339,13 +357,47 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
339
357
  realtimeServers.add(server);
340
358
  return server;
341
359
  }
360
+ async dispose() {
361
+ await super.dispose();
362
+ const closing = [...this.subscribers].map((sub) => quitWithin(sub));
363
+ this.subscribers.clear();
364
+ await Promise.allSettled(closing);
365
+ }
366
+ guardCommands(sub) {
367
+ const commands = sub;
368
+ let reported = false;
369
+ for (const name of ADAPTER_COMMANDS) {
370
+ const original = commands[name];
371
+ if (original === void 0) continue;
372
+ commands[name] = (...args) => {
373
+ const pending = original.apply(sub, args);
374
+ Promise.resolve(pending).catch((err) => {
375
+ if (reported) return;
376
+ reported = true;
377
+ const kind = Object(err).constructor?.name ?? "Error";
378
+ this.adapterLogger.warn(`Redis adapter subscriber command failed (${kind})`);
379
+ });
380
+ return pending;
381
+ };
382
+ }
383
+ }
342
384
  installRedisAdapter(server, pubClient) {
385
+ let sub;
343
386
  try {
344
387
  const { createAdapter } = __require("@socket.io/redis-adapter");
345
388
  const pub = pubClient;
346
- const sub = pub.duplicate();
389
+ sub = pub.duplicate({ disconnectTimeout: 1 });
390
+ this.subscribers.add(sub);
391
+ this.guardCommands(sub);
347
392
  server.adapter(createAdapter(pub, sub));
348
393
  } catch (err) {
394
+ if (sub !== void 0) {
395
+ this.subscribers.delete(sub);
396
+ try {
397
+ sub.disconnect();
398
+ } catch {
399
+ }
400
+ }
349
401
  const reason = describeError(err);
350
402
  throw realtimeError(
351
403
  REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
@@ -373,13 +425,18 @@ var RealtimeGateway = class {
373
425
  logger = new Logger(RealtimeGateway.name);
374
426
  server;
375
427
  authenticated = /* @__PURE__ */ new WeakMap();
428
+ tickets = /* @__PURE__ */ new WeakMap();
376
429
  authenticateHandshake = async (socket, next) => {
430
+ let ticket;
431
+ let handedOver = false;
377
432
  try {
378
433
  if (this.transport.shuttingDown) {
379
434
  next(this.unavailable());
380
435
  return;
381
436
  }
382
- const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
437
+ const held = this.admit(socket);
438
+ ticket = held;
439
+ const auth = await this.transport.authenticate(this.buildAuthContext(socket));
383
440
  if (this.transport.shuttingDown) {
384
441
  next(this.unavailable());
385
442
  return;
@@ -392,16 +449,25 @@ var RealtimeGateway = class {
392
449
  }
393
450
  const resolvedAuth = resolveAuthTenant(this.options, auth);
394
451
  assertIdentityIsNotBlank(resolvedAuth);
395
- assertAdmissionRooms(resolvedAuth);
396
- this.authenticated.set(socket, resolvedAuth);
452
+ this.authenticated.set(socket, admitRooms(resolvedAuth));
453
+ this.tickets.set(socket, held);
454
+ handedOver = true;
397
455
  next();
398
456
  } catch (err) {
399
- this.logger.error(`handshake refused for socket ${socket.id}: ${describeError(err)}`);
400
- next(new Error("Internal Server Error"));
457
+ next(this.refusalFor(socket, err));
458
+ } finally {
459
+ if (!handedOver) ticket?.release();
401
460
  }
402
461
  };
403
- unavailable() {
404
- const refusal = new Error(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
462
+ refusalFor(socket, err) {
463
+ if (err instanceof AuthenticationUnavailableError || err instanceof ConnectionLimitError) {
464
+ return this.unavailable("Internal Server Error");
465
+ }
466
+ this.logger.error(`handshake refused for socket ${socket.id}: ${describeError(err)}`);
467
+ return new Error("Internal Server Error");
468
+ }
469
+ unavailable(message = REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE) {
470
+ const refusal = new Error(message);
405
471
  refusal.data = { code: REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE };
406
472
  return refusal;
407
473
  }
@@ -437,39 +503,69 @@ var RealtimeGateway = class {
437
503
  };
438
504
  }
439
505
  async handleConnection(socket) {
506
+ let ticket;
440
507
  try {
441
- let resolvedAuth = this.authenticated.get(socket);
442
- this.authenticated.delete(socket);
443
- if (!resolvedAuth) {
444
- if (this.transport.shuttingDown) {
445
- socket.disconnect(true);
446
- return;
447
- }
448
- const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
449
- if (!auth) {
450
- socket.disconnect(true);
451
- return;
452
- }
453
- resolvedAuth = resolveAuthTenant(this.options, auth);
454
- assertIdentityIsNotBlank(resolvedAuth);
455
- assertAdmissionRooms(resolvedAuth);
456
- }
457
- await this.transport.registerSocket(socket, resolvedAuth);
508
+ const handshake = await this.takeHandshake(socket);
509
+ if (!handshake) return;
510
+ ticket = handshake.ticket;
511
+ const { auth } = handshake;
512
+ ticket?.renew();
513
+ const registering = this.transport.registerSocket(socket, auth);
514
+ ticket?.release();
515
+ await registering;
458
516
  if (this.options.websocket?.emitConnectionEvent !== false) {
459
517
  socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
460
518
  connectionId: socket.id,
461
- traits: {
462
- userId: resolvedAuth.userId,
463
- tenantId: resolvedAuth.tenantId,
464
- roles: resolvedAuth.roles
465
- }
519
+ traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
466
520
  });
467
521
  }
468
522
  } catch (err) {
469
- this.logger.error(
470
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${describeError(err)}`
471
- );
523
+ if (!(err instanceof AuthenticationUnavailableError || err instanceof ConnectionLimitError)) {
524
+ this.logger.error(
525
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${describeError(err)}`
526
+ );
527
+ }
528
+ socket.disconnect(true);
529
+ } finally {
530
+ ticket?.release();
531
+ }
532
+ }
533
+ admit(socket) {
534
+ const held = this.transport.admit();
535
+ const onClose = () => held.release();
536
+ socket.conn.once("close", onClose);
537
+ return {
538
+ release: () => {
539
+ socket.conn.off("close", onClose);
540
+ held.release();
541
+ },
542
+ renew: () => held.renew()
543
+ };
544
+ }
545
+ async takeHandshake(socket) {
546
+ const auth = this.authenticated.get(socket);
547
+ const ticket = this.tickets.get(socket);
548
+ this.authenticated.delete(socket);
549
+ this.tickets.delete(socket);
550
+ if (auth) return { auth, ticket };
551
+ if (this.transport.shuttingDown) {
472
552
  socket.disconnect(true);
553
+ return void 0;
554
+ }
555
+ const held = this.admit(socket);
556
+ try {
557
+ const fresh = await this.transport.authenticate(this.buildAuthContext(socket));
558
+ if (!fresh) {
559
+ socket.disconnect(true);
560
+ held.release();
561
+ return void 0;
562
+ }
563
+ const resolved = resolveAuthTenant(this.options, fresh);
564
+ assertIdentityIsNotBlank(resolved);
565
+ return { auth: admitRooms(resolved), ticket: held };
566
+ } catch (err) {
567
+ held.release();
568
+ throw err;
473
569
  }
474
570
  }
475
571
  async handleDisconnect(socket) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.13",
3
+ "version": "1.2.15",
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",
@@ -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-length && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
111
+ "prepublishOnly": "pnpm verify && pnpm check:runtime",
112
112
  "release": "npm publish --provenance --access public",
113
113
  "size": "node scripts/check-size.mjs",
114
114
  "test": "jest",
@@ -118,6 +118,7 @@
118
118
  "test:e2e": "jest --config jest.e2e.config.ts",
119
119
  "test:e2e:cross-instance": "jest --config jest.e2e.cross-instance.config.ts --runInBand",
120
120
  "test:watch": "jest --watch",
121
+ "verify": "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 size && pnpm check:api",
121
122
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.server.json"
122
123
  },
123
124
  "peerDependencies": {
@@ -203,7 +204,7 @@
203
204
  "rxjs": "^7.8.0",
204
205
  "socket.io": "^4.6.2",
205
206
  "socket.io-client": "^4.0.0",
206
- "supertest": "^7.0.0",
207
+ "supertest": "^7.3.1",
207
208
  "ts-jest": "^29.4.12",
208
209
  "ts-node": "^10.9.0",
209
210
  "tslib": "^2.6.0",