@cuboapp/ws 2.0.0 → 2.0.2

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.
@@ -2,50 +2,59 @@ import { EventEmitter, uuid } from '@cuboapp/utils'
2
2
 
3
3
  import { WsMessage } from '../shared'
4
4
 
5
- import { WsClientEvent } from './constants'
5
+ import { WsClientEvent, WsClientReadyState } from './constants'
6
6
  import { WsClientConnectionOptions, WsClientHandler, WsClientOptions, WsClientRequestOptions } from './types'
7
7
 
8
8
  export * from './constants'
9
9
  export * from './types'
10
10
  export * from './utils'
11
11
 
12
+ /**
13
+ * Считать ли соединение оборванным после неудачного тика.
14
+ *
15
+ * Вынесено отдельной функцией, чтобы правило можно было проверить тестом: сам `tick` живёт внутри
16
+ * таймерного цикла, и важно здесь — КОГДА состояние переключается, а не как оно запланировано.
17
+ *
18
+ * `connected === false` означает, что была неудачная попытка ПОДКЛЮЧИТЬСЯ: ждать нечего, подключаться
19
+ * просто не к чему. Терпение нужно только живому сокету, который не успел ответить.
20
+ */
21
+ export function givesUp(connected: boolean, missedPings: number, maxMisses = 3): boolean {
22
+ if (!connected) return true
23
+ return missedPings >= Math.max(1, maxMisses)
24
+ }
25
+
26
+ type Waiting = {
27
+ socket: WebSocket
28
+ timer: ReturnType<typeof setTimeout>
29
+ resolve: (data: unknown) => void
30
+ reject: (reason: unknown) => void
31
+ }
32
+
12
33
  export class WsClient<C extends unknown = {}> {
13
34
  public id = ''
14
35
  public auth: any = {}
15
36
 
16
37
  public ee = new EventEmitter()
17
38
 
18
- constructor(private opts: WsClientOptions<C>) {
19
- // handler response
20
- this.registerHandler('response', ({ message }) => {
21
- if (message.id) {
22
- const wait = this.waitings.get(message.id)
23
-
24
- if (wait) {
25
- wait.finished = true
26
-
27
- if (message.error) {
28
- wait.reject(message.error)
29
- } else {
30
- wait.resolve(message.data)
31
- }
32
- }
33
- }
34
- })
35
- }
39
+ constructor(private opts: WsClientOptions<C>) {}
36
40
 
37
41
  private ws: WebSocket | null = null
38
42
 
39
43
  private connecting: Promise<void> | null = null
40
- private disconnecting: Promise<void> | null = null
44
+ private disposeSocket: (() => void) | null = null
45
+ private cancelConnect: (() => void) | null = null
46
+ private stopped = false
47
+ private generation = 0
41
48
 
42
49
  private handlers = new Map<string, WsClientHandler<C>>()
43
- private waitings = new Map<string, { finished: boolean; resolve: (res: any) => void; reject: (reason: any) => void }>()
50
+ private waitings = new Map<string, Waiting>()
44
51
 
45
52
  public connected = false
46
53
 
47
- private _tick: any = null
54
+ private _tick: ReturnType<typeof setTimeout> | null = null
48
55
  private reconnectAttempts = 0
56
+ /** Подряд идущие пропущенные пинги; сбрасывается любым успешным ответом. */
57
+ private missedPings = 0
49
58
 
50
59
  /**
51
60
  * Задержка перед следующей попыткой переподключения с экспоненциальным
@@ -53,7 +62,7 @@ export class WsClient<C extends unknown = {}> {
53
62
  * каждую секунду (реконнект-шторм при рестарте сервера).
54
63
  */
55
64
  private get reconnectDelay() {
56
- const base = this.opts.reconnectInterval ?? this.opts.pingInterval ?? 1000
65
+ const base = this.opts.reconnectInterval ?? 1000
57
66
  const max = this.opts.reconnectMaxInterval ?? 30_000
58
67
 
59
68
  const exp = Math.min(max, base * 2 ** Math.max(0, this.reconnectAttempts - 1))
@@ -63,40 +72,45 @@ export class WsClient<C extends unknown = {}> {
63
72
  return Math.max(base, Math.round(exp + jitter))
64
73
  }
65
74
 
66
- private async tick(opts?: WsClientConnectionOptions) {
67
- // в штатном режиме (соединение живо) следующий тик — через pingInterval
68
- let nextDelay = this.opts.pingInterval ?? 1000
69
-
70
- try {
71
- if (!this.connected) {
72
- this.reconnectAttempts++
73
-
74
- await this.connect(opts)
75
+ private clearTick() {
76
+ if (this._tick) clearTimeout(this._tick)
77
+ this._tick = null
78
+ }
75
79
 
76
- this.setConnected()
80
+ /** Retrying a closed socket is independent of the optional application heartbeat. */
81
+ private scheduleTick(generation: number, opts?: WsClientConnectionOptions) {
82
+ if (!this.opts.autoReconnect || this.stopped || generation !== this.generation) return
83
+ this.clearTick()
84
+ const delay = this.connected ? this.opts.pingInterval ?? 1000 : this.reconnectDelay
85
+ if (this.connected && delay <= 0) return
86
+ this._tick = setTimeout(() => {
87
+ this._tick = null
88
+ if (this.stopped || generation !== this.generation) return
89
+ void this.tick(generation, opts)
90
+ }, delay)
91
+ }
77
92
 
78
- // успешно подключились — сбрасываем бэкофф
79
- this.reconnectAttempts = 0
80
- } else {
81
- await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 1000 })
82
- }
83
- } catch (e) {
84
- if (this.opts?.debug) {
85
- console.error('WS client - tick error', e)
86
- }
87
- this.setDisconnected()
88
-
89
- // не дозвонились — следующая попытка с бэкоффом
90
- nextDelay = this.reconnectDelay
91
- } finally {
92
- if (this.opts?.autoReconnect) {
93
- if (this._tick) {
94
- clearTimeout(this._tick)
95
- }
93
+ private async tick(generation: number, opts?: WsClientConnectionOptions) {
94
+ if (!this.connected) {
95
+ this.reconnectAttempts++
96
+ try { await this.connect(opts) }
97
+ catch (error) { if (this.opts.debug) console.error('WS reconnect failed', error) }
98
+ return
99
+ }
96
100
 
97
- this._tick = setTimeout(() => this.tick(opts), nextDelay)
101
+ const socket = this.ws
102
+ try {
103
+ await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 5000 })
104
+ if (this.ws !== socket || generation !== this.generation) return
105
+ this.missedPings = 0
106
+ } catch (error) {
107
+ if (this.ws !== socket || generation !== this.generation) return
108
+ if (this.opts.debug) console.error('WS ping failed', error)
109
+ if (givesUp(this.connected, ++this.missedPings, this.opts.pingMaxMisses)) {
110
+ this.retireSocket()
98
111
  }
99
112
  }
113
+ this.scheduleTick(generation, opts)
100
114
  }
101
115
 
102
116
  private async getToken() {
@@ -119,102 +133,102 @@ export class WsClient<C extends unknown = {}> {
119
133
  }
120
134
  }
121
135
 
122
- public async disconnect() {
123
- if (this.disconnecting) {
124
- return this.disconnecting
136
+ private retireSocket(reason = new Error('WS disconnected')) {
137
+ const socket = this.ws
138
+ this.disposeSocket?.()
139
+ this.disposeSocket = null
140
+ this.ws = null
141
+ this.id = ''
142
+ this.auth = {}
143
+ for (const [id, waiting] of this.waitings) {
144
+ if (waiting.socket !== socket) continue
145
+ this.waitings.delete(id)
146
+ clearTimeout(waiting.timer)
147
+ waiting.reject(reason)
125
148
  }
149
+ this.setDisconnected()
150
+ try { socket?.close(1000) } catch { /* already closed */ }
151
+ }
126
152
 
127
- this.disconnecting = new Promise<void>(async (resolve, reject) => {
128
- let t = setTimeout(reject, 1000)
129
-
130
- try {
131
- this.ws?.close(1000)
132
- this.ws = null
133
-
134
- clearTimeout(t)
135
-
136
- resolve()
137
- } catch (e) {
138
- reject('WS disconnect: ' + e)
139
- } finally {
140
- this.disconnecting = null
141
- }
142
- })
143
-
144
- return this.disconnecting
153
+ public async disconnect() {
154
+ this.stopped = true
155
+ this.generation++
156
+ this.clearTick()
157
+ this.cancelConnect?.()
158
+ this.cancelConnect = null
159
+ this.connecting = null
160
+ this.retireSocket()
145
161
  }
146
162
 
147
163
  public async connect(opts?: WsClientConnectionOptions) {
148
- const timeout = opts?.timeout ?? 1000
149
-
150
- if (this.connecting) {
151
- return this.connecting
152
- }
153
-
154
- if (this.connected) {
155
- await this.disconnect().catch((e) => {})
156
- }
157
-
158
- this.connecting = new Promise<void>(async (resolve, reject) => {
159
- let t = setTimeout(() => {
160
- // закрываем зависший сокет, чтобы не плодить полуоткрытые соединения на бэке
161
- try {
162
- this.ws?.close()
163
- } catch {}
164
- this.ws = null
165
-
166
- reject()
167
- this.connecting = null
168
- }, timeout)
169
-
170
- const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
164
+ if (this.connecting) return this.connecting
165
+ this.stopped = false
166
+ const generation = ++this.generation
167
+ this.clearTick()
168
+ this.retireSocket()
169
+ const attempt = (async () => {
171
170
  const token = await this.getToken()
172
-
173
- // закрываем предыдущий (недозакрытый) сокет перед созданием нового
174
- if (this.ws) {
175
- try {
176
- this.ws.close()
177
- } catch {}
178
- this.ws = null
179
- }
180
-
181
- this.ws = new WebSocket(url, token)
182
-
183
- this.registerHandler('init', ({ message }) => {
184
- // clear timeout
185
- clearTimeout(t)
186
-
187
- try {
188
- const { id, auth } = message.data as { id: string; auth: any }
189
-
190
- this.id = id
191
- this.auth = auth
192
-
193
- resolve()
194
- } catch (e) {
195
- this.setDisconnected()
196
- reject()
197
- } finally {
198
- this.connecting = null
171
+ if (generation !== this.generation || this.stopped) throw new Error('WS connection cancelled')
172
+ const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
173
+ const socket = new WebSocket(url, token)
174
+ this.ws = socket
175
+ await new Promise<void>((resolve, reject) => {
176
+ let finished = false
177
+ const current = () => this.ws === socket && generation === this.generation && !this.stopped
178
+ const finish = (error?: Error) => {
179
+ if (finished) return
180
+ finished = true
181
+ clearTimeout(timer)
182
+ this.cancelConnect = null
183
+ if (error) {
184
+ if (current()) this.retireSocket()
185
+ reject(error)
186
+ } else resolve()
187
+ }
188
+ const timer = setTimeout(() => finish(new Error('WS connection timeout')), opts?.timeout ?? 1000)
189
+ this.cancelConnect = () => finish(new Error('WS connection cancelled'))
190
+ const onMessage = (event: MessageEvent) => {
191
+ if (!current()) return
192
+ try {
193
+ const message = JSON.parse(String(event.data)) as WsMessage
194
+ if (message.method === 'init') {
195
+ if (finished) return
196
+ const data = message.data as { id: string; auth: unknown }
197
+ this.id = data.id
198
+ this.auth = data.auth
199
+ this.reconnectAttempts = 0
200
+ this.missedPings = 0
201
+ finish()
202
+ this.setConnected()
203
+ } else void this.handleMessage(message, socket)
204
+ } catch { /* malformed frames cannot affect another connection */ }
205
+ }
206
+ const onClose = ({ code, reason, wasClean }: CloseEvent) => {
207
+ if (!current()) return
208
+ const connected = this.connected
209
+ const error = new Error(connected ? 'WS disconnected' : 'WS closed before handshake', { cause: { code, reason, wasClean } })
210
+ this.retireSocket(error)
211
+ finish(error)
212
+ if (connected) this.scheduleTick(generation, opts)
213
+ }
214
+ const onError = () => {
215
+ if (current()) finish(new Error('WS connection error'))
216
+ }
217
+ socket.addEventListener('message', onMessage)
218
+ socket.addEventListener('close', onClose)
219
+ socket.addEventListener('error', onError)
220
+ this.disposeSocket = () => {
221
+ socket.removeEventListener('message', onMessage)
222
+ socket.removeEventListener('close', onClose)
223
+ socket.removeEventListener('error', onError)
199
224
  }
200
225
  })
201
-
202
- this.ws?.addEventListener('open', () => {})
203
-
204
- this.ws?.addEventListener('message', (event: any) => {
205
- this.handleMessage(JSON.parse(event.data))
206
- })
207
-
208
- this.ws?.addEventListener('close', () => {
209
- this.setDisconnected()
210
- })
211
-
212
- this.ws?.addEventListener('error', () => {})
213
-
214
- this.tick(opts)
215
- })
216
-
217
- return this.connecting
226
+ })()
227
+ this.connecting = attempt
228
+ try { await attempt } finally {
229
+ if (this.connecting === attempt) this.connecting = null
230
+ this.scheduleTick(generation, opts)
231
+ }
218
232
  }
219
233
 
220
234
  public async registerHandler(name: string, handler: WsClientHandler<C>) {
@@ -228,48 +242,47 @@ export class WsClient<C extends unknown = {}> {
228
242
  public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<true>): Promise<T>
229
243
  public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<false>): Promise<void>
230
244
  public async request(dto: WsMessage | string, opts?: WsClientRequestOptions<boolean>) {
231
- if (!this.ws || !this.connected) {
232
- throw 'WS:request - not connected'
233
- }
234
-
235
- let message: WsMessage
236
-
237
- if (typeof dto === 'string') {
238
- message = {
239
- method: dto
240
- }
241
- } else {
242
- message = dto
245
+ const socket = this.ws
246
+ if (!socket || !this.connected || socket.readyState !== WsClientReadyState.OPEN) {
247
+ throw new Error('WS:request - not connected')
243
248
  }
244
249
 
250
+ const message = typeof dto === 'string' ? { method: dto } : dto
245
251
  const wait = typeof opts === 'boolean' ? opts : (opts?.wait ?? false)
246
- const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : (opts?.timeout ?? 1000)
247
-
248
- if (wait) {
249
- message.id = uuid()
250
-
251
- const { promise, resolve, reject } = Promise.withResolvers()
252
-
253
- const w = { finished: false, resolve, reject }
254
- this.waitings.set(message.id, w)
255
-
256
- if (timeout) {
257
- setTimeout(() => {
258
- if (!w.finished) {
259
- reject('WS request timeout: ' + JSON.stringify({ dto, opts }, null, 2))
260
- }
261
- }, timeout)
262
- }
252
+ if (!wait) return socket.send(JSON.stringify(message))
253
+
254
+ const timeout = typeof opts === 'boolean' ? 1000 : opts?.timeout ?? 1000
255
+ const id = uuid()
256
+ const { promise, resolve, reject } = Promise.withResolvers<unknown>()
257
+ const timer = setTimeout(() => {
258
+ this.waitings.delete(id)
259
+ reject(new Error('WS request timeout'))
260
+ }, Number.isFinite(timeout) && timeout > 0 ? timeout : 1000)
261
+ this.waitings.set(id, { socket, timer, resolve, reject })
262
+ try {
263
+ socket.send(JSON.stringify({ ...message, id }))
264
+ } catch (error) {
265
+ clearTimeout(timer)
266
+ this.waitings.delete(id)
267
+ reject(error)
268
+ }
263
269
 
264
- this.ws?.send(JSON.stringify(message))
270
+ return promise
271
+ }
265
272
 
266
- return promise
267
- } else {
268
- return this.ws.send(JSON.stringify(message))
273
+ private async handleMessage(message: WsMessage, socket: WebSocket) {
274
+ if (message.method === 'response') {
275
+ const id = message.id
276
+ if (!id) return
277
+ const waiting = this.waitings.get(id)
278
+ if (waiting?.socket !== socket) return
279
+ this.waitings.delete(id)
280
+ clearTimeout(waiting.timer)
281
+ if (message.error != null) waiting.reject(message.error)
282
+ else waiting.resolve(message.data)
283
+ return
269
284
  }
270
- }
271
285
 
272
- private async handleMessage(message: WsMessage) {
273
286
  const handler = this.handlers.get(message.method)
274
287
  if (handler) {
275
288
  try {
@@ -277,8 +290,8 @@ export class WsClient<C extends unknown = {}> {
277
290
 
278
291
  const data = await handler(opts as any)
279
292
 
280
- if (data !== undefined) {
281
- this.ws!.send(
293
+ if (data !== undefined && this.ws === socket) {
294
+ socket.send(
282
295
  JSON.stringify({
283
296
  ...message,
284
297
  data,
@@ -14,11 +14,21 @@ export type WsClientOptions<C extends unknown> = {
14
14
  authToken?: () => Promise<string> | string
15
15
 
16
16
  autoReconnect?: boolean
17
+ /** Interval for optional application-level pings in milliseconds. Use 0 to disable them. */
17
18
  pingInterval?: number
18
19
  pingTimeout?: number
20
+ /**
21
+ * Сколько подряд пропущенных пингов считать обрывом. По умолчанию 3.
22
+ *
23
+ * Один неотвеченный пинг — это не мёртвое соединение. Вкладка, занятая тяжёлым рендером, сборкой
24
+ * мусора или просто медленной сетью, не отвечает вовремя и при пороге в 1 промах немедленно
25
+ * объявляется отключённой: сокет пересоздаётся, CRDT переподписывается на ВСЕ сущности разом,
26
+ * бэкенд получает всплеск работы — и следующий пинг опаздывает уже из-за этого. Цикл.
27
+ */
28
+ pingMaxMisses?: number
19
29
 
20
30
  /**
21
- * Базовая задержка переподключения (мс). По умолчанию = pingInterval (1000).
31
+ * Базовая задержка переподключения (мс). По умолчанию 1000.
22
32
  * Задержка растёт экспоненциально при подряд идущих неудачных попытках.
23
33
  */
24
34
  reconnectInterval?: number
@@ -21,6 +21,8 @@ export class WsServer<C = {}> {
21
21
 
22
22
  private handlers = new Map<string, WsServerHandler<C>>()
23
23
  private waitings = new Map<string, WsServerRequestWaiting[]>()
24
+ private heartbeat?: ReturnType<typeof setInterval>
25
+ private readonly alive = new WeakMap<object, boolean>()
24
26
 
25
27
  constructor(private opts: WsServerOptions<C>) {}
26
28
 
@@ -62,8 +64,11 @@ export class WsServer<C = {}> {
62
64
  // ping-pong
63
65
  this.registerHandler('ping', () => 'pong')
64
66
 
67
+ // `noServer`: the upgrade is ours to route — `opts.upgrade` may claim it first (a relayed path);
68
+ // everything else goes through this server exactly as before, verifyClient included.
65
69
  this.ws = new WebSocketServer({
66
- server: this.httpServer.getInstance(),
70
+ noServer: true,
71
+ maxPayload: this.opts.maxPayload ?? 1024 * 1024,
67
72
  verifyClient: async (info, callback) => {
68
73
  try {
69
74
  if (this.opts?.auth?.default === true && !!this.opts?.auth?.handler) {
@@ -77,9 +82,22 @@ export class WsServer<C = {}> {
77
82
  }
78
83
  })
79
84
 
85
+ const instance = this.httpServer.getInstance()
86
+ if (!instance) throw new Error('Ws: the http server did not initialise')
87
+ instance.on('upgrade', (request, socket, head) => {
88
+ if (this.opts.upgrade?.(request, socket, head)) return
89
+ this.ws.handleUpgrade(request, socket, head, (client) => this.ws.emit('connection', client, request))
90
+ })
91
+
80
92
  this.ws.addListener('connection', (socket: WsServerSocket<C>, request: WsServerRequest<C>) => {
93
+ // Oversized/invalid frames are protocol errors, not uncaught process exceptions.
94
+ socket.on('error', () => {
95
+ if (this.opts.debug) console.error('WS: invalid or oversized incoming frame')
96
+ })
81
97
  socket.id = uuid()
82
98
  socket.auth = request.auth
99
+ this.alive.set(socket, true)
100
+ socket.on('pong', () => this.alive.set(socket, true))
83
101
 
84
102
  socket.send(
85
103
  JSON.stringify({
@@ -157,9 +175,21 @@ export class WsServer<C = {}> {
157
175
  await this.init()
158
176
 
159
177
  await this.httpServer.start()
178
+ if (!this.heartbeat) {
179
+ this.heartbeat = setInterval(() => {
180
+ for (const client of this.clients) {
181
+ if (this.alive.get(client) === false) { client.terminate(); continue }
182
+ this.alive.set(client, false)
183
+ try { client.ping() } catch { client.terminate() }
184
+ }
185
+ }, 15_000)
186
+ this.heartbeat.unref?.()
187
+ }
160
188
  }
161
189
 
162
190
  async stop() {
191
+ if (this.heartbeat) clearInterval(this.heartbeat)
192
+ this.heartbeat = undefined
163
193
  await this.httpServer.stop()
164
194
  }
165
195
 
@@ -246,21 +276,44 @@ export class WsServer<C = {}> {
246
276
  }
247
277
  }
248
278
 
279
+ /** Recheck a deferred operation immediately before its write, using the same live policy. */
280
+ public async authorizeClient(client: WsServerSocket<C>, message: WsMessage = { method: 'crdt:store' }): Promise<boolean> {
281
+ if (!this.clients.has(client) || client.readyState !== 1) return false
282
+ try { return !this.opts.authorizeMessage || !!(await this.opts.authorizeMessage(client, message)) }
283
+ catch { return false }
284
+ }
285
+
249
286
  private async handleMessage(client: WsServerSocket<C>, message: WsMessage) {
287
+ if (!(await this.authorizeClient(client, message))) {
288
+ client.close(4401, 'session ended')
289
+ return
290
+ }
250
291
  const handler = this.handlers.get(message.method)
251
292
 
252
293
  if (handler) {
253
- const data = await handler({ client, message } as any)
254
-
255
- if (data !== undefined) {
256
- client.send(
257
- JSON.stringify({
258
- ...message,
259
- data,
260
- method: 'response'
261
- })
262
- )
294
+ try {
295
+ const data = await handler({ client, message } as any)
296
+
297
+ if (data !== undefined) {
298
+ client.send(
299
+ JSON.stringify({
300
+ ...message,
301
+ data,
302
+ method: 'response'
303
+ })
304
+ )
305
+ }
306
+ } catch (error) {
307
+ if (typeof message.id !== 'string' || message.id.length > 128 || client.readyState !== 1) return
308
+ const problem = typeof error === 'object' && error !== null ? error as { status?: unknown; statusCode?: unknown; text?: unknown } : undefined
309
+ const value = problem?.status ?? problem?.statusCode
310
+ const status = typeof value === 'number' && Number.isInteger(value) && value >= 400 && value < 500 ? value : 500
311
+ const text = status === 403 && problem?.text === 'Forbidden: subscription belongs to another client'
312
+ ? 'Forbidden: subscription belongs to another client'
313
+ : ({ 400: 'Bad request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not found', 409: 'Conflict', 413: 'Request too large', 429: 'Too many requests' } as Record<number, string>)[status] ?? 'Request failed'
314
+ client.send(JSON.stringify({ method: 'response', id: message.id, error: { status, text } }))
263
315
  }
316
+
264
317
  } else if (message.method) {
265
318
  throw 'No handler defined "' + message.method + '"'
266
319
  } else {
@@ -1,3 +1,6 @@
1
+ import type { IncomingMessage } from 'node:http'
2
+ import type { Duplex } from 'node:stream'
3
+
1
4
  import { type HttpServerOptions } from '@cuboapp/http-server'
2
5
 
3
6
  import { WsMessage } from '../../../shared'
@@ -10,15 +13,26 @@ import { WsServerSocket } from '../socket'
10
13
  export type WsServerOptions<C extends unknown> = {
11
14
  host: string
12
15
  port: number
16
+ /** Maximum incoming websocket frame bytes (default 1 MiB). */
17
+ maxPayload?: number
13
18
  auth?: {
14
19
  default?: boolean
15
20
  handler?: (ctx: { server: WsServer<C>; request: WsServerRequest<C> }) => Promise<void> | void
16
21
  }
22
+ /** Revalidate a live credential before dispatching each client message; failure closes the socket. */
23
+ authorizeMessage?: (client: WsServerSocket<C>, message: WsMessage) => boolean | Promise<boolean>
17
24
  debug?: boolean
18
25
  http?: Partial<HttpServerOptions<C>>
19
26
 
20
27
  onConnect?: (socket: WsServerSocket<C>) => void | Promise<void>
21
28
  onDisconnect?: (socket: WsServerSocket<C>) => void | Promise<void>
29
+
30
+ /**
31
+ * Claim an upgrade before this server's own websocket sees it — return true and the socket is yours
32
+ * (relay it, refuse it); false and it is handled here as usual, `auth` and all. For a server that also
33
+ * relays some paths elsewhere on the same port.
34
+ */
35
+ upgrade?: (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean
22
36
  }
23
37
 
24
38
  export type WsServerHandler<C, D extends unknown = object> = (