@dokebi/websocket 0.4.1 → 0.4.3

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/dist/gateway.js CHANGED
@@ -2,10 +2,11 @@ import { isUtf8 } from 'node:buffer';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
4
4
  import { diagnostics } from '@dokebi/core/libraries';
5
- import fastifyWebsocket from '@fastify/websocket';
6
- import { WebSocket } from 'ws';
5
+ import { runBeforeHijack } from '@dokebi/web/points';
7
6
  import { WebsocketError } from './errors.js';
8
7
  import { PLAIN_PROTOCOL, SEAL_PROTOCOL, } from './types.js';
8
+ /** `WebSocket.OPEN` of ws (a constant, so ws itself loads only when a route needs it). */
9
+ const OPEN = 1;
9
10
  const TEXT = Object.freeze({ binary: false });
10
11
  const BINARY = Object.freeze({ binary: true });
11
12
  /** Close codes of sealed connections (D-0059 §4); the client does not reconnect after them. */
@@ -13,11 +14,28 @@ const BAD_FRAME = 4400;
13
14
  const SEAL_REQUIRED = 4415;
14
15
  /** Why a sealed frame was refused, as a bounded log group (codec reasons look like `replay`). */
15
16
  const REASON = /^[a-z][a-z-]{0,31}$/;
17
+ /**
18
+ * The refusals that prove a frame bad (dokebi-seal `SealReject`, and `binary` of this gateway):
19
+ * 4400. Every other failure — `capacity`, `unavailable`, or none of these — means the server
20
+ * could not check the frame (D-0075, D-0096 §2): 1013, and the client reconnects.
21
+ */
22
+ const BAD_FRAME_REASONS = new Set([
23
+ 'no-prefix',
24
+ 'plain-rejected',
25
+ 'drift',
26
+ 'replay',
27
+ 'open-failed',
28
+ 'binary',
29
+ ]);
16
30
  /** Message types of `api.send`, as defineSocket handler types. */
17
31
  const TYPE = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/;
18
- /** Hub calls a `tenantPrefix` broadcast or kick runs at once. */
19
- const FAN_OUT = 16;
20
32
  const encoder = new TextEncoder();
33
+ /**
34
+ * D-0089: the before-hijack steps (@dokebi/session's save, @dokebi/auth's cookies) run before the
35
+ * 101 (`runBeforeHijack` of @dokebi/web), so the session is saved and their Set-Cookie goes out
36
+ * with the 101.
37
+ */
38
+ const upgradeTimeout = (timeoutMs) => () => new Error(`Work before the upgrade did not finish within ${timeoutMs} ms (beforeUpgradeTimeoutMs)`);
21
39
  const { describeError, errorCode, Repeats } = diagnostics;
22
40
  /** A host without its port, lower case; IPv6 literals keep their brackets (like the browser). */
23
41
  function withoutPort(host) {
@@ -55,12 +73,54 @@ function connectionInfo(record) {
55
73
  metadata: record.metadata,
56
74
  });
57
75
  }
76
+ /**
77
+ * Whether one connection's rooms and metadata are unchanged between two hub snapshots, in order
78
+ * (what comparing their JSON says, without serializing every record of every presence event).
79
+ * The local hub hands over the same frozen record while it is unchanged.
80
+ */
81
+ function sameRoomsAndMetadata(a, b) {
82
+ if (a === b)
83
+ return true;
84
+ if (a.rooms.length !== b.rooms.length)
85
+ return false;
86
+ for (let index = 0; index < a.rooms.length; index++)
87
+ if (a.rooms[index] !== b.rooms[index])
88
+ return false;
89
+ const keys = Object.keys(a.metadata);
90
+ const other = Object.keys(b.metadata);
91
+ if (keys.length !== other.length)
92
+ return false;
93
+ for (let index = 0; index < keys.length; index++) {
94
+ const key = keys[index];
95
+ if (key !== other[index] || a.metadata[key] !== b.metadata[key])
96
+ return false;
97
+ }
98
+ return true;
99
+ }
58
100
  function sealOf(route) {
59
101
  const value = route.seal;
60
102
  if (value !== undefined && typeof value !== 'boolean' && typeof value !== 'function')
61
103
  throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
62
104
  return value;
63
105
  }
106
+ /**
107
+ * The route config (D-0140): `{ id }` only, handed to dokebi-web as the upgrade route's config.
108
+ * The id value is checked by dokebi-web at start, the same check as a web route's (one rule).
109
+ */
110
+ function configOf(route) {
111
+ const value = route.config;
112
+ if (value === undefined)
113
+ return undefined;
114
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
115
+ throw new WebsocketError('INVALID_ROUTE', "WebSocket route config is an object such as { id: 'chat' }");
116
+ const values = value;
117
+ const keys = Object.keys(values).filter((key) => values[key] !== undefined);
118
+ const other = keys.find((key) => key !== 'id');
119
+ if (other !== undefined)
120
+ throw new WebsocketError('INVALID_ROUTE', `WebSocket route config takes only id, not ${JSON.stringify(other.slice(0, 64))}`);
121
+ // Typed as the route config declares it; a value that is not a valid id fails the start.
122
+ return keys.length ? Object.freeze({ id: values.id }) : undefined;
123
+ }
64
124
  /** Allow-list entries must be exact http(s) origins such as `https://app.example.com`. */
65
125
  function parseOrigins(value) {
66
126
  if (value === undefined)
@@ -140,6 +200,7 @@ export class Gateway {
140
200
  hub;
141
201
  settings;
142
202
  codecs;
203
+ #changes = new Set();
143
204
  api;
144
205
  #routes = [];
145
206
  #clients = new Map();
@@ -154,6 +215,10 @@ export class Gateway {
154
215
  #listeners = new Set();
155
216
  /** Upgrades decided as sealed in preValidation, read by handleProtocols and the wsHandler. */
156
217
  #sealed = new WeakSet();
218
+ /** Upgrades ws answered with its 101 head (the 'headers' event); refused ones are not here. */
219
+ #upgraded = new WeakSet();
220
+ /** Replies of authenticated upgrades, read when ws writes the 101 head (their Set-Cookie). */
221
+ #replies = new WeakMap();
157
222
  #frozen = false;
158
223
  #closing = false;
159
224
  #loop;
@@ -167,7 +232,10 @@ export class Gateway {
167
232
  this.settings = settings;
168
233
  this.codecs = codecs;
169
234
  const self = this;
170
- this.#throttle = new Repeats({ logger: context.logger });
235
+ this.#throttle = new Repeats({
236
+ logger: context.logger,
237
+ intervalMs: this.settings.logRepeatWindowMs,
238
+ });
171
239
  this.api = Object.freeze({
172
240
  get connections() {
173
241
  return self.#clients.size;
@@ -176,7 +244,10 @@ export class Gateway {
176
244
  route: (route) => {
177
245
  if (this.#frozen || context.app.state !== 'starting')
178
246
  throw new WebsocketError('FROZEN', 'Register websocket routes during setup');
179
- if (!route.path.startsWith('/') ||
247
+ if (route === null ||
248
+ typeof route !== 'object' ||
249
+ typeof route.path !== 'string' ||
250
+ !route.path.startsWith('/') ||
180
251
  typeof route.authenticate !== 'function' ||
181
252
  typeof route.message !== 'function')
182
253
  throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
@@ -185,7 +256,14 @@ export class Gateway {
185
256
  // Fail closed: a route that may seal must not quietly run in plain text.
186
257
  if (seal && !codecs)
187
258
  throw new WebsocketError('SEAL_PROVIDER_MISSING', `WebSocket route ${route.path} is sealed; register the dokebi-seal plugin`);
188
- this.#routes.push({ route: { ...route }, origins });
259
+ const config = configOf(route);
260
+ const id = typeof config?.id === 'string' ? config.id : null;
261
+ this.#routes.push({ route: { ...route }, origins, config, id });
262
+ context.logger.log('debug', 'WebSocket route registered', {
263
+ path: route.path,
264
+ routeId: id,
265
+ version: route.version ?? null,
266
+ });
189
267
  },
190
268
  list: (filter) => this.#list(filter),
191
269
  broadcast: (filter, data) => this.#broadcast(filter, data),
@@ -216,12 +294,37 @@ export class Gateway {
216
294
  });
217
295
  };
218
296
  },
297
+ onChange: (listener) => {
298
+ if (typeof listener !== 'function')
299
+ throw new WebsocketError('INVALID_ARGUMENT', 'Invalid change listener');
300
+ this.#changes.add(listener);
301
+ context.logger.log('debug', 'WebSocket change listener added', {
302
+ listeners: this.#changes.size,
303
+ });
304
+ return () => {
305
+ if (this.#changes.delete(listener))
306
+ context.logger.log('debug', 'WebSocket change listener removed', {
307
+ listeners: this.#changes.size,
308
+ });
309
+ };
310
+ },
219
311
  });
220
312
  // Registered without encapsulation (skip-override) so @fastify/websocket's hooks run for
221
313
  // every upgrade, including ones that match no websocket route: its onResponse hook then
222
314
  // destroys the raw socket of a 404 upgrade instead of leaving it open (ISSUE-0005 PG-14).
223
315
  const gateway = async (scope) => {
224
316
  this.#frozen = true;
317
+ // No WebSocket route: no upgrade handling at all — @fastify/websocket and ws are not loaded
318
+ // and no hook is added (its onRequest/onResponse hooks and the one below would run on every
319
+ // HTTP request, and an onResponse hook costs each one Fastify's response listeners). An
320
+ // upgrade request is then an ordinary request (404), like on a server without this plugin.
321
+ if (this.#routes.length === 0) {
322
+ this.context.logger.log('debug', 'WebSocket upgrades not handled: no WebSocket route', {
323
+ code: 'WEBSOCKET_NO_ROUTES',
324
+ });
325
+ return;
326
+ }
327
+ const { default: fastifyWebsocket } = await import('@fastify/websocket');
225
328
  await scope.register(fastifyWebsocket, {
226
329
  options: {
227
330
  maxPayload: settings.maxPayloadBytes,
@@ -242,14 +345,67 @@ export class Gateway {
242
345
  socket.close(1011, 'Socket failure');
243
346
  },
244
347
  });
245
- for (const { route, origins } of this.#routes) {
348
+ // The upgrade hijacks the reply: ws writes the 101 head itself and no onSend hook runs.
349
+ // Set-Cookie on the reply (authenticate's hooks, a guard, the before-hijack steps of the
350
+ // upgrade's preValidation, D-0089) goes out with the 101.
351
+ scope.websocketServer.on('headers', (headers, raw) => {
352
+ this.#upgraded.add(raw);
353
+ const reply = this.#replies.get(raw);
354
+ if (!reply)
355
+ return;
356
+ this.#replies.delete(raw);
357
+ const cookies = reply.getHeader('set-cookie');
358
+ if (cookies === undefined)
359
+ return;
360
+ for (const cookie of Array.isArray(cookies) ? cookies : [String(cookies)]) {
361
+ // ws writes these lines raw: a line break would inject a header (Node refuses it too).
362
+ if (/[\r\n\0]/.test(cookie)) {
363
+ this.#throttle.log('error', 'WebSocket upgrade cookie with a line break dropped', 'UPGRADE_COOKIE_INVALID', undefined);
364
+ continue;
365
+ }
366
+ headers.push(`Set-Cookie: ${cookie}`);
367
+ }
368
+ });
369
+ // An upgrade answered with a plain response (a refusal) is never handed to ws, so its raw
370
+ // socket stays open: Node detached it for the 'upgrade' event and no HTTP server owns it.
371
+ // @fastify/websocket destroys it in its onResponse hook only when its own onRequest hook ran
372
+ // first; an earlier onRequest reply (dokebi-web's 503 while starting or draining, its
373
+ // overload refusal, a rate limit) skips that hook, and the socket was kept until the client
374
+ // closed it (a client that keeps it open held web's cleanup to its deadline). Ended here,
375
+ // after the response is out, whatever answered it.
376
+ scope.addHook('onResponse', (request, reply, done) => {
377
+ const raw = request.raw;
378
+ const socket = raw.socket;
379
+ // `upgrade` is set by Node's parser on requests that came through the 'upgrade' event.
380
+ const upgrade = raw.upgrade === true;
381
+ if (upgrade && !this.#upgraded.has(raw) && socket && !socket.destroyed) {
382
+ socket.destroy();
383
+ if (this.context.logger.isEnabled('debug'))
384
+ this.context.logger.log('debug', 'WebSocket upgrade answered without upgrading; socket ended', {
385
+ status: reply.statusCode,
386
+ url: request.url.split('?', 1)[0]?.slice(0, 200),
387
+ });
388
+ }
389
+ done();
390
+ });
391
+ for (const { route, origins, config, id } of this.#routes) {
392
+ const logger = this.context.logger;
246
393
  scope.route({
247
394
  method: 'GET',
248
395
  url: route.path,
249
396
  ...(route.constraints ? { constraints: { ...route.constraints } } : {}),
397
+ // D-0140: dokebi-web records and checks `config.id` (describe, duplicates, route hooks).
398
+ ...(config ? { config: { ...config } } : {}),
250
399
  preValidation: async (request, reply) => {
251
- if (!originAllowed(request.headers.origin, this.web.requestHost(request), origins))
400
+ if (!originAllowed(request.headers.origin, this.web.requestHost(request), origins)) {
401
+ if (logger.isEnabled('debug'))
402
+ logger.log('debug', 'WebSocket origin refused', {
403
+ path: route.path,
404
+ routeId: id,
405
+ origin: String(request.headers.origin).slice(0, 200),
406
+ });
252
407
  return reply.code(403).send({ error: 'ORIGIN_FORBIDDEN' });
408
+ }
253
409
  // A hub that is reconnecting (leader change, rolling restart) is usually back within
254
410
  // a poll interval: wait for it instead of turning the client away (bounded).
255
411
  if (!this.#closing && this.hub.state === 'recovering' && this.settings.hubWaitMs)
@@ -263,13 +419,64 @@ export class Gateway {
263
419
  ? 'CAPACITY'
264
420
  : undefined;
265
421
  if (reason) {
266
- this.context.logger.log('debug', 'WebSocket upgrade refused', { reason });
422
+ logger.log('debug', 'WebSocket upgrade refused', {
423
+ path: route.path,
424
+ routeId: id,
425
+ reason,
426
+ });
267
427
  return reply.code(503).send({ error: 'UNAVAILABLE', reason });
268
428
  }
269
429
  const identity = await route.authenticate(request);
270
- if (!identity)
430
+ if (!identity) {
431
+ if (logger.isEnabled('debug'))
432
+ logger.log('debug', 'WebSocket upgrade unauthorized', {
433
+ path: route.path,
434
+ routeId: id,
435
+ });
436
+ return reply.code(401).send({ error: 'UNAUTHORIZED' });
437
+ }
438
+ // D-0088: a lease that is already invalid is refused like a missing identity (as SSE
439
+ // does), before the upgrade, a hub registration and a presence join/leave pair.
440
+ let revoked;
441
+ try {
442
+ revoked = identity.authorization?.valid() === false;
443
+ }
444
+ catch (error) {
445
+ // As on every frame (#authorized): a lease that cannot answer is a server failure,
446
+ // logged with its code, not a 401.
447
+ this.#throttle.log('error', 'WebSocket authorization failed', 'SOCKET_AUTHORIZATION_FAILED', error, { path: route.path, routeId: id });
448
+ return reply.code(500).send({ error: 'AUTHORIZATION_FAILED' });
449
+ }
450
+ if (revoked) {
451
+ if (logger.isEnabled('debug'))
452
+ logger.log('debug', 'WebSocket upgrade refused; authorization expired', {
453
+ path: route.path,
454
+ routeId: id,
455
+ });
271
456
  return reply.code(401).send({ error: 'UNAUTHORIZED' });
457
+ }
458
+ // The upgrade hijacks the reply and no onSend hook runs: the session save and auth
459
+ // cookies happen now (D-0089), or the upgrade is refused before the 101.
460
+ const started = performance.now();
461
+ let committed;
462
+ try {
463
+ const timeoutMs = this.settings.beforeUpgradeTimeoutMs;
464
+ const waiting = runBeforeHijack(request, reply, timeoutMs, upgradeTimeout(timeoutMs));
465
+ if (waiting)
466
+ committed = await waiting;
467
+ }
468
+ catch (error) {
469
+ this.#throttle.log('error', 'WebSocket upgrade refused: saving the request state failed', 'UPGRADE_COMMIT_FAILED', error, { path: route.path });
470
+ return reply.code(500).send({ error: 'COMMIT_FAILED' });
471
+ }
472
+ if (committed !== undefined && this.context.logger.isEnabled('debug'))
473
+ this.context.logger.log('debug', 'WebSocket request state saved before the upgrade', {
474
+ path: route.path,
475
+ steps: committed,
476
+ ms: Math.round(performance.now() - started),
477
+ });
272
478
  this.#identities.set(request, identity);
479
+ this.#replies.set(request.raw, reply);
273
480
  const seal = route.seal;
274
481
  if (seal === undefined || seal === false)
275
482
  return;
@@ -298,10 +505,42 @@ export class Gateway {
298
505
  void task.then(() => this.#tasks.delete(task), () => this.#tasks.delete(task));
299
506
  return task;
300
507
  }
508
+ /**
509
+ * A send the connection's state refused (closed, authorization ended, too slow). The same
510
+ * Promise goes back to the caller, who still sees the rejection when it awaits; the handler
511
+ * here only keeps a send nobody awaits (a broadcast loop over sockets, a callback typed
512
+ * `=> void`) from ending the worker with an unhandled rejection (AI-M43: one closed browser
513
+ * tab took down the worker and every socket on it).
514
+ */
515
+ #refused(error, value) {
516
+ const refused = Promise.reject(error);
517
+ refused.catch(() => {
518
+ if (this.context.logger.isEnabled('debug'))
519
+ this.context.logger.log('debug', 'WebSocket send refused', {
520
+ connection: value.session?.id ?? null,
521
+ code: error.code,
522
+ });
523
+ });
524
+ return refused;
525
+ }
526
+ /**
527
+ * A send that could not be sealed (binary bytes, a codec failure): logged at error with its
528
+ * code like any other write failure, and the same rejected Promise goes back marked handled,
529
+ * so a send nobody awaits does not end the worker (AI-M43); an awaited one still rejects.
530
+ */
531
+ #unsent(error, value) {
532
+ this.#throttle.log('error', 'WebSocket frame not sent; not sealable', error.code, error, {
533
+ connection: value.session?.id ?? null,
534
+ });
535
+ const unsent = Promise.reject(error);
536
+ // dokebi-check: allow empty-catch the same Promise goes back to the caller; logged above
537
+ unsent.catch(() => { });
538
+ return unsent;
539
+ }
301
540
  #send(value, data) {
302
541
  const socket = value.socket;
303
- if (socket.readyState !== WebSocket.OPEN)
304
- return Promise.reject(new WebsocketError('SOCKET_CLOSED', 'Socket closed'));
542
+ if (!this.#authorized(value) || socket.readyState !== OPEN)
543
+ return this.#refused(new WebsocketError('SOCKET_CLOSED', 'Socket closed'), value);
305
544
  if (value.codec) {
306
545
  // Sealed connections carry text only: UTF-8 bytes are sent as text, other bytes refused.
307
546
  let text;
@@ -310,26 +549,91 @@ export class Gateway {
310
549
  else {
311
550
  const buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
312
551
  if (!isUtf8(buffer))
313
- return Promise.reject(new WebsocketError('SEAL_BINARY_UNSUPPORTED', 'Binary data cannot be sent on a sealed socket'));
552
+ return this.#unsent(new WebsocketError('SEAL_BINARY_UNSUPPORTED', 'Binary data cannot be sent on a sealed socket'), value);
314
553
  text = buffer.toString();
315
554
  }
316
555
  try {
317
556
  data = value.codec.encode(text);
318
557
  }
319
558
  catch (error) {
320
- return Promise.reject(new WebsocketError('SEAL_ENCODE_FAILED', 'Sealing a frame failed', { cause: error }));
559
+ return this.#unsent(new WebsocketError('SEAL_ENCODE_FAILED', 'Sealing a frame failed', { cause: error }), value);
321
560
  }
322
561
  }
562
+ if (!this.#authorized(value))
563
+ return this.#refused(new WebsocketError('SOCKET_CLOSED', 'Authorization expired'), value);
323
564
  const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
324
565
  if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
325
566
  this.#slow(socket);
326
- return Promise.reject(new WebsocketError('SLOW_CONSUMER', 'Socket backpressure'));
567
+ return this.#refused(new WebsocketError('SLOW_CONSUMER', 'Socket backpressure'), value);
327
568
  }
328
- return this.#watch(new Promise((resolve, reject) => socket.send(data, (error) => (error ? reject(error) : resolve()))));
569
+ const written = new Promise((resolve, reject) => socket.send(data, (error) => {
570
+ if (!error)
571
+ return resolve();
572
+ // The socket closed while the frame was being written: the same refusal as above.
573
+ reject(socket.readyState === OPEN
574
+ ? error
575
+ : new WebsocketError('SOCKET_CLOSED', 'Socket closed', { cause: error }));
576
+ }));
577
+ // Same Promise back to the caller; a closed socket is only noted here (see #refused), any
578
+ // other write failure is logged at error so a send nobody awaits is never lost.
579
+ written.catch((error) => {
580
+ if (error?.code === 'SOCKET_CLOSED') {
581
+ if (this.context.logger.isEnabled('debug'))
582
+ this.context.logger.log('debug', 'WebSocket send refused', {
583
+ connection: value.session?.id ?? null,
584
+ code: 'SOCKET_CLOSED',
585
+ });
586
+ return;
587
+ }
588
+ this.#throttle.log('error', 'WebSocket write failed', 'SOCKET_WRITE_FAILED', error, {
589
+ connection: value.session?.id ?? null,
590
+ });
591
+ });
592
+ return this.#watch(written);
593
+ }
594
+ #authorized(value) {
595
+ try {
596
+ if (value.failed)
597
+ return false;
598
+ if (value.session?.identity.authorization?.valid() !== false)
599
+ return true;
600
+ }
601
+ catch (error) {
602
+ this.#throttle.log('error', 'WebSocket authorization failed', 'SOCKET_AUTHORIZATION_FAILED', error);
603
+ }
604
+ this.#revoke(value);
605
+ return false;
606
+ }
607
+ /**
608
+ * The connection takes and sends nothing more and closes with 4403 (D-0088). The lease is let
609
+ * go now, not when the closing handshake ends: a client that never answers it would otherwise
610
+ * keep the subscription until the close times out.
611
+ */
612
+ #revoke(value) {
613
+ value.failed = true;
614
+ this.#releaseAuthorization(value);
615
+ value.socket.close(4403, 'Authorization expired');
616
+ }
617
+ /** Ends the connection's lease subscription once; a failing unsubscribe is logged. */
618
+ #releaseAuthorization(value) {
619
+ const unsubscribe = value.unsubscribeAuthorization;
620
+ if (!unsubscribe)
621
+ return;
622
+ value.unsubscribeAuthorization = undefined;
623
+ try {
624
+ unsubscribe();
625
+ }
626
+ catch (error) {
627
+ this.#throttle.log('error', 'WebSocket authorization unsubscribe failed', 'SOCKET_AUTHORIZATION_FAILED', error, { connection: value.session?.id });
628
+ }
629
+ if (this.context.logger.isEnabled('debug'))
630
+ this.context.logger.log('debug', 'WebSocket authorization released', {
631
+ connection: value.session?.id,
632
+ });
329
633
  }
330
634
  /** Closes a socket whose send buffer passed maxBufferedBytes (1013), logging it once. */
331
635
  #slow(socket) {
332
- if (socket.readyState !== WebSocket.OPEN)
636
+ if (socket.readyState !== OPEN)
333
637
  return;
334
638
  this.context.logger.log('warn', 'WebSocket slow consumer closed', {
335
639
  code: 'SLOW_CONSUMER',
@@ -337,9 +641,13 @@ export class Gateway {
337
641
  });
338
642
  socket.close(1013, 'Slow consumer');
339
643
  }
340
- /** Queues one broadcast frame without waiting; a slow socket never delays the others. */
341
- #deliver(socket, frame, kind) {
342
- if (socket.readyState !== WebSocket.OPEN)
644
+ /**
645
+ * Queues one broadcast frame without waiting; a slow socket never delays the others. The
646
+ * caller checked the connection's authorization for this frame (and before sealing it).
647
+ */
648
+ #deliver(value, frame, kind) {
649
+ const socket = value.socket;
650
+ if (socket.readyState !== OPEN)
343
651
  return;
344
652
  const bytes = typeof frame === 'string' ? Buffer.byteLength(frame) : frame.byteLength;
345
653
  if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
@@ -468,13 +776,19 @@ export class Gateway {
468
776
  identity,
469
777
  send: (data) => this.#send(value, data),
470
778
  broadcast: async (data, target) => {
779
+ if (!this.#authorized(value))
780
+ throw new WebsocketError('SOCKET_CLOSED', 'Authorization expired');
471
781
  return this.hub.broadcast({ ...target, tenant: identity.tenant }, data);
472
782
  },
473
783
  join: async (room) => {
784
+ if (!this.#authorized(value))
785
+ throw new WebsocketError('SOCKET_CLOSED', 'Authorization expired');
474
786
  if (!route.authorizeRoom || !(await route.authorizeRoom(identity, room))) {
475
787
  this.context.logger.log('debug', 'WebSocket room refused', { connection: id });
476
788
  throw new WebsocketError('ROOM_FORBIDDEN', 'Room access denied');
477
789
  }
790
+ if (!this.#authorized(value))
791
+ throw new WebsocketError('SOCKET_CLOSED', 'Authorization expired');
478
792
  await value.registration?.join(room);
479
793
  this.context.logger.log('debug', 'WebSocket room joined', {
480
794
  connection: id,
@@ -507,31 +821,52 @@ export class Gateway {
507
821
  },
508
822
  });
509
823
  value.session = session;
824
+ if (identity.authorization) {
825
+ // A lease that expired since the upgrade check calls the listener at once (4403). One that
826
+ // cannot be subscribed to could not be revoked later, so the connection ends now.
827
+ try {
828
+ value.unsubscribeAuthorization = identity.authorization.subscribe(() => this.#revoke(value));
829
+ }
830
+ catch (error) {
831
+ this.#throttle.log('error', 'WebSocket authorization subscription failed; closed', 'SOCKET_AUTHORIZATION_FAILED', error, { connection: id });
832
+ this.#revoke(value);
833
+ }
834
+ }
510
835
  // `namespace` belongs to @dokebi/app (D-0061); the hub registers known fields only.
511
- const { namespace: _namespace, ...fields } = identity;
836
+ const { namespace: _namespace, authorization: _authorization, ...fields } = identity;
512
837
  const registration = { ...fields, connection: id };
513
- value.tail = this.#watch(this.hub.register(registration).then((handle) => {
514
- value.registration = handle;
515
- if (this.context.logger.isEnabled('debug'))
516
- this.context.logger.log('debug', 'WebSocket registered with hub', {
517
- connection: id,
518
- ms: Math.round(performance.now() - opened),
519
- });
520
- }));
521
- const registered = value.tail;
522
- void value.tail.catch((error) => {
523
- // Converted to a close code (4409 or 1013) for the client; logged here for the operator.
524
- this.#throttle.log('warn', 'WebSocket registration failed', errorCode(error, 'REGISTRATION_FAILED'), error, { connection: id });
525
- value.failed = true;
526
- // The same (tenant, member, clientId) is already connected (D-0025): a client error, not
527
- // a hub outage. A client that retries with the same clientId is refused again.
528
- const duplicate = error?.code === 'DUPLICATE_CLIENT' ||
529
- (error instanceof Error && error.message.endsWith('DUPLICATE_CLIENT'));
530
- if (duplicate)
531
- socket.close(4409, 'Duplicate client');
532
- else
533
- socket.close(1013, 'Hub unavailable');
534
- });
838
+ // Settles once the hub answered; never rejects. A refused registration is turned into a close
839
+ // code (4409 or 1013) here and logged once, so the frames queued behind it (`tail`) and the
840
+ // cleanup at close see only `value.failed` and no registration, not the error again.
841
+ const registered = value.failed
842
+ ? Promise.resolve()
843
+ : this.#watch(this.hub.register(registration).then((handle) => {
844
+ value.registration = handle;
845
+ if (this.context.logger.isEnabled('debug'))
846
+ this.context.logger.log('debug', 'WebSocket registered with hub', {
847
+ connection: id,
848
+ ms: Math.round(performance.now() - opened),
849
+ });
850
+ }, (error) => {
851
+ // Converted to a close code (4409 or 1013) for the client; logged for the operator.
852
+ this.#throttle.log('warn', 'WebSocket registration failed', errorCode(error, 'REGISTRATION_FAILED'), error, { connection: id });
853
+ value.failed = true;
854
+ // The same (tenant, member, clientId) is already connected (D-0025): a client
855
+ // error, not a hub outage. A client that retries with the same clientId is refused
856
+ // again.
857
+ const duplicate = error?.code === 'DUPLICATE_CLIENT' ||
858
+ (error instanceof Error && error.message.endsWith('DUPLICATE_CLIENT'));
859
+ if (duplicate)
860
+ socket.close(4409, 'Duplicate client');
861
+ else
862
+ socket.close(1013, 'Hub unavailable');
863
+ }));
864
+ // Revoked while the socket attached: nothing was registered (no presence join/leave pair).
865
+ if (value.failed && this.context.logger.isEnabled('debug'))
866
+ this.context.logger.log('debug', 'WebSocket not registered; authorization expired', {
867
+ connection: id,
868
+ });
869
+ value.tail = registered;
535
870
  socket.on('pong', () => {
536
871
  value.alive = true;
537
872
  });
@@ -543,6 +878,8 @@ export class Gateway {
543
878
  });
544
879
  // Attach synchronously, before awaiting Redis/TCP registration, so early frames are queued.
545
880
  socket.on('message', (raw, isBinary) => {
881
+ if (!this.#authorized(value))
882
+ return;
546
883
  value.seen = performance.now();
547
884
  // ws hands each message its own Buffer (unmasked once, never reused): take it as it is
548
885
  // instead of copying every frame (D-0068). Fragments are joined; an ArrayBuffer is wrapped.
@@ -571,7 +908,7 @@ export class Gateway {
571
908
  }
572
909
  if (text.charCodeAt(0) === 123 && this.#control(text, id))
573
910
  return;
574
- if (value.failed || !value.registration)
911
+ if (!this.#authorized(value) || !value.registration)
575
912
  return;
576
913
  return route.message(Buffer.from(text), session);
577
914
  });
@@ -583,12 +920,14 @@ export class Gateway {
583
920
  if (this.#closing)
584
921
  return;
585
922
  this.#enqueue(value, id, () => {
586
- if (value.failed || !value.registration)
923
+ if (!this.#authorized(value) || !value.registration)
587
924
  return;
588
925
  return route.message(bytes, session);
589
926
  });
590
927
  });
591
928
  socket.once('close', (code, reason) => {
929
+ // A failing unsubscribe must not skip the cleanup below (the connection would stay counted).
930
+ this.#releaseAuthorization(value);
592
931
  this.context.logger.log('debug', 'WebSocket closed', {
593
932
  connection: id,
594
933
  member: identity.member,
@@ -620,7 +959,7 @@ export class Gateway {
620
959
  control = JSON.parse(text);
621
960
  }
622
961
  catch {
623
- /* The route owns non-control payload parsing. */
962
+ // dokebi-check: allow empty-catch a frame that is not JSON is the route's payload; the route owns its parsing
624
963
  }
625
964
  // The page is alive (idleTimeoutMs): nothing else to do.
626
965
  if (control?.$dokebi === 'ping-v1')
@@ -637,9 +976,10 @@ export class Gateway {
637
976
  * A sealed frame that did not open (plain text, binary, drift, replay, bad seal): 4400 and the
638
977
  * connection takes nothing more. The reason goes to the log only, never to the client: telling
639
978
  * `replay` from `drift` would let an attacker probe the defence (D-0059 §4).
640
- * One exception: `capacity` (the in-process nonce store is full of live nonces, D-0075) is the
641
- * server's state, not the frame's, so it closes with 1013 `Try again later` and the client
642
- * reconnects with backoff.
979
+ * The exceptions are the server's state, not the frame's, so they close with 1013 `Try again
980
+ * later` and the client reconnects with backoff: `capacity` (the in-process nonce store is full
981
+ * of live nonces, D-0075, warn), and a nonce store that failed or was too slow (`unavailable`)
982
+ * or a failure without a known reason (D-0096 §2, error with the whole cause).
643
983
  */
644
984
  #refuse(value, id, error) {
645
985
  const given = error?.reason;
@@ -650,6 +990,19 @@ export class Gateway {
650
990
  value.socket.close(1013, 'Try again later');
651
991
  return;
652
992
  }
993
+ if (reason === 'nonces-lost') {
994
+ // The nonce store lost its nonces (a Redis restart, a FLUSHALL, a new process): a frame
995
+ // stamped before that may be a replay or may not; the server cannot tell, so the client
996
+ // reconnects and seals again (seal SEAL_NONCES_LOST). The store works: not UNCHECKED.
997
+ this.#throttle.log('warn', 'WebSocket sealed frame refused: stamped before the replay nonces were lost; closed', 'SEAL_NONCES_LOST', error, { connection: id, reason }, reason);
998
+ value.socket.close(1013, 'Try again later');
999
+ return;
1000
+ }
1001
+ if (!BAD_FRAME_REASONS.has(reason)) {
1002
+ this.#throttle.log('error', 'WebSocket sealed frame not checked: replay nonce store unavailable; closed', 'SEAL_FRAME_UNCHECKED', error, { connection: id, reason }, reason);
1003
+ value.socket.close(1013, 'Try again later');
1004
+ return;
1005
+ }
653
1006
  this.#throttle.log('warn', 'WebSocket sealed frame refused; closed', 'SEAL_FRAME_REFUSED', error, { connection: id, reason }, reason);
654
1007
  value.socket.close(BAD_FRAME, 'Bad frame');
655
1008
  }
@@ -675,10 +1028,16 @@ export class Gateway {
675
1028
  // failure. A slow consumer was logged where it was closed; a client that left is
676
1029
  // counted here as warn, once per interval: the client is gone, nothing on this
677
1030
  // server failed (OPS-002 soak: thousands of these hid the real cause at error).
1031
+ // Only when it is this connection's socket that is closing (every refusal of its own
1032
+ // send closed it first: closed, slow, revoked or failed). The same codes from a send
1033
+ // to another connection (a relay that awaits a peer's `send`) are a failure of this
1034
+ // handler: the branches below would otherwise leave this socket open with `failed`
1035
+ // set, taking and sending nothing more, with nothing logged (audit R9-g11-1).
1036
+ const own = socket.readyState !== OPEN;
678
1037
  const code = error?.code;
679
- if (code === 'SLOW_CONSUMER')
1038
+ if (own && code === 'SLOW_CONSUMER')
680
1039
  return;
681
- if (code === 'SOCKET_CLOSED') {
1040
+ if (own && code === 'SOCKET_CLOSED') {
682
1041
  this.#throttle.log('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
683
1042
  return;
684
1043
  }
@@ -697,6 +1056,26 @@ export class Gateway {
697
1056
  this.#owners.set(owner, connections);
698
1057
  else
699
1058
  this.#owners.delete(owner);
1059
+ if (this.#changes.size) {
1060
+ const previous = new Map(before.map((record) => [record.connection, record]));
1061
+ const changed = new Set();
1062
+ for (const record of connections) {
1063
+ const old = previous.get(record.connection);
1064
+ if (!old || !sameRoomsAndMetadata(old, record))
1065
+ changed.add(record.tenant);
1066
+ previous.delete(record.connection);
1067
+ }
1068
+ for (const record of previous.values())
1069
+ changed.add(record.tenant);
1070
+ for (const tenant of changed)
1071
+ for (const listener of this.#changes) {
1072
+ void this.#watch(Promise.resolve()
1073
+ .then(() => listener(tenant))
1074
+ .catch((error) => {
1075
+ this.#throttle.log('error', 'WebSocket snapshot listener failed', 'SNAPSHOT_LISTENER_FAILED', error);
1076
+ }));
1077
+ }
1078
+ }
700
1079
  const peer = (record) => Object.freeze({
701
1080
  member: record.member,
702
1081
  connection: record.connection,
@@ -736,6 +1115,21 @@ export class Gateway {
736
1115
  }
737
1116
  if (this.#listeners.size)
738
1117
  this.#notify(changes);
1118
+ // One frozen change per tenant, handed to every socket of it: `presence: true` of
1119
+ // defineSocket serializes it once (D-0107 §3), not once per socket.
1120
+ const shared = new Map();
1121
+ const frozen = (tenant, change) => {
1122
+ let presence = shared.get(tenant);
1123
+ if (!presence) {
1124
+ presence = Object.freeze({
1125
+ tenant,
1126
+ joined: Object.freeze(change.joined),
1127
+ left: Object.freeze(change.left),
1128
+ });
1129
+ shared.set(tenant, presence);
1130
+ }
1131
+ return presence;
1132
+ };
739
1133
  for (const value of this.#clients.values()) {
740
1134
  const { route, session } = value;
741
1135
  const change = session && changes.get(session.identity.tenant);
@@ -745,7 +1139,7 @@ export class Gateway {
745
1139
  !change ||
746
1140
  value.failed ||
747
1141
  !value.registration ||
748
- value.socket.readyState !== WebSocket.OPEN)
1142
+ value.socket.readyState !== OPEN)
749
1143
  continue;
750
1144
  // At most maxPending presence calls wait per connection (like its messages); changes
751
1145
  // that come while that many wait are merged and handed over when a call ends.
@@ -755,16 +1149,11 @@ export class Gateway {
755
1149
  this.#throttle.log('warn', 'WebSocket presence changes merged; handler behind', 'PRESENCE_MERGED', undefined, { connection: session.id, maxPending: this.settings.maxPending });
756
1150
  continue;
757
1151
  }
758
- this.#presenceCall(value, route, session, change.joined, change.left);
1152
+ this.#presenceCall(value, route, session, frozen(session.identity.tenant, change));
759
1153
  }
760
1154
  }
761
1155
  /** Queues one presence call on the connection, in order with its messages. */
762
- #presenceCall(value, route, session, joined, left) {
763
- const presence = Object.freeze({
764
- tenant: session.identity.tenant,
765
- joined: Object.freeze([...joined]),
766
- left: Object.freeze([...left]),
767
- });
1156
+ #presenceCall(value, route, session, presence) {
768
1157
  value.presencePending++;
769
1158
  // In order with this connection's messages, like a message handler.
770
1159
  value.tail = value.tail
@@ -783,7 +1172,7 @@ export class Gateway {
783
1172
  if (!buffer)
784
1173
  return;
785
1174
  value.presenceBuffer = undefined;
786
- const open = !value.failed && value.registration && value.socket.readyState === WebSocket.OPEN;
1175
+ const open = !value.failed && value.registration && value.socket.readyState === OPEN;
787
1176
  if (this.context.logger.isEnabled('debug'))
788
1177
  this.context.logger.log('debug', open ? 'WebSocket merged presence handed over' : 'WebSocket merged presence dropped', {
789
1178
  connection: session.id,
@@ -794,7 +1183,11 @@ export class Gateway {
794
1183
  // Everything cancelled out, or the socket is closing: nothing to tell.
795
1184
  if (!open || (!buffer.joined.size && !buffer.left.size))
796
1185
  return;
797
- this.#presenceCall(value, route, session, [...buffer.joined.values()], [...buffer.left.values()]);
1186
+ this.#presenceCall(value, route, session, Object.freeze({
1187
+ tenant: session.identity.tenant,
1188
+ joined: Object.freeze([...buffer.joined.values()]),
1189
+ left: Object.freeze([...buffer.left.values()]),
1190
+ }));
798
1191
  });
799
1192
  this.#watch(value.tail);
800
1193
  }
@@ -822,12 +1215,13 @@ export class Gateway {
822
1215
  const tenants = new Set(this.#mirror(filter).map((record) => record.tenant));
823
1216
  return [...tenants].map((tenant) => ({ tenant, ...narrow }));
824
1217
  }
825
- /** Runs `call` for every query, FAN_OUT at a time; the results and failures in query order. */
1218
+ /** Runs `call` for every query, `hubFanOut` at a time; the results and failures in query order. */
826
1219
  async #fanOut(queries, call) {
827
1220
  const results = [];
828
1221
  const failures = [];
829
- for (let index = 0; index < queries.length; index += FAN_OUT) {
830
- const settled = await Promise.allSettled(queries.slice(index, index + FAN_OUT).map((query) => call(query)));
1222
+ const width = this.settings.hubFanOut;
1223
+ for (let index = 0; index < queries.length; index += width) {
1224
+ const settled = await Promise.allSettled(queries.slice(index, index + width).map((query) => call(query)));
831
1225
  for (const outcome of settled)
832
1226
  if (outcome.status === 'fulfilled')
833
1227
  results.push(outcome.value);
@@ -962,11 +1356,11 @@ export class Gateway {
962
1356
  let text;
963
1357
  for (const id of event.connections) {
964
1358
  const value = this.#clients.get(id);
965
- if (!value)
1359
+ if (!value || !this.#authorized(value))
966
1360
  continue;
967
1361
  local++;
968
1362
  if (!value.codec) {
969
- this.#deliver(value.socket, frame, kind);
1363
+ this.#deliver(value, frame, kind);
970
1364
  continue;
971
1365
  }
972
1366
  // A sealed connection carries text only: a binary broadcast is not sent to it.
@@ -985,7 +1379,7 @@ export class Gateway {
985
1379
  continue;
986
1380
  }
987
1381
  sealed++;
988
- this.#deliver(value.socket, sealedFrame, TEXT);
1382
+ this.#deliver(value, sealedFrame, TEXT);
989
1383
  }
990
1384
  if (dropped)
991
1385
  this.#throttle.log('warn', 'WebSocket binary broadcast not sent to sealed sockets', 'SEAL_BINARY_UNSUPPORTED', undefined, { id: event.id, dropped });
@@ -1017,6 +1411,27 @@ export class Gateway {
1017
1411
  heartbeatMs: this.settings.heartbeatMs,
1018
1412
  idleTimeoutMs: this.settings.idleTimeoutMs,
1019
1413
  });
1414
+ this.#heartbeat();
1415
+ }
1416
+ /**
1417
+ * D-0154: reloaded limits (maxConnections, maxPending, maxBufferedBytes, idleTimeoutMs,
1418
+ * hubWaitMs, beforeUpgradeTimeoutMs) for the next connection or message, and the ping
1419
+ * interval (the timer starts again). maxPayloadBytes is the socket server's and needs a restart.
1420
+ */
1421
+ reconfigure(next) {
1422
+ const restart = this.#timer !== undefined && next.heartbeatMs !== this.settings.heartbeatMs;
1423
+ this.settings = next;
1424
+ if (restart) {
1425
+ clearInterval(this.#timer);
1426
+ this.#heartbeat();
1427
+ }
1428
+ this.context.logger.log('debug', 'WebSocket options reloaded', {
1429
+ code: 'WEBSOCKET_RELOADED',
1430
+ heartbeatMs: next.heartbeatMs,
1431
+ maxConnections: next.maxConnections,
1432
+ });
1433
+ }
1434
+ #heartbeat() {
1020
1435
  this.#timer = setInterval(() => {
1021
1436
  const idleBefore = performance.now() - this.settings.idleTimeoutMs;
1022
1437
  for (const [id, value] of this.#clients) {