@cuboapp/ws 2.0.1 → 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,7 +2,7 @@ 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'
@@ -23,42 +23,35 @@ export function givesUp(connected: boolean, missedPings: number, maxMisses = 3):
23
23
  return missedPings >= Math.max(1, maxMisses)
24
24
  }
25
25
 
26
+ type Waiting = {
27
+ socket: WebSocket
28
+ timer: ReturnType<typeof setTimeout>
29
+ resolve: (data: unknown) => void
30
+ reject: (reason: unknown) => void
31
+ }
32
+
26
33
  export class WsClient<C extends unknown = {}> {
27
34
  public id = ''
28
35
  public auth: any = {}
29
36
 
30
37
  public ee = new EventEmitter()
31
38
 
32
- constructor(private opts: WsClientOptions<C>) {
33
- // handler response
34
- this.registerHandler('response', ({ message }) => {
35
- if (message.id) {
36
- const wait = this.waitings.get(message.id)
37
-
38
- if (wait) {
39
- wait.finished = true
40
-
41
- if (message.error) {
42
- wait.reject(message.error)
43
- } else {
44
- wait.resolve(message.data)
45
- }
46
- }
47
- }
48
- })
49
- }
39
+ constructor(private opts: WsClientOptions<C>) {}
50
40
 
51
41
  private ws: WebSocket | null = null
52
42
 
53
43
  private connecting: Promise<void> | null = null
54
- 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
55
48
 
56
49
  private handlers = new Map<string, WsClientHandler<C>>()
57
- private waitings = new Map<string, { finished: boolean; resolve: (res: any) => void; reject: (reason: any) => void }>()
50
+ private waitings = new Map<string, Waiting>()
58
51
 
59
52
  public connected = false
60
53
 
61
- private _tick: any = null
54
+ private _tick: ReturnType<typeof setTimeout> | null = null
62
55
  private reconnectAttempts = 0
63
56
  /** Подряд идущие пропущенные пинги; сбрасывается любым успешным ответом. */
64
57
  private missedPings = 0
@@ -69,7 +62,7 @@ export class WsClient<C extends unknown = {}> {
69
62
  * каждую секунду (реконнект-шторм при рестарте сервера).
70
63
  */
71
64
  private get reconnectDelay() {
72
- const base = this.opts.reconnectInterval ?? this.opts.pingInterval ?? 1000
65
+ const base = this.opts.reconnectInterval ?? 1000
73
66
  const max = this.opts.reconnectMaxInterval ?? 30_000
74
67
 
75
68
  const exp = Math.min(max, base * 2 ** Math.max(0, this.reconnectAttempts - 1))
@@ -79,56 +72,45 @@ export class WsClient<C extends unknown = {}> {
79
72
  return Math.max(base, Math.round(exp + jitter))
80
73
  }
81
74
 
82
- private async tick(opts?: WsClientConnectionOptions) {
83
- // в штатном режиме (соединение живо) следующий тик — через pingInterval
84
- let nextDelay = this.opts.pingInterval ?? 1000
85
-
86
- try {
87
- if (!this.connected) {
88
- this.reconnectAttempts++
89
-
90
- await this.connect(opts)
91
-
92
- this.setConnected()
75
+ private clearTick() {
76
+ if (this._tick) clearTimeout(this._tick)
77
+ this._tick = null
78
+ }
93
79
 
94
- // успешно подключились — сбрасываем бэкофф и счётчик промахов
95
- this.reconnectAttempts = 0
96
- this.missedPings = 0
97
- } else {
98
- await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 5000 })
99
- // ответ пришёл — соединение живо, копившиеся промахи больше ничего не значат
100
- this.missedPings = 0
101
- }
102
- } catch (e) {
103
- if (this.opts?.debug) {
104
- console.error('WS client - tick error', e)
105
- }
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
+ }
106
92
 
107
- /**
108
- * Обрыв — только после НЕСКОЛЬКИХ подряд пропущенных пингов.
109
- *
110
- * Раньше хватало одного: вкладка, занятая тяжёлым рендером или сборкой мусора, не успевала
111
- * ответить за секунду, клиент немедленно пересоздавал сокет, CRDT переподписывался на все
112
- * сущности сразу, бэкенд получал всплеск работы — и следующий пинг опаздывал уже поэтому.
113
- * Соединение при этом было полностью исправно.
114
- *
115
- * Неудачный CONNECT — другое дело: там подключаться просто не к чему, и ждать нечего.
116
- */
117
- if (this.connected) this.missedPings++
118
- if (givesUp(this.connected, this.missedPings, this.opts.pingMaxMisses)) {
119
- this.setDisconnected()
120
- // не дозвонились — следующая попытка с бэкоффом
121
- nextDelay = this.reconnectDelay
122
- }
123
- } finally {
124
- if (this.opts?.autoReconnect) {
125
- if (this._tick) {
126
- clearTimeout(this._tick)
127
- }
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
+ }
128
100
 
129
- 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()
130
111
  }
131
112
  }
113
+ this.scheduleTick(generation, opts)
132
114
  }
133
115
 
134
116
  private async getToken() {
@@ -151,102 +133,102 @@ export class WsClient<C extends unknown = {}> {
151
133
  }
152
134
  }
153
135
 
154
- public async disconnect() {
155
- if (this.disconnecting) {
156
- 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)
157
148
  }
149
+ this.setDisconnected()
150
+ try { socket?.close(1000) } catch { /* already closed */ }
151
+ }
158
152
 
159
- this.disconnecting = new Promise<void>(async (resolve, reject) => {
160
- let t = setTimeout(reject, 1000)
161
-
162
- try {
163
- this.ws?.close(1000)
164
- this.ws = null
165
-
166
- clearTimeout(t)
167
-
168
- resolve()
169
- } catch (e) {
170
- reject('WS disconnect: ' + e)
171
- } finally {
172
- this.disconnecting = null
173
- }
174
- })
175
-
176
- 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()
177
161
  }
178
162
 
179
163
  public async connect(opts?: WsClientConnectionOptions) {
180
- const timeout = opts?.timeout ?? 1000
181
-
182
- if (this.connecting) {
183
- return this.connecting
184
- }
185
-
186
- if (this.connected) {
187
- await this.disconnect().catch((e) => {})
188
- }
189
-
190
- this.connecting = new Promise<void>(async (resolve, reject) => {
191
- let t = setTimeout(() => {
192
- // закрываем зависший сокет, чтобы не плодить полуоткрытые соединения на бэке
193
- try {
194
- this.ws?.close()
195
- } catch {}
196
- this.ws = null
197
-
198
- reject()
199
- this.connecting = null
200
- }, timeout)
201
-
202
- 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 () => {
203
170
  const token = await this.getToken()
204
-
205
- // закрываем предыдущий (недозакрытый) сокет перед созданием нового
206
- if (this.ws) {
207
- try {
208
- this.ws.close()
209
- } catch {}
210
- this.ws = null
211
- }
212
-
213
- this.ws = new WebSocket(url, token)
214
-
215
- this.registerHandler('init', ({ message }) => {
216
- // clear timeout
217
- clearTimeout(t)
218
-
219
- try {
220
- const { id, auth } = message.data as { id: string; auth: any }
221
-
222
- this.id = id
223
- this.auth = auth
224
-
225
- resolve()
226
- } catch (e) {
227
- this.setDisconnected()
228
- reject()
229
- } finally {
230
- 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)
231
224
  }
232
225
  })
233
-
234
- this.ws?.addEventListener('open', () => {})
235
-
236
- this.ws?.addEventListener('message', (event: any) => {
237
- this.handleMessage(JSON.parse(event.data))
238
- })
239
-
240
- this.ws?.addEventListener('close', () => {
241
- this.setDisconnected()
242
- })
243
-
244
- this.ws?.addEventListener('error', () => {})
245
-
246
- this.tick(opts)
247
- })
248
-
249
- 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
+ }
250
232
  }
251
233
 
252
234
  public async registerHandler(name: string, handler: WsClientHandler<C>) {
@@ -260,48 +242,47 @@ export class WsClient<C extends unknown = {}> {
260
242
  public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<true>): Promise<T>
261
243
  public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<false>): Promise<void>
262
244
  public async request(dto: WsMessage | string, opts?: WsClientRequestOptions<boolean>) {
263
- if (!this.ws || !this.connected) {
264
- throw 'WS:request - not connected'
265
- }
266
-
267
- let message: WsMessage
268
-
269
- if (typeof dto === 'string') {
270
- message = {
271
- method: dto
272
- }
273
- } else {
274
- message = dto
245
+ const socket = this.ws
246
+ if (!socket || !this.connected || socket.readyState !== WsClientReadyState.OPEN) {
247
+ throw new Error('WS:request - not connected')
275
248
  }
276
249
 
250
+ const message = typeof dto === 'string' ? { method: dto } : dto
277
251
  const wait = typeof opts === 'boolean' ? opts : (opts?.wait ?? false)
278
- const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : (opts?.timeout ?? 1000)
279
-
280
- if (wait) {
281
- message.id = uuid()
282
-
283
- const { promise, resolve, reject } = Promise.withResolvers()
284
-
285
- const w = { finished: false, resolve, reject }
286
- this.waitings.set(message.id, w)
287
-
288
- if (timeout) {
289
- setTimeout(() => {
290
- if (!w.finished) {
291
- reject('WS request timeout: ' + JSON.stringify({ dto, opts }, null, 2))
292
- }
293
- }, timeout)
294
- }
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
+ }
295
269
 
296
- this.ws?.send(JSON.stringify(message))
270
+ return promise
271
+ }
297
272
 
298
- return promise
299
- } else {
300
- 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
301
284
  }
302
- }
303
285
 
304
- private async handleMessage(message: WsMessage) {
305
286
  const handler = this.handlers.get(message.method)
306
287
  if (handler) {
307
288
  try {
@@ -309,8 +290,8 @@ export class WsClient<C extends unknown = {}> {
309
290
 
310
291
  const data = await handler(opts as any)
311
292
 
312
- if (data !== undefined) {
313
- this.ws!.send(
293
+ if (data !== undefined && this.ws === socket) {
294
+ socket.send(
314
295
  JSON.stringify({
315
296
  ...message,
316
297
  data,
@@ -14,6 +14,7 @@ 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
19
20
  /**
@@ -27,7 +28,7 @@ export type WsClientOptions<C extends unknown> = {
27
28
  pingMaxMisses?: number
28
29
 
29
30
  /**
30
- * Базовая задержка переподключения (мс). По умолчанию = pingInterval (1000).
31
+ * Базовая задержка переподключения (мс). По умолчанию 1000.
31
32
  * Задержка растёт экспоненциально при подряд идущих неудачных попытках.
32
33
  */
33
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> = (