-
Notifications
You must be signed in to change notification settings - Fork 12
/
hapi-plugin-websocket.js
436 lines (381 loc) · 18.2 KB
/
hapi-plugin-websocket.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
** hapi-plugin-websocket -- HAPI plugin for seamless WebSocket integration
** Copyright (c) 2016-2023 Dr. Ralf S. Engelschall <[email protected]>
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* external dependencies */
const URI = require("urijs")
const hoek = require("@hapi/hoek")
const Boom = require("@hapi/boom")
const WS = require("ws")
const WSF = require("websocket-framed")
/* internal dependencies */
const pkg = require("./package.json")
/* the HAPI plugin registration function */
const register = async (server, pluginOptions) => {
/* determine plugin registration options */
pluginOptions = hoek.applyToDefaults({
create: function () {}
}, pluginOptions, { nullOverride: true })
/* check whether a HAPI route has WebSocket enabled */
const isRouteWebSocketEnabled = (route) => {
return (
typeof route === "object"
&& typeof route.settings === "object"
&& typeof route.settings.plugins === "object"
&& typeof route.settings.plugins.websocket !== "undefined"
)
}
/* check whether a HAPI request is WebSocket driven */
const isRequestWebSocketDriven = (request) => {
return (
typeof request === "object"
&& typeof request.plugins === "object"
&& typeof request.plugins.websocket === "object"
&& request.plugins.websocket.mode === "websocket"
)
}
/* determine the route-specific options of WebSocket-enabled route */
const fetchRouteOptions = (route) => {
let routeOptions = route.settings.plugins.websocket
if (typeof routeOptions !== "object")
routeOptions = {}
routeOptions = hoek.applyToDefaults({
only: false,
subprotocol: null,
error: function () {},
connect: function () {},
disconnect: function () {},
request: function (ctx, request, h) { return h.continue },
response: function (ctx, request, h) { return h.continue },
frame: false,
frameEncoding: "json",
frameRequest: "REQUEST",
frameResponse: "RESPONSE",
frameMessage: function () {},
autoping: 0,
initially: false
}, routeOptions, { nullOverride: true })
return routeOptions
}
/* find a particular route for an HTTP request */
const findRoute = (req) => {
let route = null
/* determine request parameters */
const url = URI.parse(req.url)
const host = typeof req.headers.host === "string" ? req.headers.host : undefined
const path = url.path
const protos = (req.headers["sec-websocket-protocol"] || "").split(/, */)
/* find a matching route */
const matched = server.match("POST", path, host)
if (matched) {
/* we accept only WebSocket-enabled ones */
if (isRouteWebSocketEnabled(matched)) {
/* optionally, we accept only the correct WebSocket subprotocol */
const routeOptions = fetchRouteOptions(matched)
if (!( routeOptions.subprotocol !== null
&& protos.indexOf(routeOptions.subprotocol) === -1)) {
/* take this route */
route = matched
}
}
}
return route
}
/* the global WebSocket server instance */
let wss = null
/* per-route timers */
const routeTimers = {}
/* perform WebSocket handling on HAPI start */
server.ext({ type: "onPostStart", method: (server) => {
/* sanity check all HAPI route definitions */
server.table().forEach((route) => {
/* for all WebSocket-enabled routes... */
if (isRouteWebSocketEnabled(route)) {
/* make sure it is defined for POST method */
if (route.method.toUpperCase() !== "POST")
throw new Error("WebSocket protocol can be enabled on POST routes only")
}
})
/* establish a WebSocket server and attach it to the
Node HTTP server underlying the HAPI server */
wss = new WS.Server({
/* the underlying HTTP server */
server: server.listener,
/* disable per-server client tracking, as we have to perform it per-route */
clientTracking: false,
/* ensure that incoming WebSocket requests have a corresponding HAPI route */
verifyClient: ({ req }, result) => {
const route = findRoute(req)
if (route)
result(true)
else
result(false, 404, "No suitable WebSocket-enabled HAPI route found")
}
})
pluginOptions.create(wss)
/* per-route peer (aka client) tracking */
const routePeers = {}
/* on WebSocket connection (actually HTTP upgrade events)... */
wss.on("connection", async (ws, req) => {
/* find the (previously already successfully matched) HAPI route */
const route = findRoute(req)
/* fetch the per-route options */
const routeOptions = fetchRouteOptions(route)
/* determine a route-specific identifier */
let routeId = `${route.method}:${route.path}`
if (route.vhost)
routeId += `:${route.vhost}`
if (routeOptions.subprotocol !== null)
routeId += `:${routeOptions.subprotocol}`
/* track the peer per-route */
if (routePeers[routeId] === undefined)
routePeers[routeId] = []
const peers = routePeers[routeId]
peers.push(ws)
/* optionally enable automatic WebSocket PING messages */
if (routeOptions.autoping > 0) {
/* lazy setup of route-specific interval timer */
if (routeTimers[routeId] === undefined) {
routeTimers[routeId] = setInterval(() => {
peers.forEach((ws) => {
if (ws.isAlive === false)
ws.terminate()
else {
ws.isAlive = false
if (ws.readyState === WS.OPEN)
ws.ping("", false)
}
})
}, routeOptions.autoping)
}
/* mark peer alive initially and on WebSocket PONG messages */
ws.isAlive = true
ws.on("pong", () => {
ws.isAlive = true
})
}
/* optionally create WebSocket-Framed context */
let wsf = null
if (routeOptions.frame === true)
wsf = new WSF(ws, routeOptions.frameEncoding)
/* provide a local context */
const ctx = {}
/* allow application to hook into WebSocket connection */
routeOptions.connect.call(ctx, { ctx, wss, ws, wsf, req, peers })
/* determine HTTP headers for simulated HTTP request:
take headers of initial HTTP upgrade request, but explicitly remove Accept-Encoding,
because it could lead HAPI to compress the payload (which we cannot post-process) */
const headers = Object.assign({}, req.headers)
delete headers["accept-encoding"]
/* optionally inject an empty initial message */
if (routeOptions.initially) {
/* inject incoming WebSocket message as a simulated HTTP request */
const response = await server.inject({
/* simulate the hard-coded POST request */
method: "POST",
/* pass-through initial HTTP request information */
url: req.url,
headers: headers,
remoteAddress: req.socket.remoteAddress,
/* provide an empty HTTP POST payload */
payload: null,
/* provide WebSocket plugin context information */
plugins: {
websocket: { mode: "websocket", ctx, wss, ws, wsf, req, peers, initially: true }
}
})
/* any HTTP redirection, client error or server error response
leads to an immediate WebSocket connection drop */
if (response.statusCode >= 300) {
const annotation = `(HAPI handler responded with HTTP status ${response.statusCode})`
if (response.statusCode < 400)
ws.close(1002, `Protocol Error ${annotation}`)
else if (response.statusCode < 500)
ws.close(1008, `Policy Violation ${annotation}`)
else
ws.close(1011, `Server Error ${annotation}`)
}
}
/* hook into WebSocket message retrieval */
if (routeOptions.frame === true) {
/* framed WebSocket communication (correlated request/reply) */
wsf.on("message", async (ev) => {
/* allow application to hook into raw WebSocket frame processing */
routeOptions.frameMessage.call(ctx, { ctx, wss, ws, wsf, req, peers }, ev.frame)
/* process frame of expected type only */
if (ev.frame.type === routeOptions.frameRequest) {
/* re-encode data as JSON as HAPI want to decode it */
const message = JSON.stringify(ev.frame.data)
/* inject incoming WebSocket message as a simulated HTTP request */
const response = await server.inject({
/* simulate the hard-coded POST request */
method: "POST",
/* pass-through initial HTTP request information */
url: req.url,
headers: headers,
remoteAddress: req.socket.remoteAddress,
/* provide WebSocket message as HTTP POST payload */
payload: message,
/* provide WebSocket plugin context information */
plugins: {
websocket: { mode: "websocket", ctx, wss, ws, wsf, req, peers }
}
})
/* transform simulated HTTP response into an outgoing WebSocket message */
if (response.statusCode !== 204 && ws.readyState === WS.OPEN) {
/* decode data from JSON as HAPI has already encoded it */
const type = routeOptions.frameResponse
const data = JSON.parse(response.payload)
/* send as framed data */
wsf.send({ type, data }, ev.frame)
}
}
})
}
else {
/* plain WebSocket communication (uncorrelated request/response) */
ws.on("message", async (message) => {
/* inject incoming WebSocket message as a simulated HTTP request */
const response = await server.inject({
/* simulate the hard-coded POST request */
method: "POST",
/* pass-through initial HTTP request information */
url: req.url,
headers: headers,
remoteAddress: req.socket.remoteAddress,
/* provide WebSocket message as HTTP POST payload */
payload: message,
/* provide WebSocket plugin context information */
plugins: {
websocket: { mode: "websocket", ctx, wss, ws, wsf, req, peers }
}
})
/* transform simulated HTTP response into an outgoing WebSocket message */
if (response.statusCode !== 204 && ws.readyState === WS.OPEN)
ws.send(response.payload)
})
}
/* hook into WebSocket disconnection */
ws.on("close", () => {
/* allow application to hook into WebSocket disconnection */
routeOptions.disconnect.call(ctx, { ctx, wss, ws, wsf, req, peers })
/* stop tracking the peer */
const idx = routePeers[routeId].indexOf(ws)
routePeers[routeId].splice(idx, 1)
})
/* allow application to hook into WebSocket error processing */
ws.on("error", (error) => {
routeOptions.error.call(ctx, { ctx, wss, ws, wsf, req, peers }, error)
})
if (routeOptions.frame === true) {
wsf.on("error", (error) => {
routeOptions.error.call(ctx, { ctx, wss, ws, wsf, req, peers }, error)
})
}
})
} })
/* perform WebSocket handling on HAPI stop */
server.ext({ type: "onPreStop", method: (server, h) => {
return new Promise((resolve /*, reject */) => {
/* stop all keepalive interval timers */
for (const routeId of Object.keys(routeTimers)) {
clearInterval(routeTimers[routeId])
delete routeTimers[routeId]
}
/* close WebSocket server instance */
if (wss !== null) {
/* trigger the WebSocket server to close everything */
wss.close(() => {
/* give WebSocket server's callback a chance to execute
(this indirectly calls our "close" subscription above) */
setTimeout(() => {
/* continue processing inside HAPI */
wss = null
resolve()
}, 0)
})
}
else
resolve()
})
} })
/* make available to HAPI request the remote WebSocket information */
server.ext({ type: "onRequest", method: (request, h) => {
if (isRequestWebSocketDriven(request)) {
/* RequestInfo's remoteAddress and remotePort use getters and are not
settable, so we have to replace them. */
Object.defineProperties(request.info, {
remoteAddress: {
value: request.plugins.websocket.req.socket.remoteAddress
},
remotePort: {
value: request.plugins.websocket.req.socket.remotePort
}
})
}
return h.continue
} })
/* allow WebSocket information to be easily retrieved */
server.decorate("request", "websocket", (request) => {
return () => {
return (isRequestWebSocketDriven(request) ?
request.plugins.websocket
: { mode: "http", ctx: null, wss: null, ws: null, wsf: null, req: null, peers: null })
}
}, { apply: true })
/* handle WebSocket exclusive routes */
server.ext({ type: "onPreAuth", method: (request, h) => {
/* if WebSocket is enabled with "only" flag on the selected route... */
if ( isRouteWebSocketEnabled(request.route)
&& request.route.settings.plugins.websocket.only === true) {
/* ...but this is not a WebSocket originated request */
if (!isRequestWebSocketDriven(request))
return Boom.badRequest("Plain HTTP request to a WebSocket-only route not allowed")
}
return h.continue
} })
/* handle request/response hooks */
server.ext({ type: "onPostAuth", method: (request, h) => {
if (isRouteWebSocketEnabled(request.route) && isRequestWebSocketDriven(request)) {
const routeOptions = fetchRouteOptions(request.route)
return routeOptions.request.call(request.plugins.websocket.ctx,
request.plugins.websocket, request, h)
}
return h.continue
} })
server.ext({ type: "onPostHandler", method: (request, h) => {
if (isRouteWebSocketEnabled(request.route) && isRequestWebSocketDriven(request)) {
const routeOptions = fetchRouteOptions(request.route)
return routeOptions.response.call(request.plugins.websocket.ctx,
request.plugins.websocket, request, h)
}
return h.continue
} })
}
/* export register function, wrapped in a plugin object */
module.exports = {
plugin: {
register: register,
pkg: pkg,
once: true
}
}