kuzzle 2.49.1 → 2.50.0-beta.4

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.
Files changed (591) hide show
  1. package/dist/bin/copy-protobuf.js +17 -0
  2. package/dist/lib/api/controllers/adminController.d.ts +51 -0
  3. package/dist/lib/api/controllers/adminController.js +191 -0
  4. package/{lib → dist/lib}/api/controllers/authController.d.ts +20 -40
  5. package/{lib → dist/lib}/api/controllers/authController.js +23 -24
  6. package/dist/lib/api/controllers/bulkController.d.ts +46 -0
  7. package/dist/lib/api/controllers/bulkController.js +132 -0
  8. package/dist/lib/api/controllers/clusterController.d.ts +6 -0
  9. package/{lib → dist/lib}/api/controllers/clusterController.js +7 -11
  10. package/dist/lib/api/controllers/collectionController.d.ts +136 -0
  11. package/dist/lib/api/controllers/collectionController.js +356 -0
  12. package/dist/lib/api/controllers/documentController.d.ts +181 -0
  13. package/dist/lib/api/controllers/documentController.js +768 -0
  14. package/dist/lib/api/controllers/index.d.ts +12 -0
  15. package/{lib → dist/lib}/api/controllers/index.js +13 -14
  16. package/dist/lib/api/controllers/indexController.d.ts +65 -0
  17. package/dist/lib/api/controllers/indexController.js +139 -0
  18. package/dist/lib/api/controllers/memoryStorageController.d.ts +8 -0
  19. package/dist/lib/api/controllers/memoryStorageController.js +867 -0
  20. package/dist/lib/api/controllers/realtimeController.d.ts +47 -0
  21. package/dist/lib/api/controllers/realtimeController.js +128 -0
  22. package/dist/lib/api/controllers/securityController.d.ts +423 -0
  23. package/dist/lib/api/controllers/securityController.js +1139 -0
  24. package/dist/lib/api/controllers/serverController.d.ts +82 -0
  25. package/dist/lib/api/controllers/serverController.js +321 -0
  26. package/dist/lib/api/documentExtractor.d.ts +9 -0
  27. package/dist/lib/api/documentExtractor.js +274 -0
  28. package/dist/lib/api/funnel.d.ts +183 -0
  29. package/dist/lib/api/funnel.js +821 -0
  30. package/dist/lib/api/httpRoutes.d.ts +17 -0
  31. package/dist/lib/api/httpRoutes.js +1496 -0
  32. package/dist/lib/api/rateLimiter.d.ts +18 -0
  33. package/dist/lib/api/rateLimiter.js +74 -0
  34. package/{lib → dist/lib}/api/request/kuzzleRequest.d.ts +2 -2
  35. package/{lib → dist/lib}/api/request/requestContext.d.ts +2 -1
  36. package/dist/lib/cluster/command.d.ts +73 -0
  37. package/dist/lib/cluster/command.js +236 -0
  38. package/dist/lib/cluster/index.d.ts +2 -0
  39. package/{lib → dist/lib}/cluster/index.js +1 -2
  40. package/dist/lib/cluster/node.d.ts +278 -0
  41. package/dist/lib/cluster/node.js +876 -0
  42. package/dist/lib/cluster/publisher.d.ts +188 -0
  43. package/dist/lib/cluster/publisher.js +347 -0
  44. package/dist/lib/cluster/subscriber.d.ts +269 -0
  45. package/dist/lib/cluster/subscriber.js +555 -0
  46. package/dist/lib/cluster/workers/IDCardRenewer.d.ts +13 -0
  47. package/dist/lib/cluster/workers/IDCardRenewer.js +120 -0
  48. package/{lib → dist/lib}/config/documentEventAliases.d.ts +1 -2
  49. package/dist/lib/config/index.d.ts +5 -0
  50. package/dist/lib/config/index.js +244 -0
  51. package/dist/lib/config/sdkCompatibility.json +9 -0
  52. package/dist/lib/core/auth/formatProcessing.d.ts +30 -0
  53. package/dist/lib/core/auth/formatProcessing.js +55 -0
  54. package/dist/lib/core/auth/passportResponse.d.ts +15 -0
  55. package/{lib → dist/lib}/core/auth/passportResponse.js +24 -30
  56. package/dist/lib/core/auth/passportWrapper.d.ts +28 -0
  57. package/dist/lib/core/auth/passportWrapper.js +126 -0
  58. package/{lib → dist/lib}/core/backend/backendConfig.js +2 -2
  59. package/{lib → dist/lib}/core/backend/backendErrors.js +9 -12
  60. package/dist/lib/core/cache/cacheEngine.d.ts +15 -0
  61. package/dist/lib/core/cache/cacheEngine.js +205 -0
  62. package/dist/lib/core/network/accessLogger.d.ts +29 -0
  63. package/dist/lib/core/network/accessLogger.js +250 -0
  64. package/dist/lib/core/network/clientConnection.d.ts +15 -0
  65. package/{lib → dist/lib}/core/network/clientConnection.js +17 -24
  66. package/dist/lib/core/network/context.d.ts +42 -0
  67. package/dist/lib/core/network/context.js +57 -0
  68. package/dist/lib/core/network/entryPoint.d.ts +62 -0
  69. package/dist/lib/core/network/entryPoint.js +261 -0
  70. package/dist/lib/core/network/httpRouter/index.d.ts +85 -0
  71. package/dist/lib/core/network/httpRouter/index.js +258 -0
  72. package/dist/lib/core/network/httpRouter/routeHandler.d.ts +46 -0
  73. package/dist/lib/core/network/httpRouter/routeHandler.js +101 -0
  74. package/dist/lib/core/network/httpRouter/routePart.d.ts +35 -0
  75. package/dist/lib/core/network/httpRouter/routePart.js +117 -0
  76. package/dist/lib/core/network/protocolManifest.d.ts +6 -0
  77. package/{lib → dist/lib}/core/network/protocolManifest.js +5 -9
  78. package/dist/lib/core/network/protocols/httpMessage.d.ts +22 -0
  79. package/dist/lib/core/network/protocols/httpMessage.js +62 -0
  80. package/dist/lib/core/network/protocols/httpwsProtocol.d.ts +171 -0
  81. package/dist/lib/core/network/protocols/httpwsProtocol.js +921 -0
  82. package/dist/lib/core/network/protocols/internalProtocol.d.ts +27 -0
  83. package/dist/lib/core/network/protocols/internalProtocol.js +82 -0
  84. package/dist/lib/core/network/protocols/mqttProtocol.d.ts +39 -0
  85. package/dist/lib/core/network/protocols/mqttProtocol.js +219 -0
  86. package/dist/lib/core/network/protocols/protocol.d.ts +26 -0
  87. package/dist/lib/core/network/protocols/protocol.js +74 -0
  88. package/dist/lib/core/network/router.d.ts +49 -0
  89. package/dist/lib/core/network/router.js +193 -0
  90. package/dist/lib/core/plugin/plugin.d.ts +56 -0
  91. package/dist/lib/core/plugin/plugin.js +282 -0
  92. package/{lib → dist/lib}/core/plugin/pluginContext.js +2 -2
  93. package/dist/lib/core/plugin/pluginManifest.d.ts +5 -0
  94. package/{lib → dist/lib}/core/plugin/pluginManifest.js +16 -27
  95. package/dist/lib/core/plugin/pluginRepository.d.ts +53 -0
  96. package/dist/lib/core/plugin/pluginRepository.js +112 -0
  97. package/dist/lib/core/plugin/pluginsManager.d.ts +190 -0
  98. package/dist/lib/core/plugin/pluginsManager.js +817 -0
  99. package/dist/lib/core/plugin/privilegedContext.d.ts +14 -0
  100. package/{lib → dist/lib}/core/plugin/privilegedContext.js +10 -14
  101. package/dist/lib/core/realtime/actionEnum.d.ts +25 -0
  102. package/{lib → dist/lib}/core/realtime/actionEnum.js +7 -10
  103. package/dist/lib/core/realtime/index.d.ts +8 -0
  104. package/{lib → dist/lib}/core/realtime/index.js +9 -13
  105. package/dist/lib/core/realtime/notification/document.d.ts +34 -0
  106. package/dist/lib/core/realtime/notification/document.js +98 -0
  107. package/dist/lib/core/realtime/notification/index.d.ts +3 -0
  108. package/{lib → dist/lib}/core/realtime/notification/index.js +4 -5
  109. package/dist/lib/core/realtime/notification/server.d.ts +17 -0
  110. package/{lib → dist/lib}/core/realtime/notification/server.js +8 -10
  111. package/dist/lib/core/realtime/notification/user.d.ts +29 -0
  112. package/dist/lib/core/realtime/notification/user.js +66 -0
  113. package/dist/lib/core/realtime/notifier.d.ts +171 -0
  114. package/dist/lib/core/realtime/notifier.js +405 -0
  115. package/dist/lib/core/security/index.d.ts +14 -0
  116. package/{lib → dist/lib}/core/security/index.js +15 -19
  117. package/dist/lib/core/security/roleRepository.d.ts +143 -0
  118. package/dist/lib/core/security/roleRepository.js +445 -0
  119. package/dist/lib/core/security/securityLoader.d.ts +24 -0
  120. package/dist/lib/core/security/securityLoader.js +125 -0
  121. package/{lib → dist/lib}/core/security/tokenRepository.js +1 -1
  122. package/dist/lib/core/security/userRepository.d.ts +81 -0
  123. package/dist/lib/core/security/userRepository.js +346 -0
  124. package/dist/lib/core/shared/abstractManifest.d.ts +27 -0
  125. package/dist/lib/core/shared/abstractManifest.js +85 -0
  126. package/dist/lib/core/shared/sdk/impersonatedSdk.d.ts +7 -0
  127. package/dist/lib/core/shared/sdk/impersonatedSdk.js +80 -0
  128. package/{lib → dist/lib}/core/shared/store.d.ts +2 -2
  129. package/dist/lib/core/statistics/statistics.d.ts +94 -0
  130. package/dist/lib/core/statistics/statistics.js +287 -0
  131. package/dist/lib/core/storage/clientAdapter.d.ts +62 -0
  132. package/dist/lib/core/storage/clientAdapter.js +756 -0
  133. package/dist/lib/core/storage/storageEngine.d.ts +13 -0
  134. package/dist/lib/core/storage/storageEngine.js +52 -0
  135. package/dist/lib/core/validation/baseType.d.ts +35 -0
  136. package/dist/lib/core/validation/baseType.js +70 -0
  137. package/dist/lib/core/validation/types/anything.d.ts +10 -0
  138. package/{lib → dist/lib}/core/validation/types/anything.js +7 -10
  139. package/dist/lib/core/validation/types/boolean.d.ts +16 -0
  140. package/{lib → dist/lib}/core/validation/types/boolean.js +18 -23
  141. package/dist/lib/core/validation/types/date.d.ts +17 -0
  142. package/dist/lib/core/validation/types/date.js +215 -0
  143. package/dist/lib/core/validation/types/email.d.ts +17 -0
  144. package/dist/lib/core/validation/types/email.js +80 -0
  145. package/dist/lib/core/validation/types/enum.d.ts +17 -0
  146. package/dist/lib/core/validation/types/enum.js +70 -0
  147. package/dist/lib/core/validation/types/geoPoint.d.ts +17 -0
  148. package/{lib → dist/lib}/core/validation/types/geoPoint.js +19 -24
  149. package/dist/lib/core/validation/types/geoShape.d.ts +31 -0
  150. package/dist/lib/core/validation/types/geoShape.js +280 -0
  151. package/dist/lib/core/validation/types/integer.d.ts +7 -0
  152. package/{lib → dist/lib}/core/validation/types/integer.js +21 -27
  153. package/dist/lib/core/validation/types/ipAddress.d.ts +17 -0
  154. package/dist/lib/core/validation/types/ipAddress.js +73 -0
  155. package/dist/lib/core/validation/types/numeric.d.ts +17 -0
  156. package/dist/lib/core/validation/types/numeric.js +84 -0
  157. package/dist/lib/core/validation/types/object.d.ts +24 -0
  158. package/dist/lib/core/validation/types/object.js +74 -0
  159. package/dist/lib/core/validation/types/string.d.ts +17 -0
  160. package/dist/lib/core/validation/types/string.js +85 -0
  161. package/dist/lib/core/validation/types/url.d.ts +17 -0
  162. package/dist/lib/core/validation/types/url.js +73 -0
  163. package/dist/lib/core/validation/validation.d.ts +113 -0
  164. package/dist/lib/core/validation/validation.js +692 -0
  165. package/dist/lib/kerror/codes/0-core.json +194 -0
  166. package/dist/lib/kerror/codes/1-services.json +351 -0
  167. package/dist/lib/kerror/codes/2-api.json +195 -0
  168. package/dist/lib/kerror/codes/3-network.json +151 -0
  169. package/dist/lib/kerror/codes/4-plugin.json +498 -0
  170. package/dist/lib/kerror/codes/5-validation.json +158 -0
  171. package/dist/lib/kerror/codes/6-protocol.json +28 -0
  172. package/dist/lib/kerror/codes/7-security.json +283 -0
  173. package/dist/lib/kerror/codes/8-cluster.json +16 -0
  174. package/dist/lib/kerror/codes/index.d.ts +24 -0
  175. package/dist/lib/kerror/codes/index.js +140 -0
  176. package/{lib → dist/lib}/kerror/index.d.ts +5 -5
  177. package/{lib → dist/lib}/kuzzle/Logger.d.ts +6 -0
  178. package/{lib → dist/lib}/kuzzle/Logger.js +26 -5
  179. package/dist/lib/kuzzle/dumpGenerator.d.ts +14 -0
  180. package/dist/lib/kuzzle/dumpGenerator.js +180 -0
  181. package/dist/lib/kuzzle/event/pipeRunner.d.ts +30 -0
  182. package/dist/lib/kuzzle/event/pipeRunner.js +119 -0
  183. package/dist/lib/kuzzle/event/waterfall.d.ts +2 -0
  184. package/dist/lib/kuzzle/event/waterfall.js +90 -0
  185. package/dist/lib/kuzzle/internalIndexHandler.d.ts +186 -0
  186. package/dist/lib/kuzzle/internalIndexHandler.js +174 -0
  187. package/{lib → dist/lib}/kuzzle/kuzzle.d.ts +6 -7
  188. package/{lib → dist/lib}/kuzzle/kuzzle.js +5 -2
  189. package/dist/lib/kuzzle/kuzzleStateEnum.d.ts +20 -0
  190. package/{lib → dist/lib}/kuzzle/kuzzleStateEnum.js +5 -8
  191. package/dist/lib/kuzzle/vault.d.ts +2 -0
  192. package/dist/lib/kuzzle/vault.js +63 -0
  193. package/dist/lib/model/security/rights.d.ts +8 -0
  194. package/{lib → dist/lib}/model/security/rights.js +4 -8
  195. package/{lib → dist/lib}/model/security/role.d.ts +1 -1
  196. package/{lib → dist/lib}/model/security/user.d.ts +1 -0
  197. package/dist/lib/model/storage/apiKey.d.ts +49 -0
  198. package/dist/lib/model/storage/apiKey.js +126 -0
  199. package/dist/lib/model/storage/baseModel.d.ts +100 -0
  200. package/dist/lib/model/storage/baseModel.js +211 -0
  201. package/dist/lib/service/cache/redis.d.ts +74 -0
  202. package/dist/lib/service/cache/redis.js +237 -0
  203. package/dist/lib/service/service.d.ts +30 -0
  204. package/dist/lib/service/service.js +74 -0
  205. package/{lib → dist/lib}/service/storage/7/elasticsearch.d.ts +2 -2
  206. package/{lib → dist/lib}/service/storage/7/elasticsearch.js +23 -25
  207. package/dist/lib/service/storage/7/esWrapper.d.ts +19 -0
  208. package/dist/lib/service/storage/7/esWrapper.js +245 -0
  209. package/{lib → dist/lib}/service/storage/8/elasticsearch.js +23 -25
  210. package/dist/lib/service/storage/8/esWrapper.d.ts +19 -0
  211. package/dist/lib/service/storage/8/esWrapper.js +245 -0
  212. package/{lib → dist/lib}/types/Plugin.d.ts +1 -1
  213. package/{lib/types → dist/lib/types/controllers}/Controller.d.ts +2 -2
  214. package/{lib/types → dist/lib/types/controllers}/ControllerDefinition.d.ts +1 -1
  215. package/dist/lib/types/controllers/adminControlller.type.d.ts +5 -0
  216. package/dist/lib/types/controllers/adminControlller.type.js +3 -0
  217. package/dist/lib/types/controllers/authController.type.d.ts +5 -0
  218. package/dist/lib/types/controllers/authController.type.js +3 -0
  219. package/dist/lib/types/core/auth/formatProcessing.type.d.ts +7 -0
  220. package/dist/lib/types/core/auth/formatProcessing.type.js +3 -0
  221. package/{lib → dist/lib}/types/index.d.ts +3 -3
  222. package/{lib → dist/lib}/types/index.js +3 -3
  223. package/dist/lib/util/assertType.d.ts +41 -0
  224. package/{lib → dist/lib}/util/assertType.js +38 -56
  225. package/dist/lib/util/asyncStore.d.ts +38 -0
  226. package/dist/lib/util/asyncStore.js +70 -0
  227. package/dist/lib/util/bytes.d.ts +2 -0
  228. package/dist/lib/util/bytes.js +33 -0
  229. package/dist/lib/util/debug.d.ts +2 -0
  230. package/{lib → dist/lib}/util/debug.js +15 -23
  231. package/dist/lib/util/deprecate.d.ts +1 -0
  232. package/dist/lib/util/deprecate.js +64 -0
  233. package/dist/lib/util/didYouMean.d.ts +2 -0
  234. package/{lib → dist/lib}/util/didYouMean.js +9 -15
  235. package/dist/lib/util/extractFields.d.ts +17 -0
  236. package/{lib → dist/lib}/util/extractFields.js +18 -32
  237. package/dist/lib/util/memoize.d.ts +7 -0
  238. package/{lib → dist/lib}/util/memoize.js +14 -21
  239. package/dist/lib/util/promback.d.ts +13 -0
  240. package/dist/lib/util/promback.js +60 -0
  241. package/dist/lib/util/requestAssertions.d.ts +10 -0
  242. package/dist/lib/util/requestAssertions.js +143 -0
  243. package/dist/lib/util/safeObject.d.ts +3 -0
  244. package/{lib → dist/lib}/util/safeObject.js +7 -13
  245. package/dist/lib/util/stackTrace.d.ts +19 -0
  246. package/{lib → dist/lib}/util/stackTrace.js +35 -41
  247. package/dist/lib/util/wildcard.d.ts +1 -0
  248. package/{lib → dist/lib}/util/wildcard.js +21 -30
  249. package/dist/package.json +119 -0
  250. package/package.json +44 -58
  251. package/bin/start-kuzzle-server +0 -126
  252. package/check-node-version.js +0 -17
  253. package/lib/api/controllers/adminController.js +0 -229
  254. package/lib/api/controllers/bulkController.js +0 -210
  255. package/lib/api/controllers/collectionController.js +0 -502
  256. package/lib/api/controllers/documentController.js +0 -1156
  257. package/lib/api/controllers/indexController.js +0 -179
  258. package/lib/api/controllers/memoryStorageController.js +0 -1023
  259. package/lib/api/controllers/realtimeController.js +0 -155
  260. package/lib/api/controllers/securityController.js +0 -1571
  261. package/lib/api/controllers/serverController.js +0 -381
  262. package/lib/api/documentExtractor.js +0 -309
  263. package/lib/api/funnel.js +0 -1143
  264. package/lib/api/httpRoutes.js +0 -1547
  265. package/lib/api/rateLimiter.js +0 -87
  266. package/lib/cluster/command.js +0 -284
  267. package/lib/cluster/node.js +0 -1203
  268. package/lib/cluster/publisher.js +0 -386
  269. package/lib/cluster/subscriber.js +0 -776
  270. package/lib/cluster/workers/IDCardRenewer.js +0 -144
  271. package/lib/config/index.js +0 -351
  272. package/lib/config/sdkCompatibility.json +0 -9
  273. package/lib/core/auth/formatProcessing.js +0 -66
  274. package/lib/core/auth/passportWrapper.js +0 -126
  275. package/lib/core/cache/cacheEngine.js +0 -278
  276. package/lib/core/network/accessLogger.js +0 -322
  277. package/lib/core/network/context.js +0 -80
  278. package/lib/core/network/entryPoint.js +0 -358
  279. package/lib/core/network/httpRouter/index.js +0 -316
  280. package/lib/core/network/httpRouter/routeHandler.js +0 -111
  281. package/lib/core/network/httpRouter/routePart.js +0 -147
  282. package/lib/core/network/protocols/httpMessage.js +0 -69
  283. package/lib/core/network/protocols/httpwsProtocol.js +0 -1254
  284. package/lib/core/network/protocols/internalProtocol.js +0 -109
  285. package/lib/core/network/protocols/mqttProtocol.js +0 -291
  286. package/lib/core/network/protocols/protocol.js +0 -102
  287. package/lib/core/network/router.js +0 -255
  288. package/lib/core/plugin/plugin.js +0 -436
  289. package/lib/core/plugin/pluginRepository.js +0 -132
  290. package/lib/core/plugin/pluginsManager.js +0 -1244
  291. package/lib/core/realtime/notification/document.js +0 -108
  292. package/lib/core/realtime/notification/user.js +0 -70
  293. package/lib/core/realtime/notifier.js +0 -541
  294. package/lib/core/security/README.md +0 -223
  295. package/lib/core/security/roleRepository.js +0 -569
  296. package/lib/core/security/securityLoader.js +0 -174
  297. package/lib/core/security/userRepository.js +0 -446
  298. package/lib/core/shared/README.md +0 -3
  299. package/lib/core/shared/abstractManifest.js +0 -102
  300. package/lib/core/shared/sdk/impersonatedSdk.js +0 -94
  301. package/lib/core/statistics/index.js +0 -24
  302. package/lib/core/statistics/statistics.js +0 -373
  303. package/lib/core/storage/clientAdapter.js +0 -1045
  304. package/lib/core/storage/storageEngine.js +0 -63
  305. package/lib/core/validation/baseType.js +0 -80
  306. package/lib/core/validation/index.js +0 -24
  307. package/lib/core/validation/types/date.js +0 -284
  308. package/lib/core/validation/types/email.js +0 -92
  309. package/lib/core/validation/types/enum.js +0 -100
  310. package/lib/core/validation/types/geoShape.js +0 -370
  311. package/lib/core/validation/types/ipAddress.js +0 -83
  312. package/lib/core/validation/types/numeric.js +0 -108
  313. package/lib/core/validation/types/object.js +0 -88
  314. package/lib/core/validation/types/string.js +0 -110
  315. package/lib/core/validation/types/url.js +0 -83
  316. package/lib/core/validation/validation.js +0 -1180
  317. package/lib/kerror/codes/0-core.json +0 -194
  318. package/lib/kerror/codes/1-services.json +0 -351
  319. package/lib/kerror/codes/2-api.json +0 -195
  320. package/lib/kerror/codes/3-network.json +0 -151
  321. package/lib/kerror/codes/4-plugin.json +0 -498
  322. package/lib/kerror/codes/5-validation.json +0 -158
  323. package/lib/kerror/codes/6-protocol.json +0 -28
  324. package/lib/kerror/codes/7-security.json +0 -283
  325. package/lib/kerror/codes/8-cluster.json +0 -16
  326. package/lib/kerror/codes/index.js +0 -208
  327. package/lib/kuzzle/dumpGenerator.js +0 -259
  328. package/lib/kuzzle/event/pipeRunner.js +0 -144
  329. package/lib/kuzzle/event/waterfall.js +0 -101
  330. package/lib/kuzzle/internalIndexHandler.js +0 -234
  331. package/lib/kuzzle/vault.js +0 -89
  332. package/lib/model/storage/apiKey.js +0 -158
  333. package/lib/model/storage/baseModel.js +0 -275
  334. package/lib/service/cache/redis.js +0 -282
  335. package/lib/service/service.js +0 -84
  336. package/lib/service/storage/7/esWrapper.js +0 -303
  337. package/lib/service/storage/8/esWrapper.js +0 -303
  338. package/lib/util/asyncStore.js +0 -112
  339. package/lib/util/bytes.js +0 -36
  340. package/lib/util/deprecate.js +0 -82
  341. package/lib/util/promback.js +0 -66
  342. package/lib/util/readYamlFile.d.ts +0 -2
  343. package/lib/util/readYamlFile.js +0 -10
  344. package/lib/util/requestAssertions.js +0 -157
  345. /package/{index.d.ts → dist/index.d.ts} +0 -0
  346. /package/{index.js → dist/index.js} +0 -0
  347. /package/{lib → dist/lib}/api/controllers/baseController.d.ts +0 -0
  348. /package/{lib → dist/lib}/api/controllers/baseController.js +0 -0
  349. /package/{lib → dist/lib}/api/controllers/debugController.d.ts +0 -0
  350. /package/{lib → dist/lib}/api/controllers/debugController.js +0 -0
  351. /package/{lib → dist/lib}/api/openapi/OpenApiManager.d.ts +0 -0
  352. /package/{lib → dist/lib}/api/openapi/OpenApiManager.js +0 -0
  353. /package/{lib → dist/lib}/api/openapi/index.d.ts +0 -0
  354. /package/{lib → dist/lib}/api/openapi/index.js +0 -0
  355. /package/{lib → dist/lib}/api/openapi/openApiGenerator.d.ts +0 -0
  356. /package/{lib → dist/lib}/api/openapi/openApiGenerator.js +0 -0
  357. /package/{lib → dist/lib}/api/request/index.d.ts +0 -0
  358. /package/{lib → dist/lib}/api/request/index.js +0 -0
  359. /package/{lib → dist/lib}/api/request/kuzzleRequest.js +0 -0
  360. /package/{lib → dist/lib}/api/request/requestContext.js +0 -0
  361. /package/{lib → dist/lib}/api/request/requestInput.d.ts +0 -0
  362. /package/{lib → dist/lib}/api/request/requestInput.js +0 -0
  363. /package/{lib → dist/lib}/api/request/requestResponse.d.ts +0 -0
  364. /package/{lib → dist/lib}/api/request/requestResponse.js +0 -0
  365. /package/{lib → dist/lib}/cluster/idCardHandler.d.ts +0 -0
  366. /package/{lib → dist/lib}/cluster/idCardHandler.js +0 -0
  367. /package/{lib → dist/lib}/cluster/protobuf/command.proto +0 -0
  368. /package/{lib → dist/lib}/cluster/protobuf/sync.proto +0 -0
  369. /package/{lib → dist/lib}/cluster/state.d.ts +0 -0
  370. /package/{lib → dist/lib}/cluster/state.js +0 -0
  371. /package/{lib → dist/lib}/config/default.config.d.ts +0 -0
  372. /package/{lib → dist/lib}/config/default.config.js +0 -0
  373. /package/{lib → dist/lib}/config/documentEventAliases.js +0 -0
  374. /package/{lib → dist/lib}/core/auth/tokenManager.d.ts +0 -0
  375. /package/{lib → dist/lib}/core/auth/tokenManager.js +0 -0
  376. /package/{lib → dist/lib}/core/backend/applicationManager.d.ts +0 -0
  377. /package/{lib → dist/lib}/core/backend/applicationManager.js +0 -0
  378. /package/{lib → dist/lib}/core/backend/backend.d.ts +0 -0
  379. /package/{lib → dist/lib}/core/backend/backend.js +0 -0
  380. /package/{lib → dist/lib}/core/backend/backendCluster.d.ts +0 -0
  381. /package/{lib → dist/lib}/core/backend/backendCluster.js +0 -0
  382. /package/{lib → dist/lib}/core/backend/backendConfig.d.ts +0 -0
  383. /package/{lib → dist/lib}/core/backend/backendController.d.ts +0 -0
  384. /package/{lib → dist/lib}/core/backend/backendController.js +0 -0
  385. /package/{lib → dist/lib}/core/backend/backendErrors.d.ts +0 -0
  386. /package/{lib → dist/lib}/core/backend/backendHook.d.ts +0 -0
  387. /package/{lib → dist/lib}/core/backend/backendHook.js +0 -0
  388. /package/{lib → dist/lib}/core/backend/backendImport.d.ts +0 -0
  389. /package/{lib → dist/lib}/core/backend/backendImport.js +0 -0
  390. /package/{lib → dist/lib}/core/backend/backendOpenApi.d.ts +0 -0
  391. /package/{lib → dist/lib}/core/backend/backendOpenApi.js +0 -0
  392. /package/{lib → dist/lib}/core/backend/backendPipe.d.ts +0 -0
  393. /package/{lib → dist/lib}/core/backend/backendPipe.js +0 -0
  394. /package/{lib → dist/lib}/core/backend/backendPlugin.d.ts +0 -0
  395. /package/{lib → dist/lib}/core/backend/backendPlugin.js +0 -0
  396. /package/{lib → dist/lib}/core/backend/backendStorage.d.ts +0 -0
  397. /package/{lib → dist/lib}/core/backend/backendStorage.js +0 -0
  398. /package/{lib → dist/lib}/core/backend/backendSubscription.d.ts +0 -0
  399. /package/{lib → dist/lib}/core/backend/backendSubscription.js +0 -0
  400. /package/{lib → dist/lib}/core/backend/backendVault.d.ts +0 -0
  401. /package/{lib → dist/lib}/core/backend/backendVault.js +0 -0
  402. /package/{lib → dist/lib}/core/backend/index.d.ts +0 -0
  403. /package/{lib → dist/lib}/core/backend/index.js +0 -0
  404. /package/{lib → dist/lib}/core/backend/internalLogger.d.ts +0 -0
  405. /package/{lib → dist/lib}/core/backend/internalLogger.js +0 -0
  406. /package/{lib → dist/lib}/core/cache/cacheDbEnum.d.ts +0 -0
  407. /package/{lib → dist/lib}/core/cache/cacheDbEnum.js +0 -0
  408. /package/{lib → dist/lib}/core/debug/kuzzleDebugger.d.ts +0 -0
  409. /package/{lib → dist/lib}/core/debug/kuzzleDebugger.js +0 -0
  410. /package/{lib → dist/lib}/core/plugin/pluginContext.d.ts +0 -0
  411. /package/{lib → dist/lib}/core/realtime/channel.d.ts +0 -0
  412. /package/{lib → dist/lib}/core/realtime/channel.js +0 -0
  413. /package/{lib → dist/lib}/core/realtime/connectionRooms.d.ts +0 -0
  414. /package/{lib → dist/lib}/core/realtime/connectionRooms.js +0 -0
  415. /package/{lib → dist/lib}/core/realtime/hotelClerk.d.ts +0 -0
  416. /package/{lib → dist/lib}/core/realtime/hotelClerk.js +0 -0
  417. /package/{lib → dist/lib}/core/realtime/room.d.ts +0 -0
  418. /package/{lib → dist/lib}/core/realtime/room.js +0 -0
  419. /package/{lib → dist/lib}/core/realtime/subscription.d.ts +0 -0
  420. /package/{lib → dist/lib}/core/realtime/subscription.js +0 -0
  421. /package/{lib → dist/lib}/core/security/profileRepository.d.ts +0 -0
  422. /package/{lib → dist/lib}/core/security/profileRepository.js +0 -0
  423. /package/{lib → dist/lib}/core/security/tokenRepository.d.ts +0 -0
  424. /package/{lib → dist/lib}/core/shared/KoncordeWrapper.d.ts +0 -0
  425. /package/{lib → dist/lib}/core/shared/KoncordeWrapper.js +0 -0
  426. /package/{lib → dist/lib}/core/shared/ObjectRepository.d.ts +0 -0
  427. /package/{lib → dist/lib}/core/shared/ObjectRepository.js +0 -0
  428. /package/{lib → dist/lib}/core/shared/sdk/embeddedSdk.d.ts +0 -0
  429. /package/{lib → dist/lib}/core/shared/sdk/embeddedSdk.js +0 -0
  430. /package/{lib → dist/lib}/core/shared/sdk/funnelProtocol.d.ts +0 -0
  431. /package/{lib → dist/lib}/core/shared/sdk/funnelProtocol.js +0 -0
  432. /package/{lib → dist/lib}/core/shared/store.js +0 -0
  433. /package/{lib → dist/lib}/core/storage/indexCache.d.ts +0 -0
  434. /package/{lib → dist/lib}/core/storage/indexCache.js +0 -0
  435. /package/{lib → dist/lib}/core/storage/storeScopeEnum.d.ts +0 -0
  436. /package/{lib → dist/lib}/core/storage/storeScopeEnum.js +0 -0
  437. /package/{lib → dist/lib}/kerror/errors/badRequestError.d.ts +0 -0
  438. /package/{lib → dist/lib}/kerror/errors/badRequestError.js +0 -0
  439. /package/{lib → dist/lib}/kerror/errors/externalServiceError.d.ts +0 -0
  440. /package/{lib → dist/lib}/kerror/errors/externalServiceError.js +0 -0
  441. /package/{lib → dist/lib}/kerror/errors/forbiddenError.d.ts +0 -0
  442. /package/{lib → dist/lib}/kerror/errors/forbiddenError.js +0 -0
  443. /package/{lib → dist/lib}/kerror/errors/gatewayTimeoutError.d.ts +0 -0
  444. /package/{lib → dist/lib}/kerror/errors/gatewayTimeoutError.js +0 -0
  445. /package/{lib → dist/lib}/kerror/errors/index.d.ts +0 -0
  446. /package/{lib → dist/lib}/kerror/errors/index.js +0 -0
  447. /package/{lib → dist/lib}/kerror/errors/internalError.d.ts +0 -0
  448. /package/{lib → dist/lib}/kerror/errors/internalError.js +0 -0
  449. /package/{lib → dist/lib}/kerror/errors/kuzzleError.d.ts +0 -0
  450. /package/{lib → dist/lib}/kerror/errors/kuzzleError.js +0 -0
  451. /package/{lib → dist/lib}/kerror/errors/multipleErrorsError.d.ts +0 -0
  452. /package/{lib → dist/lib}/kerror/errors/multipleErrorsError.js +0 -0
  453. /package/{lib → dist/lib}/kerror/errors/notFoundError.d.ts +0 -0
  454. /package/{lib → dist/lib}/kerror/errors/notFoundError.js +0 -0
  455. /package/{lib → dist/lib}/kerror/errors/partialError.d.ts +0 -0
  456. /package/{lib → dist/lib}/kerror/errors/partialError.js +0 -0
  457. /package/{lib → dist/lib}/kerror/errors/pluginImplementationError.d.ts +0 -0
  458. /package/{lib → dist/lib}/kerror/errors/pluginImplementationError.js +0 -0
  459. /package/{lib → dist/lib}/kerror/errors/preconditionError.d.ts +0 -0
  460. /package/{lib → dist/lib}/kerror/errors/preconditionError.js +0 -0
  461. /package/{lib → dist/lib}/kerror/errors/serviceUnavailableError.d.ts +0 -0
  462. /package/{lib → dist/lib}/kerror/errors/serviceUnavailableError.js +0 -0
  463. /package/{lib → dist/lib}/kerror/errors/sizeLimitError.d.ts +0 -0
  464. /package/{lib → dist/lib}/kerror/errors/sizeLimitError.js +0 -0
  465. /package/{lib → dist/lib}/kerror/errors/tooManyRequestsError.d.ts +0 -0
  466. /package/{lib → dist/lib}/kerror/errors/tooManyRequestsError.js +0 -0
  467. /package/{lib → dist/lib}/kerror/errors/unauthorizedError.d.ts +0 -0
  468. /package/{lib → dist/lib}/kerror/errors/unauthorizedError.js +0 -0
  469. /package/{lib → dist/lib}/kerror/index.js +0 -0
  470. /package/{lib → dist/lib}/kuzzle/event/KuzzleEventEmitter.d.ts +0 -0
  471. /package/{lib → dist/lib}/kuzzle/event/KuzzleEventEmitter.js +0 -0
  472. /package/{lib → dist/lib}/kuzzle/index.d.ts +0 -0
  473. /package/{lib → dist/lib}/kuzzle/index.js +0 -0
  474. /package/{lib → dist/lib}/model/security/profile.d.ts +0 -0
  475. /package/{lib → dist/lib}/model/security/profile.js +0 -0
  476. /package/{lib → dist/lib}/model/security/role.js +0 -0
  477. /package/{lib → dist/lib}/model/security/token.d.ts +0 -0
  478. /package/{lib → dist/lib}/model/security/token.js +0 -0
  479. /package/{lib → dist/lib}/model/security/user.js +0 -0
  480. /package/{lib → dist/lib}/service/storage/8/elasticsearch.d.ts +0 -0
  481. /package/{lib → dist/lib}/service/storage/Elasticsearch.d.ts +0 -0
  482. /package/{lib → dist/lib}/service/storage/Elasticsearch.js +0 -0
  483. /package/{lib → dist/lib}/service/storage/commons/queryTranslator.d.ts +0 -0
  484. /package/{lib → dist/lib}/service/storage/commons/queryTranslator.js +0 -0
  485. /package/{lib → dist/lib}/types/ClientConnection.d.ts +0 -0
  486. /package/{lib → dist/lib}/types/ClientConnection.js +0 -0
  487. /package/{lib → dist/lib}/types/Deprecation.d.ts +0 -0
  488. /package/{lib → dist/lib}/types/Deprecation.js +0 -0
  489. /package/{lib → dist/lib}/types/EventHandler.d.ts +0 -0
  490. /package/{lib → dist/lib}/types/EventHandler.js +0 -0
  491. /package/{lib → dist/lib}/types/Global.d.ts +0 -0
  492. /package/{lib → dist/lib}/types/Global.js +0 -0
  493. /package/{lib → dist/lib}/types/HttpMessage.d.ts +0 -0
  494. /package/{lib → dist/lib}/types/HttpMessage.js +0 -0
  495. /package/{lib → dist/lib}/types/HttpStream.d.ts +0 -0
  496. /package/{lib → dist/lib}/types/HttpStream.js +0 -0
  497. /package/{lib → dist/lib}/types/Kuzzle.d.ts +0 -0
  498. /package/{lib → dist/lib}/types/Kuzzle.js +0 -0
  499. /package/{lib → dist/lib}/types/KuzzleDocument.d.ts +0 -0
  500. /package/{lib → dist/lib}/types/KuzzleDocument.js +0 -0
  501. /package/{lib → dist/lib}/types/OpenApiDefinition.d.ts +0 -0
  502. /package/{lib → dist/lib}/types/OpenApiDefinition.js +0 -0
  503. /package/{lib → dist/lib}/types/PasswordPolicy.d.ts +0 -0
  504. /package/{lib → dist/lib}/types/PasswordPolicy.js +0 -0
  505. /package/{lib → dist/lib}/types/Plugin.js +0 -0
  506. /package/{lib → dist/lib}/types/PluginManifest.d.ts +0 -0
  507. /package/{lib → dist/lib}/types/PluginManifest.js +0 -0
  508. /package/{lib → dist/lib}/types/Policy.d.ts +0 -0
  509. /package/{lib → dist/lib}/types/Policy.js +0 -0
  510. /package/{lib → dist/lib}/types/PolicyRestrictions.d.ts +0 -0
  511. /package/{lib → dist/lib}/types/PolicyRestrictions.js +0 -0
  512. /package/{lib → dist/lib}/types/ProfileDefinition.d.ts +0 -0
  513. /package/{lib → dist/lib}/types/ProfileDefinition.js +0 -0
  514. /package/{lib → dist/lib}/types/RoleDefinition.d.ts +0 -0
  515. /package/{lib → dist/lib}/types/RoleDefinition.js +0 -0
  516. /package/{lib → dist/lib}/types/StrategyDefinition.d.ts +0 -0
  517. /package/{lib → dist/lib}/types/StrategyDefinition.js +0 -0
  518. /package/{lib → dist/lib}/types/Target.d.ts +0 -0
  519. /package/{lib → dist/lib}/types/Target.js +0 -0
  520. /package/{lib → dist/lib}/types/Token.d.ts +0 -0
  521. /package/{lib → dist/lib}/types/Token.js +0 -0
  522. /package/{lib → dist/lib}/types/User.d.ts +0 -0
  523. /package/{lib → dist/lib}/types/User.js +0 -0
  524. /package/{lib → dist/lib}/types/config/DumpConfiguration.d.ts +0 -0
  525. /package/{lib → dist/lib}/types/config/DumpConfiguration.js +0 -0
  526. /package/{lib → dist/lib}/types/config/HttpConfiguration.d.ts +0 -0
  527. /package/{lib → dist/lib}/types/config/HttpConfiguration.js +0 -0
  528. /package/{lib → dist/lib}/types/config/KuzzleConfiguration.d.ts +0 -0
  529. /package/{lib → dist/lib}/types/config/KuzzleConfiguration.js +0 -0
  530. /package/{lib → dist/lib}/types/config/LimitsConfiguration.d.ts +0 -0
  531. /package/{lib → dist/lib}/types/config/LimitsConfiguration.js +0 -0
  532. /package/{lib → dist/lib}/types/config/PluginsConfiguration.d.ts +0 -0
  533. /package/{lib → dist/lib}/types/config/PluginsConfiguration.js +0 -0
  534. /package/{lib → dist/lib}/types/config/SecurityConfiguration.d.ts +0 -0
  535. /package/{lib → dist/lib}/types/config/SecurityConfiguration.js +0 -0
  536. /package/{lib → dist/lib}/types/config/ServerConfiguration.d.ts +0 -0
  537. /package/{lib → dist/lib}/types/config/ServerConfiguration.js +0 -0
  538. /package/{lib → dist/lib}/types/config/ServicesConfiguration.d.ts +0 -0
  539. /package/{lib → dist/lib}/types/config/ServicesConfiguration.js +0 -0
  540. /package/{lib → dist/lib}/types/config/internalCache/InternalCacheRedisConfiguration.d.ts +0 -0
  541. /package/{lib → dist/lib}/types/config/internalCache/InternalCacheRedisConfiguration.js +0 -0
  542. /package/{lib → dist/lib}/types/config/publicCache/PublicCacheRedisConfiguration.d.ts +0 -0
  543. /package/{lib → dist/lib}/types/config/publicCache/PublicCacheRedisConfiguration.js +0 -0
  544. /package/{lib → dist/lib}/types/config/storageEngine/StorageEngineElasticsearchConfiguration.d.ts +0 -0
  545. /package/{lib → dist/lib}/types/config/storageEngine/StorageEngineElasticsearchConfiguration.js +0 -0
  546. /package/{lib/types → dist/lib/types/controllers}/Controller.js +0 -0
  547. /package/{lib/types → dist/lib/types/controllers}/ControllerDefinition.js +0 -0
  548. /package/{lib/types → dist/lib/types/controllers}/ControllerRights.d.ts +0 -0
  549. /package/{lib/types → dist/lib/types/controllers}/ControllerRights.js +0 -0
  550. /package/{lib → dist/lib}/types/errors/ErrorDefinition.d.ts +0 -0
  551. /package/{lib → dist/lib}/types/errors/ErrorDefinition.js +0 -0
  552. /package/{lib → dist/lib}/types/errors/ErrorDomains.d.ts +0 -0
  553. /package/{lib → dist/lib}/types/errors/ErrorDomains.js +0 -0
  554. /package/{lib → dist/lib}/types/events/EventGenericDocument.d.ts +0 -0
  555. /package/{lib → dist/lib}/types/events/EventGenericDocument.js +0 -0
  556. /package/{lib → dist/lib}/types/events/EventProtocol.d.ts +0 -0
  557. /package/{lib → dist/lib}/types/events/EventProtocol.js +0 -0
  558. /package/{lib → dist/lib}/types/realtime/RealtimeScope.d.ts +0 -0
  559. /package/{lib → dist/lib}/types/realtime/RealtimeScope.js +0 -0
  560. /package/{lib → dist/lib}/types/realtime/RealtimeUsers.d.ts +0 -0
  561. /package/{lib → dist/lib}/types/realtime/RealtimeUsers.js +0 -0
  562. /package/{lib → dist/lib}/types/realtime/RoomList.d.ts +0 -0
  563. /package/{lib → dist/lib}/types/realtime/RoomList.js +0 -0
  564. /package/{lib → dist/lib}/types/shared/StoreCollectionsDefinition.d.ts +0 -0
  565. /package/{lib → dist/lib}/types/shared/StoreCollectionsDefinition.js +0 -0
  566. /package/{lib → dist/lib}/types/storage/7/Elasticsearch.d.ts +0 -0
  567. /package/{lib → dist/lib}/types/storage/7/Elasticsearch.js +0 -0
  568. /package/{lib → dist/lib}/types/storage/8/Elasticsearch.d.ts +0 -0
  569. /package/{lib → dist/lib}/types/storage/8/Elasticsearch.js +0 -0
  570. /package/{lib → dist/lib}/util/Inflector.d.ts +0 -0
  571. /package/{lib → dist/lib}/util/Inflector.js +0 -0
  572. /package/{lib → dist/lib}/util/array.d.ts +0 -0
  573. /package/{lib → dist/lib}/util/array.js +0 -0
  574. /package/{lib → dist/lib}/util/async.d.ts +0 -0
  575. /package/{lib → dist/lib}/util/async.js +0 -0
  576. /package/{lib → dist/lib}/util/bufferedPassThrough.d.ts +0 -0
  577. /package/{lib → dist/lib}/util/bufferedPassThrough.js +0 -0
  578. /package/{lib → dist/lib}/util/crypto.d.ts +0 -0
  579. /package/{lib → dist/lib}/util/crypto.js +0 -0
  580. /package/{lib → dist/lib}/util/dump-collection.d.ts +0 -0
  581. /package/{lib → dist/lib}/util/dump-collection.js +0 -0
  582. /package/{lib → dist/lib}/util/esRequest.d.ts +0 -0
  583. /package/{lib → dist/lib}/util/esRequest.js +0 -0
  584. /package/{lib → dist/lib}/util/koncordeCompat.d.ts +0 -0
  585. /package/{lib → dist/lib}/util/koncordeCompat.js +0 -0
  586. /package/{lib → dist/lib}/util/mutex.d.ts +0 -0
  587. /package/{lib → dist/lib}/util/mutex.js +0 -0
  588. /package/{lib → dist/lib}/util/name-generator.d.ts +0 -0
  589. /package/{lib → dist/lib}/util/name-generator.js +0 -0
  590. /package/{lib → dist/lib}/util/time.d.ts +0 -0
  591. /package/{lib → dist/lib}/util/time.js +0 -0
@@ -0,0 +1,921 @@
1
+ /*
2
+ * Kuzzle, a backend software, self-hostable and ready to use
3
+ * to power modern apps
4
+ *
5
+ * Copyright 2015-2022 Kuzzle
6
+ * mailto: support AT kuzzle.io
7
+ * website: http://kuzzle.io
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * https://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ "use strict";
22
+ const querystring = require("querystring");
23
+ const url = require("url");
24
+ const zlib = require("zlib");
25
+ const uWS = require("uWebSockets.js");
26
+ const { HttpStream } = require("../../../types");
27
+ const { Request } = require("../../../api/request");
28
+ const { KuzzleError } = require("../../../kerror/errors");
29
+ const Protocol = require("./protocol");
30
+ const ClientConnection = require("../clientConnection");
31
+ const { removeStacktrace } = require("../../../util/stackTrace");
32
+ const debug = require("../../../util/debug");
33
+ const kerror = require("../../../kerror");
34
+ const HttpMessage = require("./httpMessage");
35
+ const kerrorWS = kerror.wrap("network", "websocket");
36
+ const kerrorHTTP = kerror.wrap("network", "http");
37
+ const debugWS = debug("kuzzle:network:protocols:websocket");
38
+ const debugHTTP = debug("kuzzle:network:protocols:http");
39
+ // The idleTimeout option should never be deactivated, so instead we use
40
+ // a default value for backward-compatibility
41
+ const DEFAULT_IDLE_TIMEOUT = 60000;
42
+ // Size (in bytes) of backpressure an individual socket can handle before
43
+ // needing to drain
44
+ const WS_PER_SOCKET_BACKPRESSURE_BUFFER_SIZE = 4096;
45
+ // Size of the backpressure buffer: if a client is too slow to absorb the amount
46
+ // of data we need to send to it, then we forcibly close its socket to prevent
47
+ // the server to be impacted by it
48
+ const WS_BACKPRESSURE_BUFFER_MAX_LENGTH = 50;
49
+ // Applicative WebSocket PONG message for browsers
50
+ const WS_APP_PONG_RESPONSE = Buffer.from('{"p":2}');
51
+ // Used by the broadcast method to build JSON payloads while limiting the
52
+ // number of JSON serializations
53
+ const JSON_ROOM_PROPERTY = ',"room":"';
54
+ const JSON_ENDER = '"}';
55
+ // Pre-computed messages & errors
56
+ const WS_FORCED_TERMINATION_CODE = 1011;
57
+ const WS_BACKPRESSURE_MESSAGE = Buffer.from("too much backpressure: client is too slow");
58
+ const WS_GENERIC_CLOSE_MESSAGE = Buffer.from("Connection closed by remote host");
59
+ const WS_RATE_LIMIT_EXCEEDED_ERROR = kerrorWS.get("ratelimit_exceeded");
60
+ const HTTP_REQUEST_TOO_LARGE_ERROR = kerrorHTTP.get("request_too_large");
61
+ const HTTP_FILE_TOO_LARGE_ERROR = kerrorHTTP.get("file_too_large");
62
+ // HTTP-related constants
63
+ const HTTP_ALLOWED_CONTENT_TYPES = [
64
+ "application/json",
65
+ "application/x-www-form-urlencoded",
66
+ "multipart/form-data",
67
+ ];
68
+ const HTTP_SKIPPED_HEADERS = ["content-length", "set-cookie"];
69
+ const HTTP_HEADER_CONNECTION = Buffer.from("Connection");
70
+ const HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = Buffer.from("Access-Control-Allow-Origin");
71
+ const HTTP_HEADER_SET_COOKIE = Buffer.from("Set-Cookie");
72
+ const HTTP_HEADER_VARY = Buffer.from("Vary");
73
+ const WILDCARD = Buffer.from("*");
74
+ const ORIGIN = Buffer.from("Origin");
75
+ const X_KUZZLE_REQUEST_ID = Buffer.from("X-Kuzzle-Request-Id");
76
+ const CLOSE = Buffer.from("close");
77
+ const CHARSET_REGEX = /charset=([\w-]+)/i;
78
+ /**
79
+ * @class HTTPWS
80
+ * Handles both HTTP and WebSocket connections
81
+ */
82
+ class HttpWsProtocol extends Protocol {
83
+ constructor() {
84
+ super("websocket");
85
+ this.server = null;
86
+ this.wsConfig = null;
87
+ this.httpConfig = null;
88
+ // Used to limit the rate of messages on websocket
89
+ this.now = Date.now();
90
+ this.nowInterval = setInterval(() => {
91
+ this.now = Date.now();
92
+ }, 1000);
93
+ // Map<uWS.WebSocket, ClientConnection>
94
+ this.connectionBySocket = new Map();
95
+ // Map<uWS.WebSocket, Array.<Buffer>>
96
+ this.backpressureBuffer = new Map();
97
+ // Map<string, uWS.WebSocket>
98
+ this.socketByConnectionId = new Map();
99
+ this.logger = global.kuzzle.log.child("core:network:protocols:httpws");
100
+ }
101
+ async init(entrypoint) {
102
+ super.init(null, entrypoint);
103
+ this.config = entrypoint.config.protocols;
104
+ this.wsConfig = this.parseWebSocketOptions();
105
+ this.httpConfig = this.parseHttpOptions();
106
+ if (!this.wsConfig.enabled && !this.httpConfig.enabled) {
107
+ return false;
108
+ }
109
+ // eslint-disable-next-line new-cap
110
+ this.server = uWS.App();
111
+ if (this.wsConfig.enabled) {
112
+ this.initWebSocket();
113
+ }
114
+ if (this.httpConfig.enabled) {
115
+ this.initHttp();
116
+ }
117
+ this.server.listen(entrypoint.config.port, (socket) => {
118
+ if (!socket) {
119
+ throw new Error(`[http/websocket] fatal: unable to listen to port ${entrypoint.config.port}`);
120
+ }
121
+ });
122
+ return true;
123
+ }
124
+ initWebSocket() {
125
+ /* eslint-disable sort-keys */
126
+ this.server.ws("/*", {
127
+ ...this.wsConfig.opts,
128
+ maxBackPressure: WS_PER_SOCKET_BACKPRESSURE_BUFFER_SIZE,
129
+ upgrade: this.wsOnUpgradeHandler.bind(this),
130
+ open: this.wsOnOpenHandler.bind(this),
131
+ close: this.wsOnCloseHandler.bind(this),
132
+ message: this.wsOnMessageHandler.bind(this),
133
+ drain: this.wsOnDrainHandler.bind(this),
134
+ });
135
+ /* eslint-enable sort-keys */
136
+ }
137
+ initHttp() {
138
+ this.server.any("/*", this.httpOnMessageHandler.bind(this));
139
+ }
140
+ broadcast(data) {
141
+ const stringified = JSON.stringify(data.payload);
142
+ const payloadByteSize = Buffer.from(stringified).byteLength;
143
+ // 255 bytes should be enough to hold the following:
144
+ // ,"room":"<channel identifier>"
145
+ // (with current channel encoding, this is less than 100 bytes)
146
+ const payload = Buffer.allocUnsafe(payloadByteSize + 255);
147
+ let offset = payloadByteSize - 1;
148
+ payload.write(stringified, 0);
149
+ payload.write(JSON_ROOM_PROPERTY, offset);
150
+ offset += JSON_ROOM_PROPERTY.length;
151
+ for (const channel of data.channels) {
152
+ // Adds the room property to the message
153
+ payload.write(channel, offset);
154
+ payload.write(JSON_ENDER, offset + channel.length);
155
+ // prevent buffer overwrites due to sending packets being an
156
+ // async method (race condition)
157
+ const payloadLength = offset + channel.length + JSON_ENDER.length;
158
+ const payloadSafeCopy = Buffer.allocUnsafe(payloadLength);
159
+ payload.copy(payloadSafeCopy, 0, 0, payloadLength);
160
+ debugWS('Publishing to channel "realtime/%s": %s', channel, payloadSafeCopy);
161
+ this.server.publish(`realtime/${channel}`, payloadSafeCopy, false);
162
+ }
163
+ }
164
+ notify(data) {
165
+ const socket = this.socketByConnectionId.get(data.connectionId);
166
+ debugWS("notify: %a", data);
167
+ if (!socket) {
168
+ return;
169
+ }
170
+ const payload = data.payload;
171
+ for (let i = 0; i < data.channels.length; i++) {
172
+ payload.room = data.channels[i];
173
+ this.wsSend(socket, Buffer.from(JSON.stringify(payload)));
174
+ }
175
+ }
176
+ joinChannel(channel, connectionId) {
177
+ const socket = this.socketByConnectionId.get(connectionId);
178
+ if (!socket) {
179
+ return;
180
+ }
181
+ debugWS('Subscribing connection ID "%s" to channel "realtime/%s"', connectionId, channel);
182
+ socket.subscribe(`realtime/${channel}`);
183
+ }
184
+ leaveChannel(channel, connectionId) {
185
+ const socket = this.socketByConnectionId.get(connectionId);
186
+ if (!socket) {
187
+ return;
188
+ }
189
+ debugWS('Removing connection ID "%s" from channel "realtime/%s"', connectionId, channel);
190
+ socket.unsubscribe(`realtime/${channel}`);
191
+ }
192
+ disconnect(connectionId, message = null) {
193
+ debugWS("[%s] forced disconnect", connectionId);
194
+ const socket = this.socketByConnectionId.get(connectionId);
195
+ if (!socket) {
196
+ return;
197
+ }
198
+ socket.end(WS_FORCED_TERMINATION_CODE, message ? Buffer.from(message) : WS_GENERIC_CLOSE_MESSAGE);
199
+ }
200
+ wsOnUpgradeHandler(res, req, context) {
201
+ const headers = {};
202
+ // Extract headers from uWS request
203
+ req.forEach((header, value) => {
204
+ headers[header] = value;
205
+ });
206
+ res.upgrade({
207
+ headers,
208
+ internal: {},
209
+ }, req.getHeader("sec-websocket-key"), req.getHeader("sec-websocket-protocol"), req.getHeader("sec-websocket-extensions"), context);
210
+ }
211
+ wsOnOpenHandler(socket) {
212
+ const ip = Buffer.from(socket.getRemoteAddressAsText()).toString();
213
+ const connection = new ClientConnection(this.name, [ip], socket.headers, socket.internal);
214
+ this.entryPoint.newConnection(connection);
215
+ this.connectionBySocket.set(socket, connection);
216
+ this.socketByConnectionId.set(connection.id, socket);
217
+ this.backpressureBuffer.set(socket, []);
218
+ }
219
+ wsOnCloseHandler(socket, code, message) {
220
+ const connection = this.connectionBySocket.get(socket);
221
+ if (!connection) {
222
+ return;
223
+ }
224
+ const reason = Buffer.from(message || "").toString();
225
+ // This hack is only here to indicate that uWebSockets killed the connection early
226
+ // because the received payload exceeded the configured threshold.
227
+ if (code === 1006 && reason.startsWith("Received too big message")) {
228
+ this.logger.error(`[${connection.id}] connection closed: payload exceeded the threshold`);
229
+ }
230
+ if (debugWS.enabled) {
231
+ debugWS("[%s] received a `close` event (CODE: %d, REASON: %s)", connection.id, code, reason);
232
+ }
233
+ this.entryPoint.removeConnection(connection.id);
234
+ this.connectionBySocket.delete(socket);
235
+ this.backpressureBuffer.delete(socket);
236
+ this.socketByConnectionId.delete(connection.id);
237
+ }
238
+ async wsOnMessageHandler(socket, data) {
239
+ if (!data || data.byteLength === 0) {
240
+ return;
241
+ }
242
+ const connection = this.connectionBySocket.get(socket);
243
+ // enforce rate limits
244
+ if (this.wsConfig.rateLimit > 0) {
245
+ if (socket.last === this.now) {
246
+ socket.count++;
247
+ if (socket.count > this.wsConfig.rateLimit) {
248
+ this.wsSendError(socket, connection, WS_RATE_LIMIT_EXCEEDED_ERROR);
249
+ return;
250
+ }
251
+ }
252
+ else {
253
+ socket.last = this.now;
254
+ socket.count = 1;
255
+ }
256
+ }
257
+ let parsed;
258
+ let message = Buffer.from(data).toString();
259
+ debugWS("[%s] client message: %s", connection.id, message);
260
+ ({ payload: message } = await global.kuzzle.pipe("protocol:websocket:beforeParsingPayload", { connection, payload: message }));
261
+ try {
262
+ ({ payload: parsed } = await global.kuzzle.pipe("protocol:websocket:afterParsingPayload", { connection, payload: JSON.parse(message) }));
263
+ }
264
+ catch (e) {
265
+ /*
266
+ we cannot add a "room" information since we need to extract
267
+ a request ID from the incoming data, which is apparently
268
+ not a valid JSON
269
+ So... the error is forwarded to the client, hoping they know
270
+ what to do with it.
271
+ */
272
+ this.wsSendError(socket, connection, kerrorWS.getFrom(e, "unexpected_error", e.message));
273
+ return;
274
+ }
275
+ if (parsed.p && parsed.p === 1 && Object.keys(parsed).length === 1) {
276
+ debugWS('[%s] sending back a "pong" message', connection.id);
277
+ this.wsSend(socket, WS_APP_PONG_RESPONSE);
278
+ return;
279
+ }
280
+ let request;
281
+ try {
282
+ request = new Request(parsed, { connection });
283
+ }
284
+ catch (e) {
285
+ this.wsSendError(socket, connection, e, parsed.requestId);
286
+ return;
287
+ }
288
+ this.entryPoint.execute(connection, request, (result) => {
289
+ if (result.content) {
290
+ if (typeof result.content === "object") {
291
+ result.content.room = result.requestId;
292
+ }
293
+ }
294
+ else {
295
+ result.content = "";
296
+ }
297
+ this.wsSend(socket, Buffer.from(JSON.stringify(result.content)));
298
+ });
299
+ }
300
+ /**
301
+ * Absorb as much of the backpressure buffer as possible
302
+ * @param {uWS.WebSocket} socket
303
+ */
304
+ wsOnDrainHandler(socket) {
305
+ socket.cork(() => {
306
+ const buffer = this.backpressureBuffer.get(socket);
307
+ while (buffer.length > 0 &&
308
+ socket.getBufferedAmount() < WS_PER_SOCKET_BACKPRESSURE_BUFFER_SIZE) {
309
+ const payload = buffer.shift();
310
+ socket.send(payload);
311
+ }
312
+ });
313
+ }
314
+ /**
315
+ * Forwards an error to a socket
316
+ *
317
+ * @param {uWS.WebSocket} socket
318
+ * @param {ClientConnection} connection
319
+ * @param {Error} error
320
+ * @param {String} requestId @optional
321
+ */
322
+ wsSendError(socket, connection, error, requestId) {
323
+ const request = new Request({}, { connection, error });
324
+ // If a requestId is provided we use it instead of the generated one
325
+ request.id = requestId || request.id;
326
+ const sanitized = removeStacktrace(request.response.toJSON()).content;
327
+ this.wsSend(socket, Buffer.from(JSON.stringify(sanitized)));
328
+ }
329
+ /**
330
+ * Sends a message immediately, or queue it up for later if backpressure built
331
+ * up
332
+ *
333
+ * @param {uWS.WebSocket} socket
334
+ * @param {Buffer} payload
335
+ */
336
+ wsSend(socket, payload) {
337
+ if (!this.connectionBySocket.has(socket)) {
338
+ return;
339
+ }
340
+ if (socket.getBufferedAmount() < WS_PER_SOCKET_BACKPRESSURE_BUFFER_SIZE) {
341
+ socket.cork(() => socket.send(payload));
342
+ }
343
+ else {
344
+ const buffer = this.backpressureBuffer.get(socket);
345
+ buffer.push(payload);
346
+ /**
347
+ * Client socket too slow: we need to close it
348
+ *
349
+ * If the socket is marked as a debugSession, we don't close it
350
+ * the debugger might send a lot of messages and we don't want to
351
+ * loose the connection while debugging and loose important information.
352
+ */
353
+ if (!socket.internal.debugSession &&
354
+ buffer.length > WS_BACKPRESSURE_BUFFER_MAX_LENGTH) {
355
+ socket.end(WS_FORCED_TERMINATION_CODE, WS_BACKPRESSURE_MESSAGE);
356
+ }
357
+ }
358
+ }
359
+ /**
360
+ * @param {uWS.HttpResponse} response
361
+ * @param {uWS.HttpRequest} request
362
+ */
363
+ httpOnMessageHandler(response, request) {
364
+ const connection = new ClientConnection("HTTP/1.1", getHttpIps(response, request), request.headers);
365
+ const message = new HttpMessage(connection, request);
366
+ debugHTTP("[%s] Received HTTP request: %a", connection.id, message);
367
+ if (message.headers["content-length"] > this.maxRequestSize) {
368
+ this.httpSendError(message, response, HTTP_REQUEST_TOO_LARGE_ERROR);
369
+ return;
370
+ }
371
+ const contentTypeHeader = message.headers["content-type"];
372
+ if (contentTypeHeader) {
373
+ const contentTypeParamIndex = contentTypeHeader.indexOf(";");
374
+ const contentType = contentTypeParamIndex !== -1
375
+ ? contentTypeHeader.slice(0, contentTypeParamIndex).trim()
376
+ : contentTypeHeader.trim();
377
+ if (!this.httpConfig.opts.allowedContentTypes.some((allowed) => contentType === allowed)) {
378
+ this.httpSendError(message, response, kerrorHTTP.get("unsupported_content", contentType));
379
+ return;
380
+ }
381
+ }
382
+ const encoding = CHARSET_REGEX.exec(contentTypeHeader);
383
+ if (encoding !== null && encoding[1].toLowerCase() !== "utf-8") {
384
+ this.httpSendError(message, response, kerrorHTTP.get("unsupported_charset", encoding[1].toLowerCase()));
385
+ return;
386
+ }
387
+ this.httpReadData(message, response, (err) => {
388
+ if (err) {
389
+ this.httpSendError(message, response, err);
390
+ return;
391
+ }
392
+ this.httpProcessRequest(response, message);
393
+ });
394
+ }
395
+ /**
396
+ * Read an HTTP payload data
397
+ *
398
+ * @param {HttpMessage} message
399
+ * @param {uWS.HttpResponse} response
400
+ * @param {Function} cb
401
+ */
402
+ httpReadData(message, response, cb) {
403
+ let payload = null;
404
+ response.aborted = false;
405
+ response.onData((data, isLast) => {
406
+ const chunk = Buffer.from(data);
407
+ payload = payload
408
+ ? Buffer.concat([payload, chunk])
409
+ : Buffer.concat([chunk]);
410
+ /*
411
+ * The content-length header can be bypassed and
412
+ * is not reliable enough. We have to enforce the HTTP
413
+ * max size limit while reading chunks too
414
+ */
415
+ if (payload.byteLength > this.maxRequestSize) {
416
+ cb(HTTP_REQUEST_TOO_LARGE_ERROR);
417
+ return;
418
+ }
419
+ if (!isLast) {
420
+ return;
421
+ }
422
+ if (payload.byteLength === 0) {
423
+ cb();
424
+ return;
425
+ }
426
+ let resolve;
427
+ let promise = new Promise((res) => (resolve = res));
428
+ this.httpUncompress(message, payload, async (err, inflated) => {
429
+ if (err) {
430
+ cb(err);
431
+ resolve();
432
+ return;
433
+ }
434
+ const { payload: newPayload } = await global.kuzzle.pipe("protocol:http:beforeParsingPayload", { message, payload: inflated });
435
+ await this.httpParseContent(message, newPayload, cb);
436
+ resolve();
437
+ });
438
+ return promise;
439
+ });
440
+ // Beware: the "response" object might be invalidated at any point of time,
441
+ // whenever the connection gets closed by the client for instance
442
+ response.onAborted(() => {
443
+ response.aborted = true;
444
+ });
445
+ }
446
+ async httpParseContent(message, content, cb) {
447
+ const type = message.headers["content-type"] || "";
448
+ if (type.includes("multipart/form-data")) {
449
+ const parts = uWS.getParts(content, message.headers["content-type"]);
450
+ message.content = {};
451
+ if (!parts) {
452
+ cb();
453
+ return;
454
+ }
455
+ for (const part of parts) {
456
+ if (part.data.byteLength > this.maxFormFileSize) {
457
+ cb(HTTP_FILE_TOO_LARGE_ERROR);
458
+ return;
459
+ }
460
+ if (part.filename) {
461
+ message.content[part.name] = {
462
+ encoding: part.type,
463
+ file: Buffer.from(part.data).toString("base64"),
464
+ filename: part.filename,
465
+ };
466
+ }
467
+ else {
468
+ message.content[part.name] = Buffer.from(part.data).toString();
469
+ }
470
+ }
471
+ }
472
+ else if (type.includes("application/x-www-form-urlencoded")) {
473
+ message.content = querystring.parse(content.toString());
474
+ }
475
+ else {
476
+ try {
477
+ const { payload } = await global.kuzzle.pipe("protocol:http:afterParsingPayload", { message, payload: JSON.parse(content.toString()) });
478
+ message.content = payload;
479
+ }
480
+ catch (e) {
481
+ cb(kerrorHTTP.get("body_parse_failed", content.toString().slice(0, 50)));
482
+ return;
483
+ }
484
+ }
485
+ cb();
486
+ }
487
+ httpProcessRequest(response, message) {
488
+ debugHTTP("[%s] httpProcessRequest: %a", message.connection.id, message);
489
+ if (response.aborted) {
490
+ return;
491
+ }
492
+ this.entryPoint.newConnection(message.connection);
493
+ global.kuzzle.router.http.route(message, (request) => {
494
+ this.entryPoint.logAccess(message.connection, request, message);
495
+ this.entryPoint.removeConnection(message.connection.id);
496
+ if (response.aborted) {
497
+ return;
498
+ }
499
+ if (request.result instanceof HttpStream) {
500
+ this.httpSendStream(request, response, request.result, message);
501
+ return;
502
+ }
503
+ // Send the response in one go
504
+ const data = this.httpRequestToResponse(request, message);
505
+ this.httpCompress(message, data, (result) => {
506
+ if (response.aborted) {
507
+ return;
508
+ }
509
+ request.response.setHeader("Content-Encoding", result.encoding);
510
+ response.cork(() => {
511
+ this.httpWriteRequestHeaders(request, response, message);
512
+ const [success] = response.tryEnd(result.compressed, result.compressed.length);
513
+ if (!success) {
514
+ response.onWritable((offset) => {
515
+ const retryData = result.compressed.subarray(offset);
516
+ const [retrySuccess] = response.tryEnd(retryData, retryData.length);
517
+ return retrySuccess;
518
+ });
519
+ }
520
+ });
521
+ });
522
+ });
523
+ }
524
+ /**
525
+ *
526
+ * @param {uWS.HttpRequest} request
527
+ * @param {uWS.HttpResponse} response
528
+ * @param {HttpMessage} message
529
+ */
530
+ httpWriteRequestHeaders(request, response, message) {
531
+ response.writeStatus(Buffer.from(request.response.status.toString()));
532
+ response.writeHeader(HTTP_HEADER_CONNECTION, CLOSE);
533
+ response.writeHeader(X_KUZZLE_REQUEST_ID, message.requestId);
534
+ for (const header of this.httpConfig.headers) {
535
+ // If header is missing, add the default one
536
+ if (request.response.headers[header[2]] === undefined) {
537
+ response.writeHeader(header[0], header[1]);
538
+ }
539
+ }
540
+ // Access-Control-Allow-Origin Logic
541
+ if (request.response.headers["Access-Control-Allow-Origin"] === undefined &&
542
+ message.headers &&
543
+ message.headers.origin) {
544
+ response.writeHeader(HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, Buffer.from(message.headers.origin));
545
+ response.writeHeader(HTTP_HEADER_VARY, ORIGIN);
546
+ }
547
+ if (request.response.headers["set-cookie"]) {
548
+ for (const cookie of request.response.headers["set-cookie"]) {
549
+ response.writeHeader(HTTP_HEADER_SET_COOKIE, Buffer.from(cookie));
550
+ }
551
+ }
552
+ for (const [key, value] of Object.entries(request.response.headers)) {
553
+ // Skip some headers that are not allowed to be sent or modified
554
+ if (HTTP_SKIPPED_HEADERS.includes(key.toLowerCase())) {
555
+ continue;
556
+ }
557
+ response.writeHeader(Buffer.from(key), Buffer.from(value.toString()));
558
+ }
559
+ }
560
+ /**
561
+ * Send stream data thorugh the HTTP response
562
+ * @param {HttpRequest} request
563
+ * @param {HttpStream} httpStream - The data stream to send
564
+ * @param {uWS.HttpResponse} response
565
+ * @param {HttpMessage} message
566
+ */
567
+ httpSendStream(request, response, httpStream, message) {
568
+ const streamSizeFixed = typeof httpStream.totalBytes === "number" && httpStream.totalBytes > 0;
569
+ if (httpStream.errored) {
570
+ this.httpSendError(message, response, kerror.get("network", "http", "stream_errored", httpStream.error.message));
571
+ return;
572
+ }
573
+ if (httpStream.destroyed) {
574
+ this.httpSendError(message, response, kerror.get("network", "http", "stream_closed"));
575
+ return;
576
+ }
577
+ // Remove Content-Length header to avoid conflic with Transfer-Encoding header
578
+ request.response.setHeader("Content-Length", null);
579
+ // Send Headers in one go
580
+ response.cork(() => {
581
+ this.httpWriteRequestHeaders(request, response, message);
582
+ });
583
+ httpStream.stream.on("data", (chunk) => {
584
+ // Make a copy of the array buffer
585
+ const arrayBuffer = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
586
+ const arrayBufferOffset = response.getWriteOffset();
587
+ let backpressure = false;
588
+ /**
589
+ * Switch method of writing data to the response
590
+ * based on the size of the stream.
591
+ * If the stream has a fixed size we can use the tryEnd method
592
+ */
593
+ if (streamSizeFixed) {
594
+ const [success, done] = response.tryEnd(arrayBuffer, httpStream.totalBytes);
595
+ backpressure = !success;
596
+ if (done) {
597
+ httpStream.destroy();
598
+ return;
599
+ }
600
+ }
601
+ else {
602
+ const success = response.write(arrayBuffer);
603
+ backpressure = !success;
604
+ }
605
+ // In case of backpressure we need to wait for drainage before sending more data
606
+ if (backpressure) {
607
+ response.arrayBufferOffset = arrayBufferOffset;
608
+ response.arrayBuffer = arrayBuffer;
609
+ httpStream.stream.pause();
610
+ /**
611
+ * When the stream is drained we can resume sending data,
612
+ * only if the is no backpressure after we wrote the missing chunk data.
613
+ */
614
+ response.onWritable((offset) => {
615
+ if (!streamSizeFixed && offset - response.arrayBufferOffset === 0) {
616
+ httpStream.stream.resume();
617
+ return true;
618
+ }
619
+ let retryBackpressure = false;
620
+ const remainingChunkData = response.arrayBuffer.slice(offset - response.arrayBufferOffset);
621
+ if (streamSizeFixed) {
622
+ const [success] = response.tryEnd(remainingChunkData, httpStream.totalBytes);
623
+ retryBackpressure = !success;
624
+ }
625
+ else {
626
+ const success = response.write(remainingChunkData);
627
+ retryBackpressure = !success;
628
+ }
629
+ if (!retryBackpressure) {
630
+ httpStream.stream.resume();
631
+ }
632
+ return !retryBackpressure;
633
+ });
634
+ }
635
+ });
636
+ httpStream.stream.on("end", () => {
637
+ if (httpStream.destroy()) {
638
+ response.end();
639
+ }
640
+ });
641
+ httpStream.stream.on("close", () => {
642
+ if (httpStream.destroy()) {
643
+ response.end();
644
+ }
645
+ });
646
+ httpStream.stream.on("error", (err) => {
647
+ if (httpStream.destroy()) {
648
+ response.end();
649
+ }
650
+ debugHTTP("[%s] httpSendStream: %s", httpStream.connection.id, err.message);
651
+ });
652
+ response.onAborted(() => {
653
+ httpStream.destroy();
654
+ });
655
+ }
656
+ /**
657
+ * Forward an error response to the client
658
+ *
659
+ * @param {HttpMessage} message
660
+ * @param {uWS.HttpResponse} response
661
+ * @param {Error} error
662
+ */
663
+ httpSendError(message, response, error) {
664
+ const kerr = error instanceof KuzzleError
665
+ ? error
666
+ : kerrorHTTP.getFrom(error, "unexpected_error", error.message);
667
+ const content = Buffer.from(JSON.stringify(removeStacktrace(kerr)));
668
+ debugHTTP("[%s] httpSendError: %a", message.connection.id, kerr);
669
+ this.entryPoint.logAccess(message.connection, new Request(message, {
670
+ connectionId: message.connection.id,
671
+ error: kerr,
672
+ }), message);
673
+ this.entryPoint.removeConnection(message.connection.id);
674
+ if (response.aborted) {
675
+ return;
676
+ }
677
+ response.cork(() => {
678
+ response.writeStatus(Buffer.from(kerr.status.toString()));
679
+ for (const header of this.httpConfig.headers) {
680
+ response.writeHeader(header[0], header[1]);
681
+ }
682
+ // Access-Control-Allow-Origin Logic
683
+ if (message.headers && message.headers.origin) {
684
+ if (global.kuzzle.config.internal.allowAllOrigins) {
685
+ response.writeHeader(HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, WILDCARD);
686
+ }
687
+ else {
688
+ response.writeHeader(HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, Buffer.from(message.headers.origin));
689
+ response.writeHeader(HTTP_HEADER_VARY, ORIGIN);
690
+ }
691
+ }
692
+ response.end(content);
693
+ });
694
+ }
695
+ /**
696
+ * Convert a Kuzzle query result into an appropriate payload format
697
+ * to send back to the client
698
+ *
699
+ * @param {Request} request
700
+ * @param {HttpMessage} message
701
+ * @returns {Buffer}
702
+ */
703
+ httpRequestToResponse(request, message) {
704
+ let data = removeStacktrace(request.response.toJSON());
705
+ if (message.requestId !== data.requestId) {
706
+ data.requestId = message.requestId;
707
+ if (!data.raw) {
708
+ data.content.requestId = message.requestId;
709
+ }
710
+ }
711
+ debugHTTP("HTTP request response: %a", data);
712
+ if (data.raw) {
713
+ if (data.content === null || data.content === undefined) {
714
+ data = "";
715
+ }
716
+ else if (typeof data.content === "object") {
717
+ /*
718
+ This object can be either a Buffer object, a stringified Buffer object,
719
+ or anything else.
720
+ In the former two cases, we create a new Buffer object, and in the
721
+ latter, we stringify t he content.
722
+ */
723
+ if (data.content instanceof Buffer ||
724
+ (data.content.type === "Buffer" && Array.isArray(data.content.data))) {
725
+ data = data.content;
726
+ }
727
+ else {
728
+ data = JSON.stringify(data.content);
729
+ }
730
+ }
731
+ else {
732
+ // scalars are sent as strings
733
+ data = data.content.toString();
734
+ }
735
+ }
736
+ else {
737
+ let indent = 0;
738
+ const parsedUrl = url.parse(message.url, true);
739
+ if (parsedUrl.query && parsedUrl.query.pretty !== undefined) {
740
+ indent = 2;
741
+ }
742
+ data = JSON.stringify(data.content, undefined, indent);
743
+ }
744
+ return Buffer.from(data);
745
+ }
746
+ /**
747
+ * Compress an outgoing message according to the
748
+ * specified accept-encoding HTTP header
749
+ *
750
+ * @param {HttpMessage} message
751
+ * @param {Buffer} data
752
+ * @param {Function} callback
753
+ */
754
+ httpCompress(message, data, callback) {
755
+ if (message.headers["accept-encoding"]) {
756
+ const encodings = message.headers["accept-encoding"]
757
+ .split(",")
758
+ .map((e) => e.trim().toLowerCase());
759
+ let algorithm;
760
+ let priority = -1;
761
+ for (const encoding of encodings) {
762
+ if (encoding.startsWith("gzip") || encoding.startsWith("deflate")) {
763
+ let [_algorithm, _priority = "q=0"] = encoding.split(";");
764
+ _priority = Number.parseFloat(_priority.split("=")[1] || 0);
765
+ if (_priority > priority) {
766
+ algorithm = _algorithm;
767
+ priority = _priority;
768
+ }
769
+ // gzip should be the preferred algorithm in case of a tie
770
+ else if (Math.abs(priority - _priority) < 10e-3 &&
771
+ _algorithm === "gzip") {
772
+ algorithm = "gzip";
773
+ }
774
+ }
775
+ }
776
+ if (algorithm === "gzip") {
777
+ zlib.gzip(data, (err, compressed) => callback({
778
+ compressed: !err ? compressed : data,
779
+ encoding: !err ? "gzip" : "identity",
780
+ }));
781
+ return;
782
+ }
783
+ else if (algorithm === "deflate") {
784
+ zlib.deflate(data, (err, compressed) => callback({
785
+ compressed: !err ? compressed : data,
786
+ encoding: !err ? "deflate" : "identity",
787
+ }));
788
+ return;
789
+ }
790
+ }
791
+ callback({
792
+ compressed: data,
793
+ encoding: "identity",
794
+ });
795
+ }
796
+ httpUncompress(message, payload, cb) {
797
+ let encodings = message.headers["content-encoding"];
798
+ if (!encodings) {
799
+ cb(null, payload);
800
+ return;
801
+ }
802
+ encodings = encodings.split(",").map((e) => e.trim().toLowerCase());
803
+ if (encodings.length > this.httpConfig.opts.maxEncodingLayers) {
804
+ cb(kerrorHTTP.get("too_many_encodings"));
805
+ return;
806
+ }
807
+ // encodings are listed in the same order they have been applied
808
+ // this means that we need to invert the list to correctly
809
+ // decode the message
810
+ encodings.reverse();
811
+ this.httpUncompressStep(encodings, payload, cb, 0);
812
+ }
813
+ httpUncompressStep(encodings, payload, cb, index) {
814
+ if (index === encodings.length) {
815
+ cb(null, payload);
816
+ return;
817
+ }
818
+ const encoding = encodings[index];
819
+ if (encoding === "identity") {
820
+ this.httpUncompressStep(encodings, payload, cb, index + 1);
821
+ }
822
+ else if (encoding === "gzip" || encoding === "deflate") {
823
+ const fn = encoding === "gzip" ? zlib.gunzip : zlib.inflate;
824
+ fn(payload, (err, inflated) => {
825
+ if (err) {
826
+ cb(err);
827
+ return;
828
+ }
829
+ this.httpUncompressStep(encodings, inflated, cb, index + 1);
830
+ });
831
+ }
832
+ else {
833
+ cb(kerrorHTTP.get("unsupported_compression", encoding));
834
+ }
835
+ }
836
+ parseWebSocketOptions() {
837
+ const cfg = this.config.websocket;
838
+ if (cfg === undefined) {
839
+ this.logger.warn("[websocket] no configuration found for websocket: disabling it");
840
+ return { enabled: false };
841
+ }
842
+ let idleTimeout = cfg.idleTimeout;
843
+ const compression = cfg.compression ? uWS.SHARED_COMPRESSOR : uWS.DISABLED;
844
+ if (idleTimeout === 0 || idleTimeout < 1000) {
845
+ idleTimeout = DEFAULT_IDLE_TIMEOUT;
846
+ this.logger.warn(`[websocket] The "idleTimeout" parameter can neither be deactivated or be set with a value lower than 1000. Defaulted to ${DEFAULT_IDLE_TIMEOUT}.`);
847
+ }
848
+ const idleTimeoutInSecond = Math.round(idleTimeout / 1000);
849
+ /**
850
+ * @deprecated -- to be removed in the next major version
851
+ */
852
+ if (cfg.heartbeat) {
853
+ this.logger.warn('[websocket] The "heartbeat" parameter has been deprecated and is now ignored. The "idleTimeout" parameter should now be configured instead.');
854
+ }
855
+ return {
856
+ enabled: cfg.enabled,
857
+ opts: {
858
+ compression,
859
+ idleTimeout: idleTimeoutInSecond,
860
+ maxPayloadLength: this.maxRequestSize,
861
+ resetIdleTimeoutOnSend: cfg.resetIdleTimeoutOnSend,
862
+ sendPingsAutomatically: cfg.sendPingsAutomatically,
863
+ },
864
+ rateLimit: cfg.rateLimit,
865
+ };
866
+ }
867
+ parseHttpOptions() {
868
+ const cfg = this.config.http;
869
+ if (cfg === undefined) {
870
+ this.logger.warn("[http] no configuration found for http: disabling it");
871
+ return { enabled: false };
872
+ }
873
+ // precomputes default headers
874
+ const httpCfg = global.kuzzle.config.http;
875
+ const headers = [
876
+ ["Access-Control-Allow-Headers", httpCfg.accessControlAllowHeaders],
877
+ ["Access-Control-Allow-Methods", httpCfg.accessControlAllowMethods],
878
+ ["Content-Type", "application/json"],
879
+ ];
880
+ for (const header of headers) {
881
+ header[2] = header[0]; // Save the raw header name in the third slot
882
+ header[0] = Buffer.from(header[0]);
883
+ header[1] = Buffer.from(header[1]);
884
+ }
885
+ return {
886
+ enabled: cfg.enabled,
887
+ headers,
888
+ opts: {
889
+ allowCompression: cfg.allowCompression,
890
+ allowedContentTypes: [
891
+ ...HTTP_ALLOWED_CONTENT_TYPES,
892
+ ...cfg.additionalContentTypes,
893
+ ],
894
+ maxEncodingLayers: cfg.maxEncodingLayers,
895
+ maxFormFileSize: cfg.maxFormFileSize,
896
+ },
897
+ };
898
+ }
899
+ }
900
+ /**
901
+ * Returns the list of IP addresses
902
+ *
903
+ * @param {uWS.HttpResponse} response
904
+ * @param {uWS.HttpRequest} request
905
+ * @return {Array.<string>}
906
+ */
907
+ function getHttpIps(response, request) {
908
+ const ips = [Buffer.from(response.getRemoteAddressAsText()).toString()];
909
+ const forwardHeader = request.getHeader("x-forwarded-for");
910
+ if (forwardHeader && forwardHeader.length > 0) {
911
+ for (const header of forwardHeader.split(",")) {
912
+ const trimmed = header.trim();
913
+ if (trimmed.length > 0) {
914
+ ips.push(trimmed);
915
+ }
916
+ }
917
+ }
918
+ return ips;
919
+ }
920
+ module.exports = HttpWsProtocol;
921
+ //# sourceMappingURL=httpwsProtocol.js.map