@contember/engine-http 2.1.0-beta.2 → 2.2.0-alpha.1

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 (556) hide show
  1. package/CLAUDE.md +2 -0
  2. package/dist/development/index.cjs +11 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +12 -1
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/MasterContainer.cjs +48 -7
  7. package/dist/development/src/MasterContainer.cjs.map +1 -1
  8. package/dist/development/src/MasterContainer.js +48 -7
  9. package/dist/development/src/MasterContainer.js.map +1 -1
  10. package/dist/development/src/application/application.cjs +36 -7
  11. package/dist/development/src/application/application.cjs.map +1 -1
  12. package/dist/development/src/application/application.js +36 -7
  13. package/dist/development/src/application/application.js.map +1 -1
  14. package/dist/development/src/application/forceHttpOk.cjs +34 -0
  15. package/dist/development/src/application/forceHttpOk.cjs.map +1 -0
  16. package/dist/development/src/application/forceHttpOk.js +34 -0
  17. package/dist/development/src/application/forceHttpOk.js.map +1 -0
  18. package/dist/development/src/bootstrap/Initializer.cjs.map +1 -1
  19. package/dist/development/src/bootstrap/Initializer.js.map +1 -1
  20. package/dist/development/src/common/Authorizator.cjs +61 -4
  21. package/dist/development/src/common/Authorizator.cjs.map +1 -1
  22. package/dist/development/src/common/Authorizator.js +61 -4
  23. package/dist/development/src/common/Authorizator.js.map +1 -1
  24. package/dist/development/src/common/ModuleInfoMiddleware.cjs.map +1 -1
  25. package/dist/development/src/common/ModuleInfoMiddleware.js.map +1 -1
  26. package/dist/development/src/common/NotFoundMiddleware.cjs +15 -0
  27. package/dist/development/src/common/NotFoundMiddleware.cjs.map +1 -0
  28. package/dist/development/src/common/NotFoundMiddleware.js +15 -0
  29. package/dist/development/src/common/NotFoundMiddleware.js.map +1 -0
  30. package/dist/development/src/config/config.cjs.map +1 -1
  31. package/dist/development/src/config/config.js.map +1 -1
  32. package/dist/development/src/config/configSchema.cjs +64 -2
  33. package/dist/development/src/config/configSchema.cjs.map +1 -1
  34. package/dist/development/src/config/configSchema.js +64 -2
  35. package/dist/development/src/config/configSchema.js.map +1 -1
  36. package/dist/development/src/config/configTemplate.cjs +13 -2
  37. package/dist/development/src/config/configTemplate.cjs.map +1 -1
  38. package/dist/development/src/config/configTemplate.js +13 -2
  39. package/dist/development/src/config/configTemplate.js.map +1 -1
  40. package/dist/development/src/config/projectConfigResolver.cjs.map +1 -1
  41. package/dist/development/src/config/projectConfigResolver.js.map +1 -1
  42. package/dist/development/src/config/tenantConfigResolver.cjs.map +1 -1
  43. package/dist/development/src/config/tenantConfigResolver.js.map +1 -1
  44. package/dist/development/src/content/ContentApiControllerFactory.cjs +26 -4
  45. package/dist/development/src/content/ContentApiControllerFactory.cjs.map +1 -1
  46. package/dist/development/src/content/ContentApiControllerFactory.js +26 -4
  47. package/dist/development/src/content/ContentApiControllerFactory.js.map +1 -1
  48. package/dist/development/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
  49. package/dist/development/src/content/ContentQueryHandlerFactory.js.map +1 -1
  50. package/dist/development/src/content/ContentSchemaResolver.cjs.map +1 -1
  51. package/dist/development/src/content/ContentSchemaResolver.js.map +1 -1
  52. package/dist/development/src/content/GraphQlSchemaFactory.cjs.map +1 -1
  53. package/dist/development/src/content/GraphQlSchemaFactory.js.map +1 -1
  54. package/dist/development/src/content/NotModifiedChecker.cjs.map +1 -1
  55. package/dist/development/src/content/NotModifiedChecker.js.map +1 -1
  56. package/dist/development/src/content/ProjectMembershipResolver.cjs +1 -0
  57. package/dist/development/src/content/ProjectMembershipResolver.cjs.map +1 -1
  58. package/dist/development/src/content/ProjectMembershipResolver.js +1 -0
  59. package/dist/development/src/content/ProjectMembershipResolver.js.map +1 -1
  60. package/dist/development/src/content/triggeredActionsListener.cjs.map +1 -1
  61. package/dist/development/src/content/triggeredActionsListener.js.map +1 -1
  62. package/dist/development/src/graphql/dbQueriesListener.cjs.map +1 -1
  63. package/dist/development/src/graphql/dbQueriesListener.js.map +1 -1
  64. package/dist/development/src/misc/HomepageMiddlewareFactory.cjs +1 -0
  65. package/dist/development/src/misc/HomepageMiddlewareFactory.cjs.map +1 -1
  66. package/dist/development/src/misc/HomepageMiddlewareFactory.js +1 -0
  67. package/dist/development/src/misc/HomepageMiddlewareFactory.js.map +1 -1
  68. package/dist/development/src/project/ProjectContainer.cjs +1 -0
  69. package/dist/development/src/project/ProjectContainer.cjs.map +1 -1
  70. package/dist/development/src/project/ProjectContainer.js +1 -0
  71. package/dist/development/src/project/ProjectContainer.js.map +1 -1
  72. package/dist/development/src/project/ProjectContainerResolver.cjs.map +1 -1
  73. package/dist/development/src/project/ProjectContainerResolver.js.map +1 -1
  74. package/dist/development/src/project/ProjectContainerStore.cjs.map +1 -1
  75. package/dist/development/src/project/ProjectContainerStore.js.map +1 -1
  76. package/dist/development/src/project/ProjectInitializer.cjs.map +1 -1
  77. package/dist/development/src/project/ProjectInitializer.js.map +1 -1
  78. package/dist/development/src/project/ProjectSchemaResolver.cjs.map +1 -1
  79. package/dist/development/src/project/ProjectSchemaResolver.js.map +1 -1
  80. package/dist/development/src/project-common/ProjectContextResolver.cjs +1 -0
  81. package/dist/development/src/project-common/ProjectContextResolver.cjs.map +1 -1
  82. package/dist/development/src/project-common/ProjectContextResolver.js +1 -0
  83. package/dist/development/src/project-common/ProjectContextResolver.js.map +1 -1
  84. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +17 -4
  85. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
  86. package/dist/development/src/projectGroup/ProjectGroupContainer.js +17 -4
  87. package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
  88. package/dist/development/src/projectGroup/ProjectGroupContainerResolver.cjs.map +1 -1
  89. package/dist/development/src/projectGroup/ProjectGroupContainerResolver.js.map +1 -1
  90. package/dist/development/src/projectGroup/ProjectGroupResolver.cjs +1 -0
  91. package/dist/development/src/projectGroup/ProjectGroupResolver.cjs.map +1 -1
  92. package/dist/development/src/projectGroup/ProjectGroupResolver.js +1 -0
  93. package/dist/development/src/projectGroup/ProjectGroupResolver.js.map +1 -1
  94. package/dist/development/src/prometheus/CollectHttpMetricsMiddelware.cjs.map +1 -1
  95. package/dist/development/src/prometheus/CollectHttpMetricsMiddelware.js.map +1 -1
  96. package/dist/development/src/prometheus/ProjectGroupContainerMetricsHook.cjs.map +1 -1
  97. package/dist/development/src/prometheus/ProjectGroupContainerMetricsHook.js.map +1 -1
  98. package/dist/development/src/prometheus/PrometheusRegistryFactory.cjs.map +1 -1
  99. package/dist/development/src/prometheus/PrometheusRegistryFactory.js.map +1 -1
  100. package/dist/development/src/prometheus/ShowMetricsMiddleware.cjs.map +1 -1
  101. package/dist/development/src/prometheus/ShowMetricsMiddleware.js.map +1 -1
  102. package/dist/development/src/prometheus/dbMetrics.cjs.map +1 -1
  103. package/dist/development/src/prometheus/dbMetrics.js.map +1 -1
  104. package/dist/development/src/system/ContentQueryExecutor.cjs.map +1 -1
  105. package/dist/development/src/system/ContentQueryExecutor.js.map +1 -1
  106. package/dist/development/src/system/SystemApiMiddlewareFactory.cjs +1 -0
  107. package/dist/development/src/system/SystemApiMiddlewareFactory.cjs.map +1 -1
  108. package/dist/development/src/system/SystemApiMiddlewareFactory.js +1 -0
  109. package/dist/development/src/system/SystemApiMiddlewareFactory.js.map +1 -1
  110. package/dist/development/src/system/SystemGraphQLContextFactory.cjs.map +1 -1
  111. package/dist/development/src/system/SystemGraphQLContextFactory.js.map +1 -1
  112. package/dist/development/src/system/SystemGraphQLHandlerFactory.cjs.map +1 -1
  113. package/dist/development/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
  114. package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs +46 -0
  115. package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs.map +1 -0
  116. package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js +46 -0
  117. package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js.map +1 -0
  118. package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs +8 -1
  119. package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
  120. package/dist/development/src/tenant/TenantApiMiddlewareFactory.js +8 -1
  121. package/dist/development/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
  122. package/dist/development/src/tenant/TenantGraphQLHandlerFactory.cjs.map +1 -1
  123. package/dist/development/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
  124. package/dist/development/src/testing/TestTransactions.cjs +144 -0
  125. package/dist/development/src/testing/TestTransactions.cjs.map +1 -0
  126. package/dist/development/src/testing/TestTransactions.js +144 -0
  127. package/dist/development/src/testing/TestTransactions.js.map +1 -0
  128. package/dist/development/src/transfer/CommandStream.cjs.map +1 -1
  129. package/dist/development/src/transfer/CommandStream.js.map +1 -1
  130. package/dist/development/src/transfer/ContentSchemaTransferMappingFactory.cjs.map +1 -1
  131. package/dist/development/src/transfer/ContentSchemaTransferMappingFactory.js.map +1 -1
  132. package/dist/development/src/transfer/ExportApiControllerFactory.cjs +1 -0
  133. package/dist/development/src/transfer/ExportApiControllerFactory.cjs.map +1 -1
  134. package/dist/development/src/transfer/ExportApiControllerFactory.js +1 -0
  135. package/dist/development/src/transfer/ExportApiControllerFactory.js.map +1 -1
  136. package/dist/development/src/transfer/ExportExecutor.cjs +4 -1
  137. package/dist/development/src/transfer/ExportExecutor.cjs.map +1 -1
  138. package/dist/development/src/transfer/ExportExecutor.js +4 -1
  139. package/dist/development/src/transfer/ExportExecutor.js.map +1 -1
  140. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +1 -0
  141. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  142. package/dist/development/src/transfer/ImportApiMiddlewareFactory.js +1 -0
  143. package/dist/development/src/transfer/ImportApiMiddlewareFactory.js.map +1 -1
  144. package/dist/development/src/transfer/ImportExecutor.cjs +7 -3
  145. package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
  146. package/dist/development/src/transfer/ImportExecutor.js +7 -3
  147. package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
  148. package/dist/development/src/transfer/SystemSchemaTransferMappingFactory.cjs.map +1 -1
  149. package/dist/development/src/transfer/SystemSchemaTransferMappingFactory.js.map +1 -1
  150. package/dist/development/src/utils/CryptoWrapper.cjs +4 -0
  151. package/dist/development/src/utils/CryptoWrapper.cjs.map +1 -1
  152. package/dist/development/src/utils/CryptoWrapper.js +4 -0
  153. package/dist/development/src/utils/CryptoWrapper.js.map +1 -1
  154. package/dist/development/src/utils/remoteAddress.cjs +5 -4
  155. package/dist/development/src/utils/remoteAddress.cjs.map +1 -1
  156. package/dist/development/src/utils/remoteAddress.js +5 -4
  157. package/dist/development/src/utils/remoteAddress.js.map +1 -1
  158. package/dist/development/src/utils/sentry.cjs.map +1 -1
  159. package/dist/development/src/utils/sentry.js.map +1 -1
  160. package/dist/development/src/utils/serverStartup.cjs +2 -2
  161. package/dist/development/src/utils/serverStartup.cjs.map +1 -1
  162. package/dist/development/src/utils/serverStartup.js.map +1 -1
  163. package/dist/production/index.cjs +11 -0
  164. package/dist/production/index.cjs.map +1 -1
  165. package/dist/production/index.js +12 -1
  166. package/dist/production/index.js.map +1 -1
  167. package/dist/production/src/MasterContainer.cjs +48 -7
  168. package/dist/production/src/MasterContainer.cjs.map +1 -1
  169. package/dist/production/src/MasterContainer.js +48 -7
  170. package/dist/production/src/MasterContainer.js.map +1 -1
  171. package/dist/production/src/application/application.cjs +36 -7
  172. package/dist/production/src/application/application.cjs.map +1 -1
  173. package/dist/production/src/application/application.js +36 -7
  174. package/dist/production/src/application/application.js.map +1 -1
  175. package/dist/production/src/application/forceHttpOk.cjs +34 -0
  176. package/dist/production/src/application/forceHttpOk.cjs.map +1 -0
  177. package/dist/production/src/application/forceHttpOk.js +34 -0
  178. package/dist/production/src/application/forceHttpOk.js.map +1 -0
  179. package/dist/production/src/bootstrap/Initializer.cjs.map +1 -1
  180. package/dist/production/src/bootstrap/Initializer.js.map +1 -1
  181. package/dist/production/src/common/Authorizator.cjs +61 -4
  182. package/dist/production/src/common/Authorizator.cjs.map +1 -1
  183. package/dist/production/src/common/Authorizator.js +61 -4
  184. package/dist/production/src/common/Authorizator.js.map +1 -1
  185. package/dist/production/src/common/ModuleInfoMiddleware.cjs.map +1 -1
  186. package/dist/production/src/common/ModuleInfoMiddleware.js.map +1 -1
  187. package/dist/production/src/common/NotFoundMiddleware.cjs +15 -0
  188. package/dist/production/src/common/NotFoundMiddleware.cjs.map +1 -0
  189. package/dist/production/src/common/NotFoundMiddleware.js +15 -0
  190. package/dist/production/src/common/NotFoundMiddleware.js.map +1 -0
  191. package/dist/production/src/config/config.cjs.map +1 -1
  192. package/dist/production/src/config/config.js.map +1 -1
  193. package/dist/production/src/config/configSchema.cjs +64 -2
  194. package/dist/production/src/config/configSchema.cjs.map +1 -1
  195. package/dist/production/src/config/configSchema.js +64 -2
  196. package/dist/production/src/config/configSchema.js.map +1 -1
  197. package/dist/production/src/config/configTemplate.cjs +13 -2
  198. package/dist/production/src/config/configTemplate.cjs.map +1 -1
  199. package/dist/production/src/config/configTemplate.js +13 -2
  200. package/dist/production/src/config/configTemplate.js.map +1 -1
  201. package/dist/production/src/config/projectConfigResolver.cjs.map +1 -1
  202. package/dist/production/src/config/projectConfigResolver.js.map +1 -1
  203. package/dist/production/src/config/tenantConfigResolver.cjs.map +1 -1
  204. package/dist/production/src/config/tenantConfigResolver.js.map +1 -1
  205. package/dist/production/src/content/ContentApiControllerFactory.cjs +26 -4
  206. package/dist/production/src/content/ContentApiControllerFactory.cjs.map +1 -1
  207. package/dist/production/src/content/ContentApiControllerFactory.js +26 -4
  208. package/dist/production/src/content/ContentApiControllerFactory.js.map +1 -1
  209. package/dist/production/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
  210. package/dist/production/src/content/ContentQueryHandlerFactory.js.map +1 -1
  211. package/dist/production/src/content/ContentSchemaResolver.cjs.map +1 -1
  212. package/dist/production/src/content/ContentSchemaResolver.js.map +1 -1
  213. package/dist/production/src/content/GraphQlSchemaFactory.cjs.map +1 -1
  214. package/dist/production/src/content/GraphQlSchemaFactory.js.map +1 -1
  215. package/dist/production/src/content/NotModifiedChecker.cjs.map +1 -1
  216. package/dist/production/src/content/NotModifiedChecker.js.map +1 -1
  217. package/dist/production/src/content/ProjectMembershipResolver.cjs +1 -0
  218. package/dist/production/src/content/ProjectMembershipResolver.cjs.map +1 -1
  219. package/dist/production/src/content/ProjectMembershipResolver.js +1 -0
  220. package/dist/production/src/content/ProjectMembershipResolver.js.map +1 -1
  221. package/dist/production/src/content/triggeredActionsListener.cjs.map +1 -1
  222. package/dist/production/src/content/triggeredActionsListener.js.map +1 -1
  223. package/dist/production/src/graphql/dbQueriesListener.cjs.map +1 -1
  224. package/dist/production/src/graphql/dbQueriesListener.js.map +1 -1
  225. package/dist/production/src/misc/HomepageMiddlewareFactory.cjs +1 -0
  226. package/dist/production/src/misc/HomepageMiddlewareFactory.cjs.map +1 -1
  227. package/dist/production/src/misc/HomepageMiddlewareFactory.js +1 -0
  228. package/dist/production/src/misc/HomepageMiddlewareFactory.js.map +1 -1
  229. package/dist/production/src/project/ProjectContainer.cjs +1 -0
  230. package/dist/production/src/project/ProjectContainer.cjs.map +1 -1
  231. package/dist/production/src/project/ProjectContainer.js +1 -0
  232. package/dist/production/src/project/ProjectContainer.js.map +1 -1
  233. package/dist/production/src/project/ProjectContainerResolver.cjs.map +1 -1
  234. package/dist/production/src/project/ProjectContainerResolver.js.map +1 -1
  235. package/dist/production/src/project/ProjectContainerStore.cjs.map +1 -1
  236. package/dist/production/src/project/ProjectContainerStore.js.map +1 -1
  237. package/dist/production/src/project/ProjectInitializer.cjs.map +1 -1
  238. package/dist/production/src/project/ProjectInitializer.js.map +1 -1
  239. package/dist/production/src/project/ProjectSchemaResolver.cjs.map +1 -1
  240. package/dist/production/src/project/ProjectSchemaResolver.js.map +1 -1
  241. package/dist/production/src/project-common/ProjectContextResolver.cjs +1 -0
  242. package/dist/production/src/project-common/ProjectContextResolver.cjs.map +1 -1
  243. package/dist/production/src/project-common/ProjectContextResolver.js +1 -0
  244. package/dist/production/src/project-common/ProjectContextResolver.js.map +1 -1
  245. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +17 -4
  246. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
  247. package/dist/production/src/projectGroup/ProjectGroupContainer.js +17 -4
  248. package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
  249. package/dist/production/src/projectGroup/ProjectGroupContainerResolver.cjs.map +1 -1
  250. package/dist/production/src/projectGroup/ProjectGroupContainerResolver.js.map +1 -1
  251. package/dist/production/src/projectGroup/ProjectGroupResolver.cjs +1 -0
  252. package/dist/production/src/projectGroup/ProjectGroupResolver.cjs.map +1 -1
  253. package/dist/production/src/projectGroup/ProjectGroupResolver.js +1 -0
  254. package/dist/production/src/projectGroup/ProjectGroupResolver.js.map +1 -1
  255. package/dist/production/src/prometheus/CollectHttpMetricsMiddelware.cjs.map +1 -1
  256. package/dist/production/src/prometheus/CollectHttpMetricsMiddelware.js.map +1 -1
  257. package/dist/production/src/prometheus/ProjectGroupContainerMetricsHook.cjs.map +1 -1
  258. package/dist/production/src/prometheus/ProjectGroupContainerMetricsHook.js.map +1 -1
  259. package/dist/production/src/prometheus/PrometheusRegistryFactory.cjs.map +1 -1
  260. package/dist/production/src/prometheus/PrometheusRegistryFactory.js.map +1 -1
  261. package/dist/production/src/prometheus/ShowMetricsMiddleware.cjs.map +1 -1
  262. package/dist/production/src/prometheus/ShowMetricsMiddleware.js.map +1 -1
  263. package/dist/production/src/prometheus/dbMetrics.cjs.map +1 -1
  264. package/dist/production/src/prometheus/dbMetrics.js.map +1 -1
  265. package/dist/production/src/system/ContentQueryExecutor.cjs.map +1 -1
  266. package/dist/production/src/system/ContentQueryExecutor.js.map +1 -1
  267. package/dist/production/src/system/SystemApiMiddlewareFactory.cjs +1 -0
  268. package/dist/production/src/system/SystemApiMiddlewareFactory.cjs.map +1 -1
  269. package/dist/production/src/system/SystemApiMiddlewareFactory.js +1 -0
  270. package/dist/production/src/system/SystemApiMiddlewareFactory.js.map +1 -1
  271. package/dist/production/src/system/SystemGraphQLContextFactory.cjs.map +1 -1
  272. package/dist/production/src/system/SystemGraphQLContextFactory.js.map +1 -1
  273. package/dist/production/src/system/SystemGraphQLHandlerFactory.cjs.map +1 -1
  274. package/dist/production/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
  275. package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs +46 -0
  276. package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs.map +1 -0
  277. package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js +46 -0
  278. package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js.map +1 -0
  279. package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs +8 -1
  280. package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
  281. package/dist/production/src/tenant/TenantApiMiddlewareFactory.js +8 -1
  282. package/dist/production/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
  283. package/dist/production/src/tenant/TenantGraphQLHandlerFactory.cjs.map +1 -1
  284. package/dist/production/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
  285. package/dist/production/src/testing/TestTransactions.cjs +144 -0
  286. package/dist/production/src/testing/TestTransactions.cjs.map +1 -0
  287. package/dist/production/src/testing/TestTransactions.js +144 -0
  288. package/dist/production/src/testing/TestTransactions.js.map +1 -0
  289. package/dist/production/src/transfer/CommandStream.cjs.map +1 -1
  290. package/dist/production/src/transfer/CommandStream.js.map +1 -1
  291. package/dist/production/src/transfer/ContentSchemaTransferMappingFactory.cjs.map +1 -1
  292. package/dist/production/src/transfer/ContentSchemaTransferMappingFactory.js.map +1 -1
  293. package/dist/production/src/transfer/ExportApiControllerFactory.cjs +1 -0
  294. package/dist/production/src/transfer/ExportApiControllerFactory.cjs.map +1 -1
  295. package/dist/production/src/transfer/ExportApiControllerFactory.js +1 -0
  296. package/dist/production/src/transfer/ExportApiControllerFactory.js.map +1 -1
  297. package/dist/production/src/transfer/ExportExecutor.cjs +4 -1
  298. package/dist/production/src/transfer/ExportExecutor.cjs.map +1 -1
  299. package/dist/production/src/transfer/ExportExecutor.js +4 -1
  300. package/dist/production/src/transfer/ExportExecutor.js.map +1 -1
  301. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +1 -0
  302. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  303. package/dist/production/src/transfer/ImportApiMiddlewareFactory.js +1 -0
  304. package/dist/production/src/transfer/ImportApiMiddlewareFactory.js.map +1 -1
  305. package/dist/production/src/transfer/ImportExecutor.cjs +7 -3
  306. package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
  307. package/dist/production/src/transfer/ImportExecutor.js +7 -3
  308. package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
  309. package/dist/production/src/transfer/SystemSchemaTransferMappingFactory.cjs.map +1 -1
  310. package/dist/production/src/transfer/SystemSchemaTransferMappingFactory.js.map +1 -1
  311. package/dist/production/src/utils/CryptoWrapper.cjs +4 -0
  312. package/dist/production/src/utils/CryptoWrapper.cjs.map +1 -1
  313. package/dist/production/src/utils/CryptoWrapper.js +4 -0
  314. package/dist/production/src/utils/CryptoWrapper.js.map +1 -1
  315. package/dist/production/src/utils/remoteAddress.cjs +5 -4
  316. package/dist/production/src/utils/remoteAddress.cjs.map +1 -1
  317. package/dist/production/src/utils/remoteAddress.js +5 -4
  318. package/dist/production/src/utils/remoteAddress.js.map +1 -1
  319. package/dist/production/src/utils/sentry.cjs.map +1 -1
  320. package/dist/production/src/utils/sentry.js.map +1 -1
  321. package/dist/production/src/utils/serverStartup.cjs +2 -2
  322. package/dist/production/src/utils/serverStartup.cjs.map +1 -1
  323. package/dist/production/src/utils/serverStartup.js.map +1 -1
  324. package/dist/tests/cases/unit/authenticatorGeoCountry.test.d.ts +2 -0
  325. package/dist/tests/cases/unit/authenticatorGeoCountry.test.d.ts.map +1 -0
  326. package/dist/tests/cases/unit/forceHttpOk.test.d.ts +2 -0
  327. package/dist/tests/cases/unit/forceHttpOk.test.d.ts.map +1 -0
  328. package/dist/tests/cases/unit/notFoundResponse.test.d.ts +2 -0
  329. package/dist/tests/cases/unit/notFoundResponse.test.d.ts.map +1 -0
  330. package/dist/tests/cases/unit/oidcBackchannelLogout.test.d.ts +2 -0
  331. package/dist/tests/cases/unit/oidcBackchannelLogout.test.d.ts.map +1 -0
  332. package/dist/tests/cases/unit/remoteAddress.test.d.ts +2 -0
  333. package/dist/tests/cases/unit/remoteAddress.test.d.ts.map +1 -0
  334. package/dist/tests/cases/unit/serverConfig.test.d.ts +2 -0
  335. package/dist/tests/cases/unit/serverConfig.test.d.ts.map +1 -0
  336. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  337. package/dist/types/MasterContainer.d.ts +34 -22
  338. package/dist/types/MasterContainer.d.ts.map +1 -1
  339. package/dist/types/application/application.d.ts +14 -5
  340. package/dist/types/application/application.d.ts.map +1 -1
  341. package/dist/types/application/forceHttpOk.d.ts +41 -0
  342. package/dist/types/application/forceHttpOk.d.ts.map +1 -0
  343. package/dist/types/application/index.d.ts +3 -2
  344. package/dist/types/application/index.d.ts.map +1 -1
  345. package/dist/types/bootstrap/Initializer.d.ts +1 -1
  346. package/dist/types/bootstrap/Initializer.d.ts.map +1 -1
  347. package/dist/types/bootstrap/index.d.ts +1 -1
  348. package/dist/types/bootstrap/index.d.ts.map +1 -1
  349. package/dist/types/common/Authorizator.d.ts +14 -3
  350. package/dist/types/common/Authorizator.d.ts.map +1 -1
  351. package/dist/types/common/ModuleInfoMiddleware.d.ts +1 -1
  352. package/dist/types/common/ModuleInfoMiddleware.d.ts.map +1 -1
  353. package/dist/types/common/NotFoundMiddleware.d.ts +8 -0
  354. package/dist/types/common/NotFoundMiddleware.d.ts.map +1 -0
  355. package/dist/types/common/index.d.ts +4 -3
  356. package/dist/types/common/index.d.ts.map +1 -1
  357. package/dist/types/config/ConfigProcessor.d.ts +1 -1
  358. package/dist/types/config/ConfigProcessor.d.ts.map +1 -1
  359. package/dist/types/config/config.d.ts +4 -4
  360. package/dist/types/config/config.d.ts.map +1 -1
  361. package/dist/types/config/configSchema.d.ts +37 -0
  362. package/dist/types/config/configSchema.d.ts.map +1 -1
  363. package/dist/types/config/configTemplate.d.ts.map +1 -1
  364. package/dist/types/config/projectConfigResolver.d.ts +3 -3
  365. package/dist/types/config/projectConfigResolver.d.ts.map +1 -1
  366. package/dist/types/config/tenantConfigResolver.d.ts +1 -1
  367. package/dist/types/config/tenantConfigResolver.d.ts.map +1 -1
  368. package/dist/types/content/ContentApiControllerFactory.d.ts +8 -6
  369. package/dist/types/content/ContentApiControllerFactory.d.ts.map +1 -1
  370. package/dist/types/content/ContentQueryHandlerFactory.d.ts +2 -2
  371. package/dist/types/content/ContentQueryHandlerFactory.d.ts.map +1 -1
  372. package/dist/types/content/GraphQLSchemaContributor.d.ts +2 -2
  373. package/dist/types/content/GraphQLSchemaContributor.d.ts.map +1 -1
  374. package/dist/types/content/GraphQlSchemaFactory.d.ts +4 -4
  375. package/dist/types/content/GraphQlSchemaFactory.d.ts.map +1 -1
  376. package/dist/types/content/NotModifiedChecker.d.ts +1 -1
  377. package/dist/types/content/NotModifiedChecker.d.ts.map +1 -1
  378. package/dist/types/content/ProjectMembershipResolver.d.ts +1 -1
  379. package/dist/types/content/ProjectMembershipResolver.d.ts.map +1 -1
  380. package/dist/types/content/index.d.ts +9 -9
  381. package/dist/types/content/index.d.ts.map +1 -1
  382. package/dist/types/content/triggeredActionsListener.d.ts +2 -2
  383. package/dist/types/content/triggeredActionsListener.d.ts.map +1 -1
  384. package/dist/types/graphql/dbQueriesListener.d.ts +1 -1
  385. package/dist/types/graphql/dbQueriesListener.d.ts.map +1 -1
  386. package/dist/types/graphql/index.d.ts +3 -3
  387. package/dist/types/graphql/index.d.ts.map +1 -1
  388. package/dist/types/index.d.ts +29 -28
  389. package/dist/types/index.d.ts.map +1 -1
  390. package/dist/types/misc/HomepageMiddlewareFactory.d.ts +1 -1
  391. package/dist/types/misc/HomepageMiddlewareFactory.d.ts.map +1 -1
  392. package/dist/types/misc/index.d.ts +1 -1
  393. package/dist/types/misc/index.d.ts.map +1 -1
  394. package/dist/types/plugin/Plugin.d.ts +4 -4
  395. package/dist/types/plugin/Plugin.d.ts.map +1 -1
  396. package/dist/types/project/ProjectContainer.d.ts +5 -5
  397. package/dist/types/project/ProjectContainer.d.ts.map +1 -1
  398. package/dist/types/project/ProjectContainerResolver.d.ts +3 -3
  399. package/dist/types/project/ProjectContainerResolver.d.ts.map +1 -1
  400. package/dist/types/project/ProjectContainerStore.d.ts +1 -1
  401. package/dist/types/project/ProjectContainerStore.d.ts.map +1 -1
  402. package/dist/types/project/ProjectInitializer.d.ts +1 -1
  403. package/dist/types/project/ProjectInitializer.d.ts.map +1 -1
  404. package/dist/types/project/ProjectSchemaResolver.d.ts +1 -1
  405. package/dist/types/project/ProjectSchemaResolver.d.ts.map +1 -1
  406. package/dist/types/project/config.d.ts +6 -0
  407. package/dist/types/project/config.d.ts.map +1 -1
  408. package/dist/types/project/index.d.ts +4 -4
  409. package/dist/types/project/index.d.ts.map +1 -1
  410. package/dist/types/project-common/ProjectContextResolver.d.ts +3 -3
  411. package/dist/types/project-common/ProjectContextResolver.d.ts.map +1 -1
  412. package/dist/types/project-common/index.d.ts +2 -2
  413. package/dist/types/project-common/index.d.ts.map +1 -1
  414. package/dist/types/projectGroup/ProjectGroupContainer.d.ts +13 -9
  415. package/dist/types/projectGroup/ProjectGroupContainer.d.ts.map +1 -1
  416. package/dist/types/projectGroup/ProjectGroupContainerResolver.d.ts +2 -2
  417. package/dist/types/projectGroup/ProjectGroupContainerResolver.d.ts.map +1 -1
  418. package/dist/types/projectGroup/ProjectGroupResolver.d.ts +3 -3
  419. package/dist/types/projectGroup/ProjectGroupResolver.d.ts.map +1 -1
  420. package/dist/types/prometheus/CollectHttpMetricsMiddelware.d.ts +4 -4
  421. package/dist/types/prometheus/CollectHttpMetricsMiddelware.d.ts.map +1 -1
  422. package/dist/types/prometheus/ProjectGroupContainerMetricsHook.d.ts +1 -1
  423. package/dist/types/prometheus/ProjectGroupContainerMetricsHook.d.ts.map +1 -1
  424. package/dist/types/prometheus/PrometheusRegistryFactory.d.ts +1 -1
  425. package/dist/types/prometheus/PrometheusRegistryFactory.d.ts.map +1 -1
  426. package/dist/types/prometheus/ShowMetricsMiddleware.d.ts +1 -1
  427. package/dist/types/prometheus/ShowMetricsMiddleware.d.ts.map +1 -1
  428. package/dist/types/prometheus/index.d.ts +2 -2
  429. package/dist/types/prometheus/index.d.ts.map +1 -1
  430. package/dist/types/system/SystemApiMiddlewareFactory.d.ts +3 -3
  431. package/dist/types/system/SystemApiMiddlewareFactory.d.ts.map +1 -1
  432. package/dist/types/system/SystemGraphQLContextFactory.d.ts +3 -3
  433. package/dist/types/system/SystemGraphQLContextFactory.d.ts.map +1 -1
  434. package/dist/types/system/SystemGraphQLHandlerFactory.d.ts +1 -1
  435. package/dist/types/system/SystemGraphQLHandlerFactory.d.ts.map +1 -1
  436. package/dist/types/system/index.d.ts +3 -3
  437. package/dist/types/system/index.d.ts.map +1 -1
  438. package/dist/types/tenant/OidcBackchannelLogoutMiddlewareFactory.d.ts +18 -0
  439. package/dist/types/tenant/OidcBackchannelLogoutMiddlewareFactory.d.ts.map +1 -0
  440. package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts +1 -1
  441. package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts.map +1 -1
  442. package/dist/types/tenant/TenantGraphQLHandlerFactory.d.ts +1 -1
  443. package/dist/types/tenant/TenantGraphQLHandlerFactory.d.ts.map +1 -1
  444. package/dist/types/tenant/index.d.ts +3 -2
  445. package/dist/types/tenant/index.d.ts.map +1 -1
  446. package/dist/types/testing/TestTransactions.d.ts +22 -0
  447. package/dist/types/testing/TestTransactions.d.ts.map +1 -0
  448. package/dist/types/testing/index.d.ts +2 -0
  449. package/dist/types/testing/index.d.ts.map +1 -0
  450. package/dist/types/transfer/CommandStream.d.ts +1 -1
  451. package/dist/types/transfer/CommandStream.d.ts.map +1 -1
  452. package/dist/types/transfer/ContentSchemaTransferMappingFactory.d.ts +1 -1
  453. package/dist/types/transfer/ContentSchemaTransferMappingFactory.d.ts.map +1 -1
  454. package/dist/types/transfer/ExportApiControllerFactory.d.ts +3 -3
  455. package/dist/types/transfer/ExportApiControllerFactory.d.ts.map +1 -1
  456. package/dist/types/transfer/ExportExecutor.d.ts +4 -4
  457. package/dist/types/transfer/ExportExecutor.d.ts.map +1 -1
  458. package/dist/types/transfer/ImportApiMiddlewareFactory.d.ts +3 -3
  459. package/dist/types/transfer/ImportApiMiddlewareFactory.d.ts.map +1 -1
  460. package/dist/types/transfer/ImportExecutor.d.ts +6 -6
  461. package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
  462. package/dist/types/transfer/SystemSchemaTransferMappingFactory.d.ts +1 -1
  463. package/dist/types/transfer/SystemSchemaTransferMappingFactory.d.ts.map +1 -1
  464. package/dist/types/transfer/index.d.ts +6 -6
  465. package/dist/types/transfer/index.d.ts.map +1 -1
  466. package/dist/types/tsconfig.tsbuildinfo +1 -1
  467. package/dist/types/utils/CryptoWrapper.d.ts +2 -0
  468. package/dist/types/utils/CryptoWrapper.d.ts.map +1 -1
  469. package/dist/types/utils/remoteAddress.d.ts.map +1 -1
  470. package/dist/types/utils/serverStartup.d.ts +4 -4
  471. package/dist/types/utils/serverStartup.d.ts.map +1 -1
  472. package/dist/types/workers/index.d.ts +1 -1
  473. package/dist/types/workers/index.d.ts.map +1 -1
  474. package/package.json +15 -15
  475. package/src/MasterContainer.ts +75 -27
  476. package/src/application/application.ts +44 -13
  477. package/src/application/forceHttpOk.ts +70 -0
  478. package/src/application/index.ts +3 -2
  479. package/src/bootstrap/Initializer.ts +1 -1
  480. package/src/bootstrap/index.ts +1 -1
  481. package/src/common/Authorizator.ts +93 -5
  482. package/src/common/ModuleInfoMiddleware.ts +1 -1
  483. package/src/common/NotFoundMiddleware.ts +18 -0
  484. package/src/common/index.ts +4 -3
  485. package/src/config/ConfigProcessor.ts +1 -1
  486. package/src/config/config.ts +5 -5
  487. package/src/config/configSchema.ts +67 -1
  488. package/src/config/configTemplate.ts +11 -0
  489. package/src/config/projectConfigResolver.ts +4 -4
  490. package/src/config/tenantConfigResolver.ts +2 -2
  491. package/src/content/ContentApiControllerFactory.ts +43 -10
  492. package/src/content/ContentQueryHandlerFactory.ts +3 -3
  493. package/src/content/ContentSchemaResolver.ts +2 -2
  494. package/src/content/GraphQLSchemaContributor.ts +2 -2
  495. package/src/content/GraphQlSchemaFactory.ts +4 -4
  496. package/src/content/NotModifiedChecker.ts +1 -1
  497. package/src/content/ProjectMembershipResolver.ts +2 -2
  498. package/src/content/index.ts +9 -9
  499. package/src/content/triggeredActionsListener.ts +2 -2
  500. package/src/graphql/dbQueriesListener.ts +1 -1
  501. package/src/graphql/index.ts +3 -3
  502. package/src/index.ts +28 -27
  503. package/src/misc/HomepageMiddlewareFactory.ts +2 -2
  504. package/src/misc/index.ts +1 -1
  505. package/src/plugin/Plugin.ts +4 -4
  506. package/src/project/ProjectContainer.ts +6 -6
  507. package/src/project/ProjectContainerResolver.ts +4 -4
  508. package/src/project/ProjectContainerStore.ts +1 -1
  509. package/src/project/ProjectInitializer.ts +1 -1
  510. package/src/project/ProjectSchemaResolver.ts +1 -1
  511. package/src/project/config.ts +6 -0
  512. package/src/project/index.ts +4 -4
  513. package/src/project-common/ProjectContextResolver.ts +2 -2
  514. package/src/project-common/index.ts +2 -2
  515. package/src/projectGroup/ProjectGroupContainer.ts +34 -11
  516. package/src/projectGroup/ProjectGroupContainerResolver.ts +2 -2
  517. package/src/projectGroup/ProjectGroupResolver.ts +4 -4
  518. package/src/prometheus/CollectHttpMetricsMiddelware.ts +4 -4
  519. package/src/prometheus/ProjectGroupContainerMetricsHook.ts +2 -2
  520. package/src/prometheus/PrometheusRegistryFactory.ts +2 -2
  521. package/src/prometheus/ShowMetricsMiddleware.ts +1 -1
  522. package/src/prometheus/dbMetrics.ts +1 -1
  523. package/src/prometheus/index.ts +2 -2
  524. package/src/system/ContentQueryExecutor.ts +2 -2
  525. package/src/system/SystemApiMiddlewareFactory.ts +5 -5
  526. package/src/system/SystemGraphQLContextFactory.ts +3 -3
  527. package/src/system/SystemGraphQLHandlerFactory.ts +1 -1
  528. package/src/system/index.ts +3 -3
  529. package/src/tenant/OidcBackchannelLogoutMiddlewareFactory.ts +63 -0
  530. package/src/tenant/TenantApiMiddlewareFactory.ts +10 -4
  531. package/src/tenant/TenantGraphQLHandlerFactory.ts +1 -1
  532. package/src/tenant/index.ts +3 -2
  533. package/src/testing/TestTransactions.ts +237 -0
  534. package/src/testing/index.ts +1 -0
  535. package/src/transfer/CommandStream.ts +2 -2
  536. package/src/transfer/ContentSchemaTransferMappingFactory.ts +1 -1
  537. package/src/transfer/ExportApiControllerFactory.ts +6 -6
  538. package/src/transfer/ExportExecutor.ts +12 -6
  539. package/src/transfer/ImportApiMiddlewareFactory.ts +5 -5
  540. package/src/transfer/ImportExecutor.ts +12 -9
  541. package/src/transfer/SystemSchemaTransferMappingFactory.ts +2 -2
  542. package/src/transfer/index.ts +6 -6
  543. package/src/utils/CryptoWrapper.ts +5 -0
  544. package/src/utils/remoteAddress.ts +3 -1
  545. package/src/utils/sentry.ts +1 -1
  546. package/src/utils/serverStartup.ts +3 -3
  547. package/src/workers/index.ts +1 -1
  548. package/tests/cases/unit/authenticatorGeoCountry.test.ts +100 -0
  549. package/tests/cases/unit/configResolver.test.ts +33 -3
  550. package/tests/cases/unit/crypto.test.ts +1 -1
  551. package/tests/cases/unit/forceHttpOk.test.ts +92 -0
  552. package/tests/cases/unit/notFoundResponse.test.ts +39 -0
  553. package/tests/cases/unit/oidcBackchannelLogout.test.ts +113 -0
  554. package/tests/cases/unit/projectMembershipResolver.test.ts +2 -2
  555. package/tests/cases/unit/remoteAddress.test.ts +90 -0
  556. package/tests/cases/unit/serverConfig.test.ts +70 -0
@@ -1 +1 @@
1
- {"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["logger","module","WebSocketServer","http","getClientIP","URL","HttpErrorResponse","ws","performance","HttpResponse","remoteAddress","FingerCrossedLoggerHandler","cpuUsage","memoryUsage","Readable","pathToRegexp","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,MAAM,YAAY;AAAA,EASxB,YACkB,sBACA,cACA,WACA,SACAA,SAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAAA;AAblB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AASP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAAA,EAC3H;AAAA,EAEA,cAAc,YAAgC;AAC7C,SAAK,YAAY,KAAK,UAAU;AAAA,EACjC;AAAA,EAEO,SAASC,SAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB,QAAAA;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EACF;AAAA,EAEO,iBAAiBA,SAAgB,MAAc,YAA0C;AAC/F,SAAK,eAAe,KAAK;AAAA,MACxB,QAAAA;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EACF;AAAA,EAEO,kBAAkBA,SAAgB,MAAc,YAAuC;AAC7F,SAAK,gBAAgB,KAAK;AAAA,MACzB,QAAAA;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EACF;AAAA,EAEA,MAAM,SAAsC;AAC3C,UAAM,MAAM,IAAI,IAAA;AAChB,UAAM,M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AAED,oBAAY,KAAK,IAAI,EAAE,MAAM,IAAI;AAAA,MAClC,OAAO;AACN,aAAA;AAAA,MACD;AAAA,IACD;AACA,WAAO,EAAE,OAAO,KAAA;AAAA,EACjB;AAAA,EAEQ,aAAgB,QAAoB,KAAoC;AAC/E,eAAW,SAAS,QAAQ;AAC3B,YAAM,SAAS,MAAM,MAAM,EAAE,KAAK;AAClC,UAAI,WAAW,MAAM;AACpB,eAAO,EAAE,QAAQ,YAAY,MAAM,YAAY,QAAQ,MAAM,OAAA;AAAA,MAC9D;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAyDA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,EAAE,QAAQ,SAASC,aAAAA,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;;;"}
1
+ {"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["logger","module","WebSocketServer","http","getClientIP","URL","HttpErrorResponse","ws","performance","HttpResponse","shouldForceHttpOk","isForceHttpOkRequested","remoteAddress","FingerCrossedLoggerHandler","cpuUsage","memoryUsage","Readable","pathToRegexp","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBO,MAAM,YAAY;AAAA,EAWxB,YACkB,sBACA,cACA,WACA,SACAA,SAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAAA;AAflB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AACR,kBAAA,MAAQ,gBAAA;AACR,kBAAA,MAAQ,oBAAA;AASP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAC1H,SAAK,iBAAiB,aAAa,MAAM,kBAAkB,CAAA;AAC3D,SAAK,qBAAqB,aAAa,MAAM,wBAAwB;AAAA,EACtE;AAAA,EAEA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AAO;AACN,aAAA;AAAA,MACD;AAAA,IACD;AACA,WAAO,EAAE,OAAO,KAAA;AAAA,EACjB;AAAA,EAEQ,aAAgB,QAAoB,KAAoC;AAC/E,eAAW,SAAS,QAAQ;AAC3B,YAAM,SAAS,MAAM,MAAM,EAAE,KAAK;AAClC,UAAI,WAAW,MAAM;AACpB,eAAO,EAAE,QAAQ,YAAY,MAAM,YAAY,QAAQ,MAAM,OAAA;AAAA,MAC9D;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAyDA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,EAAE,QAAQ,SAASC,aAAAA,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;;;"}
@@ -1,5 +1,6 @@
1
1
  import { pathToRegexp } from "path-to-regexp";
2
2
  import { HttpErrorResponse, HttpResponse } from "../common/HttpResponse.js";
3
+ import "ipaddr.js";
3
4
  import Koa from "koa";
4
5
  import * as http from "node:http";
5
6
  import { WebSocketServer } from "ws";
@@ -12,6 +13,7 @@ import { URL } from "node:url";
12
13
  import { cpuUsage, memoryUsage } from "node:process";
13
14
  import { performance } from "node:perf_hooks";
14
15
  import { getClientIP } from "../utils/remoteAddress.js";
16
+ import { shouldForceHttpOk, isForceHttpOkRequested } from "./forceHttpOk.js";
15
17
  var __defProp = Object.defineProperty;
16
18
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
17
19
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
@@ -27,8 +29,12 @@ class Application {
27
29
  __publicField(this, "internalRoutes", []);
28
30
  __publicField(this, "websocketRoutes", []);
29
31
  __publicField(this, "suppressAccessLog");
32
+ __publicField(this, "trustedProxies");
33
+ __publicField(this, "forceHttpOkEnabled");
30
34
  const suppressAccessLogRaw = serverConfig.http?.suppressAccessLog;
31
35
  this.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false;
36
+ this.trustedProxies = serverConfig.http?.trustedProxies ?? [];
37
+ this.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true;
32
38
  }
33
39
  addMiddleware(middleware) {
34
40
  this.middlewares.push(middleware);
@@ -95,7 +101,7 @@ class Application {
95
101
  let webSocketContext = null;
96
102
  let requestLogger = this.logger;
97
103
  const { timer, send: sendTimer } = this.createTimer();
98
- const clientIp = getClientIP(req);
104
+ const clientIp = getClientIP(req, this.trustedProxies);
99
105
  try {
100
106
  const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
101
107
  const matchedRequest = this.matchRequest(this.websocketRoutes, url);
@@ -107,11 +113,12 @@ class Application {
107
113
  requestLogger = requestLogger.child({
108
114
  projectGroup: groupContainer.slug
109
115
  });
110
- const authResult = await groupContainer.authenticator.authenticate({ request: req, timer });
116
+ const authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp });
111
117
  requestLogger.debug("User authenticated", { authResult });
112
118
  requestLogger = requestLogger.child({
113
119
  user: authResult?.identityId
114
120
  });
121
+ const effectiveClientIp = authResult?.clientIp ?? clientIp;
115
122
  const ws = await new Promise(
116
123
  (resolve) => wss.handleUpgrade(req, socket, head, (ws2, request) => {
117
124
  resolve(ws2);
@@ -125,7 +132,7 @@ class Application {
125
132
  timer,
126
133
  url,
127
134
  request: req,
128
- clientIp,
135
+ clientIp: effectiveClientIp,
129
136
  authResult,
130
137
  params: matchedRequest.params,
131
138
  projectGroup: groupContainer
@@ -170,7 +177,7 @@ class Application {
170
177
  }
171
178
  }
172
179
  let httpContext = null;
173
- const clientIp = getClientIP(ctx.req);
180
+ const clientIp = getClientIP(ctx.req, this.trustedProxies);
174
181
  let requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp);
175
182
  const { timer, send: sendTimer } = this.createTimer();
176
183
  try {
@@ -188,17 +195,18 @@ class Application {
188
195
  });
189
196
  ctx.state.projectGroup = groupContainer.slug;
190
197
  ctx.state.project = matchedRequest.params.projectSlug;
191
- const authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer });
198
+ const authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp });
192
199
  requestLogger.debug("User authenticated", { authResult });
193
200
  requestLogger = requestLogger.child({
194
201
  user: authResult?.identityId
195
202
  });
203
+ const effectiveClientIp = authResult?.clientIp ?? clientIp;
196
204
  const response = await requestLogger.scope(async (logger) => {
197
205
  httpContext = {
198
206
  koa: ctx,
199
207
  body: ctx.request.body,
200
208
  url: ctx.request.URL,
201
- clientIp,
209
+ clientIp: effectiveClientIp,
202
210
  logger,
203
211
  timer,
204
212
  request: ctx.req,
@@ -221,6 +229,7 @@ class Application {
221
229
  requestLogger.error(e);
222
230
  }
223
231
  } finally {
232
+ this.maybeForceHttpOk(ctx, matchedRequest?.module);
224
233
  sendTimer({
225
234
  req: ctx.req,
226
235
  response: ctx.res,
@@ -236,7 +245,7 @@ class Application {
236
245
  const response = await this.logger.scope(async (logger) => {
237
246
  return await matchedRequest.controller({
238
247
  koa: ctx,
239
- clientIp: getClientIP(ctx.req),
248
+ clientIp: getClientIP(ctx.req, this.trustedProxies),
240
249
  body: ctx.request.body,
241
250
  url: ctx.request.URL,
242
251
  logger,
@@ -257,6 +266,26 @@ class Application {
257
266
  }
258
267
  }
259
268
  }
269
+ /**
270
+ * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),
271
+ * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the
272
+ * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses
273
+ * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.
274
+ */
275
+ maybeForceHttpOk(ctx, module) {
276
+ const coerce = shouldForceHttpOk({
277
+ enabled: this.forceHttpOkEnabled,
278
+ status: ctx.status,
279
+ module,
280
+ hasBody: ctx.body !== void 0 && ctx.body !== null,
281
+ headerRequested: isForceHttpOkRequested(ctx.req)
282
+ });
283
+ if (!coerce) {
284
+ return;
285
+ }
286
+ ctx.set("X-Contember-Original-Status", String(ctx.status));
287
+ ctx.status = 200;
288
+ }
260
289
  sendHttpResponse(ctx, response) {
261
290
  if (response.contentType) {
262
291
  ctx.set("Content-type", response.contentType);
@@ -1 +1 @@
1
- {"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["ws","match"],"mappings":";;;;;;;;;;;;;;;;;AAqBO,MAAM,YAAY;AAAA,EASxB,YACkB,sBACA,cACA,WACA,SACA,QAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AAblB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AASP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAAA,EAC3H;AAAA,EAEA,cAAc,YAAgC;AAC7C,SAAK,YAAY,KAAK,UAAU;AAAA,EACjC;AAAA,EAEO,SAAS,QAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EACF;AAAA,EAEO,iBAAiB,QAAgB,MAAc,YAA0C;AAC/F,SAAK,eAAe,KAAK;AAAA,MACxB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAA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AE,MAAM,IAAI;AAAA,MAClC,OAAO;AACN,aAAA;AAAA,MACD;AAAA,IACD;AACA,WAAO,EAAE,OAAO,KAAA;AAAA,EACjB;AAAA,EAEQ,aAAgB,QAAoB,KAAoC;AAC/E,eAAW,SAAS,QAAQ;AAC3B,YAAM,SAAS,MAAM,MAAM,EAAE,KAAK;AAClC,UAAI,WAAW,MAAM;AACpB,eAAO,EAAE,QAAQ,YAAY,MAAM,YAAY,QAAQ,MAAM,OAAA;AAAA,MAC9D;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAyDA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,EAAE,QAAQ,SAAS,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;"}
1
+ {"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["ws","match"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBO,MAAM,YAAY;AAAA,EAWxB,YACkB,sBACA,cACA,WACA,SACA,QAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AAflB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AACR,kBAAA,MAAQ,gBAAA;AACR,kBAAA,MAAQ,oBAAA;AASP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAC1H,SAAK,iBAAiB,aAAa,MAAM,kBAAkB,CAAA;AAC3D,SAAK,qBAAqB,aAAa,MAAM,wBAAwB;AAAA,EACtE;AAAA,EAEA,cAAc,YAAgC;AAC7C,SAAK,YAAY,KAAK,UAAU;AAAA,EACjC;AAAA,EAEO,SAAS,QAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EAC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AE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;"}
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const forceHttpOkHeader = "x-contember-force-ok";
4
+ const graphqlModules = /* @__PURE__ */ new Set(["content", "tenant", "system"]);
5
+ const truthyValues = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
6
+ const isForceHttpOkRequested = (request) => {
7
+ const raw = request.headers[forceHttpOkHeader];
8
+ const value = Array.isArray(raw) ? raw[0] : raw;
9
+ if (value === void 0) {
10
+ return false;
11
+ }
12
+ return truthyValues.has(value.trim().toLowerCase());
13
+ };
14
+ const isGraphqlModule = (module2) => module2 !== void 0 && graphqlModules.has(module2);
15
+ const shouldForceHttpOk = ({ enabled, status, module: module2, hasBody, headerRequested }) => {
16
+ if (!enabled) {
17
+ return false;
18
+ }
19
+ if (status === 200) {
20
+ return false;
21
+ }
22
+ if (!isGraphqlModule(module2)) {
23
+ return false;
24
+ }
25
+ if (!hasBody) {
26
+ return false;
27
+ }
28
+ return headerRequested;
29
+ };
30
+ exports.forceHttpOkHeader = forceHttpOkHeader;
31
+ exports.isForceHttpOkRequested = isForceHttpOkRequested;
32
+ exports.isGraphqlModule = isGraphqlModule;
33
+ exports.shouldForceHttpOk = shouldForceHttpOk;
34
+ //# sourceMappingURL=forceHttpOk.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"forceHttpOk.cjs","sources":["../../../../../packages/engine-http/src/application/forceHttpOk.ts"],"sourcesContent":["import { IncomingMessage } from 'node:http'\n\n/**\n * Opt-in mechanism to coerce the HTTP status of a GraphQL API response to 200.\n *\n * Some GraphQL clients cannot properly handle non-200 HTTP status codes (e.g. on\n * authentication failure). When a request carries the `X-Contember-Force-Ok` header\n * with a truthy value, the response status is forced to 200 while the error information\n * remains in the JSON body.\n *\n * This is scoped to the GraphQL API endpoints (content/tenant/system) where a JSON body\n * with `errors`/`data` is returned, so that fatal/non-JSON responses are not mislabeled.\n *\n * The capability can be disabled globally via the `http.responseStatusHeader` config flag.\n */\nexport const forceHttpOkHeader = 'x-contember-force-ok'\n\nconst graphqlModules = new Set(['content', 'tenant', 'system'])\n\nconst truthyValues = new Set(['1', 'true', 'on', 'yes'])\n\nexport const isForceHttpOkRequested = (request: IncomingMessage): boolean => {\n\tconst raw = request.headers[forceHttpOkHeader]\n\tconst value = Array.isArray(raw) ? raw[0] : raw\n\tif (value === undefined) {\n\t\treturn false\n\t}\n\treturn truthyValues.has(value.trim().toLowerCase())\n}\n\nexport const isGraphqlModule = (module: string | undefined): boolean => module !== undefined && graphqlModules.has(module)\n\nexport interface ForceHttpOkDecisionInput {\n\t/** Whether the capability is enabled in config (http.responseStatusHeader). */\n\tenabled: boolean\n\t/** The current HTTP response status. */\n\tstatus: number\n\t/** The matched route module, if any. */\n\tmodule: string | undefined\n\t/** Whether the response carries a (JSON) body. */\n\thasBody: boolean\n\t/** Whether the client requested coercion via the X-Contember-Force-Ok header. */\n\theaderRequested: boolean\n}\n\n/**\n * Pure decision for whether a response status should be coerced to 200.\n *\n * Coercion happens only when ALL of the following hold:\n * - the capability is enabled in config (kill-switch off),\n * - the status is not already 200,\n * - the matched module is a GraphQL API module (content/tenant/system),\n * - the response has a body (so non-JSON / transport responses are not mislabeled),\n * - the client opted in via the X-Contember-Force-Ok header.\n */\nexport const shouldForceHttpOk = ({ enabled, status, module, hasBody, headerRequested }: ForceHttpOkDecisionInput): boolean => {\n\tif (!enabled) {\n\t\treturn false\n\t}\n\tif (status === 200) {\n\t\treturn false\n\t}\n\tif (!isGraphqlModule(module)) {\n\t\treturn false\n\t}\n\tif (!hasBody) {\n\t\treturn false\n\t}\n\treturn headerRequested\n}\n"],"names":["module"],"mappings":";;AAeO,MAAM,oBAAoB;AAEjC,MAAM,iBAAiB,oBAAI,IAAI,CAAC,WAAW,UAAU,QAAQ,CAAC;AAE9D,MAAM,mCAAmB,IAAI,CAAC,KAAK,QAAQ,MAAM,KAAK,CAAC;AAEhD,MAAM,yBAAyB,CAAC,YAAsC;AAC5E,QAAM,MAAM,QAAQ,QAAQ,iBAAiB;AAC7C,QAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,IAAI;AAC5C,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA,EACR;AACA,SAAO,aAAa,IAAI,MAAM,KAAA,EAAO,aAAa;AACnD;AAEO,MAAM,kBAAkB,CAACA,YAAwCA,YAAW,UAAa,eAAe,IAAIA,OAAM;AAyBlH,MAAM,oBAAoB,CAAC,EAAE,SAAS,QAAQ,QAAAA,SAAQ,SAAS,sBAAyD;AAC9H,MAAI,CAAC,SAAS;AACb,WAAO;AAAA,EACR;AACA,MAAI,WAAW,KAAK;AACnB,WAAO;AAAA,EACR;AACA,MAAI,CAAC,gBAAgBA,OAAM,GAAG;AAC7B,WAAO;AAAA,EACR;AACA,MAAI,CAAC,SAAS;AACb,WAAO;AAAA,EACR;AACA,SAAO;AACR;;;;;"}
@@ -0,0 +1,34 @@
1
+ const forceHttpOkHeader = "x-contember-force-ok";
2
+ const graphqlModules = /* @__PURE__ */ new Set(["content", "tenant", "system"]);
3
+ const truthyValues = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
4
+ const isForceHttpOkRequested = (request) => {
5
+ const raw = request.headers[forceHttpOkHeader];
6
+ const value = Array.isArray(raw) ? raw[0] : raw;
7
+ if (value === void 0) {
8
+ return false;
9
+ }
10
+ return truthyValues.has(value.trim().toLowerCase());
11
+ };
12
+ const isGraphqlModule = (module) => module !== void 0 && graphqlModules.has(module);
13
+ const shouldForceHttpOk = ({ enabled, status, module, hasBody, headerRequested }) => {
14
+ if (!enabled) {
15
+ return false;
16
+ }
17
+ if (status === 200) {
18
+ return false;
19
+ }
20
+ if (!isGraphqlModule(module)) {
21
+ return false;
22
+ }
23
+ if (!hasBody) {
24
+ return false;
25
+ }
26
+ return headerRequested;
27
+ };
28
+ export {
29
+ forceHttpOkHeader,
30
+ isForceHttpOkRequested,
31
+ isGraphqlModule,
32
+ shouldForceHttpOk
33
+ };
34
+ //# sourceMappingURL=forceHttpOk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"forceHttpOk.js","sources":["../../../../../packages/engine-http/src/application/forceHttpOk.ts"],"sourcesContent":["import { IncomingMessage } from 'node:http'\n\n/**\n * Opt-in mechanism to coerce the HTTP status of a GraphQL API response to 200.\n *\n * Some GraphQL clients cannot properly handle non-200 HTTP status codes (e.g. on\n * authentication failure). When a request carries the `X-Contember-Force-Ok` header\n * with a truthy value, the response status is forced to 200 while the error information\n * remains in the JSON body.\n *\n * This is scoped to the GraphQL API endpoints (content/tenant/system) where a JSON body\n * with `errors`/`data` is returned, so that fatal/non-JSON responses are not mislabeled.\n *\n * The capability can be disabled globally via the `http.responseStatusHeader` config flag.\n */\nexport const forceHttpOkHeader = 'x-contember-force-ok'\n\nconst graphqlModules = new Set(['content', 'tenant', 'system'])\n\nconst truthyValues = new Set(['1', 'true', 'on', 'yes'])\n\nexport const isForceHttpOkRequested = (request: IncomingMessage): boolean => {\n\tconst raw = request.headers[forceHttpOkHeader]\n\tconst value = Array.isArray(raw) ? raw[0] : raw\n\tif (value === undefined) {\n\t\treturn false\n\t}\n\treturn truthyValues.has(value.trim().toLowerCase())\n}\n\nexport const isGraphqlModule = (module: string | undefined): boolean => module !== undefined && graphqlModules.has(module)\n\nexport interface ForceHttpOkDecisionInput {\n\t/** Whether the capability is enabled in config (http.responseStatusHeader). */\n\tenabled: boolean\n\t/** The current HTTP response status. */\n\tstatus: number\n\t/** The matched route module, if any. */\n\tmodule: string | undefined\n\t/** Whether the response carries a (JSON) body. */\n\thasBody: boolean\n\t/** Whether the client requested coercion via the X-Contember-Force-Ok header. */\n\theaderRequested: boolean\n}\n\n/**\n * Pure decision for whether a response status should be coerced to 200.\n *\n * Coercion happens only when ALL of the following hold:\n * - the capability is enabled in config (kill-switch off),\n * - the status is not already 200,\n * - the matched module is a GraphQL API module (content/tenant/system),\n * - the response has a body (so non-JSON / transport responses are not mislabeled),\n * - the client opted in via the X-Contember-Force-Ok header.\n */\nexport const shouldForceHttpOk = ({ enabled, status, module, hasBody, headerRequested }: ForceHttpOkDecisionInput): boolean => {\n\tif (!enabled) {\n\t\treturn false\n\t}\n\tif (status === 200) {\n\t\treturn false\n\t}\n\tif (!isGraphqlModule(module)) {\n\t\treturn false\n\t}\n\tif (!hasBody) {\n\t\treturn false\n\t}\n\treturn headerRequested\n}\n"],"names":[],"mappings":"AAeO,MAAM,oBAAoB;AAEjC,MAAM,iBAAiB,oBAAI,IAAI,CAAC,WAAW,UAAU,QAAQ,CAAC;AAE9D,MAAM,mCAAmB,IAAI,CAAC,KAAK,QAAQ,MAAM,KAAK,CAAC;AAEhD,MAAM,yBAAyB,CAAC,YAAsC;AAC5E,QAAM,MAAM,QAAQ,QAAQ,iBAAiB;AAC7C,QAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,IAAI;AAC5C,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA,EACR;AACA,SAAO,aAAa,IAAI,MAAM,KAAA,EAAO,aAAa;AACnD;AAEO,MAAM,kBAAkB,CAAC,WAAwC,WAAW,UAAa,eAAe,IAAI,MAAM;AAyBlH,MAAM,oBAAoB,CAAC,EAAE,SAAS,QAAQ,QAAQ,SAAS,sBAAyD;AAC9H,MAAI,CAAC,SAAS;AACb,WAAO;AAAA,EACR;AACA,MAAI,WAAW,KAAK;AACnB,WAAO;AAAA,EACR;AACA,MAAI,CAAC,gBAAgB,MAAM,GAAG;AAC7B,WAAO;AAAA,EACR;AACA,MAAI,CAAC,SAAS;AACb,WAAO;AAAA,EACR;AACA,SAAO;AACR;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Initializer.cjs","sources":["../../../../../packages/engine-http/src/bootstrap/Initializer.ts"],"sourcesContent":["import { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\n\nexport class Initializer {\n\tconstructor(\n\t\tprivate readonly projectGroupContainer: ProjectGroupContainer,\n\t) {}\n\n\tpublic async initialize(): Promise<string[]> {\n\t\tconst groupContainer = await this.projectGroupContainer\n\t\tconst tenantMigrationsLogger = groupContainer.logger.child()\n\t\tconst tenantContainer = groupContainer.tenantContainer\n\t\tawait tenantContainer.migrationsRunner.run(tenantMigrationsLogger)\n\n\t\tconst projects: string[] = []\n\n\t\tconst tenantProjects = await tenantContainer.projectManager.getProjects(tenantContainer.databaseContext)\n\t\tfor (const { slug: projectSlug } of tenantProjects) {\n\t\t\tconst projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(projectSlug, { alias: false })\n\t\t\tif (!projectContainer) {\n\t\t\t\tthrow new Error()\n\t\t\t}\n\t\t\tconst project = projectContainer.project\n\t\t\tprojects.push(project.slug)\n\t\t}\n\t\treturn projects\n\t}\n}\n"],"names":[],"mappings":";;AAEO,MAAM,YAAY;AAAA,EACxB,YACkB,uBAChB;AADgB,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAa,aAAgC;AAC5C,UAAM,iBAAiB,MAAM,KAAK;AAClC,UAAM,yBAAyB,eAAe,OAAO,MAAA;AACrD,UAAM,kBAAkB,eAAe;AACvC,UAAM,gBAAgB,iBAAiB,IAAI,sBAAsB;AAEjE,UAAM,WAAqB,CAAA;AAE3B,UAAM,iBAAiB,MAAM,gBAAgB,eAAe,YAAY,gBAAgB,eAAe;AACvG,eAAW,EAAE,MAAM,YAAA,KAAiB,gBAAgB;AACnD,YAAM,mBAAmB,MAAM,eAAe,yBAAyB,oBAAoB,aAAa,EAAE,OAAO,OAAO;AACxH,UAAI,CAAC,kBAAkB;AACtB,cAAM,IAAI,MAAA;AAAA,MACX;AACA,YAAM,UAAU,iBAAiB;AACjC,eAAS,KAAK,QAAQ,IAAI;AAAA,IAC3B;AACA,WAAO;AAAA,EACR;AACD;;"}
1
+ {"version":3,"file":"Initializer.cjs","sources":["../../../../../packages/engine-http/src/bootstrap/Initializer.ts"],"sourcesContent":["import { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\n\nexport class Initializer {\n\tconstructor(\n\t\tprivate readonly projectGroupContainer: ProjectGroupContainer,\n\t) {}\n\n\tpublic async initialize(): Promise<string[]> {\n\t\tconst groupContainer = await this.projectGroupContainer\n\t\tconst tenantMigrationsLogger = groupContainer.logger.child()\n\t\tconst tenantContainer = groupContainer.tenantContainer\n\t\tawait tenantContainer.migrationsRunner.run(tenantMigrationsLogger)\n\n\t\tconst projects: string[] = []\n\n\t\tconst tenantProjects = await tenantContainer.projectManager.getProjects(tenantContainer.databaseContext)\n\t\tfor (const { slug: projectSlug } of tenantProjects) {\n\t\t\tconst projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(projectSlug, { alias: false })\n\t\t\tif (!projectContainer) {\n\t\t\t\tthrow new Error()\n\t\t\t}\n\t\t\tconst project = projectContainer.project\n\t\t\tprojects.push(project.slug)\n\t\t}\n\t\treturn projects\n\t}\n}\n"],"names":[],"mappings":";;AAEO,MAAM,YAAY;AAAA,EACxB,YACkB,uBAChB;AADgB,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAa,aAAgC;AAC5C,UAAM,iBAAiB,MAAM,KAAK;AAClC,UAAM,yBAAyB,eAAe,OAAO,MAAA;AACrD,UAAM,kBAAkB,eAAe;AACvC,UAAM,gBAAgB,iBAAiB,IAAI,sBAAsB;AAEjE,UAAM,WAAqB,CAAA;AAE3B,UAAM,iBAAiB,MAAM,gBAAgB,eAAe,YAAY,gBAAgB,eAAe;AACvG,eAAW,EAAE,MAAM,YAAA,KAAiB,gBAAgB;AACnD,YAAM,mBAAmB,MAAM,eAAe,yBAAyB,oBAAoB,aAAa,EAAE,OAAO,OAAO;AACxH,UAAI,CAAC,kBAAkB;AACtB,cAAM,IAAI,MAAA;AAAA,MACX;AACA,YAAM,UAAU,iBAAiB;AACjC,eAAS,KAAK,QAAQ,IAAI;AAAA,IAC3B;AACA,WAAO;AAAA,EACR;AACD;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Initializer.js","sources":["../../../../../packages/engine-http/src/bootstrap/Initializer.ts"],"sourcesContent":["import { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\n\nexport class Initializer {\n\tconstructor(\n\t\tprivate readonly projectGroupContainer: ProjectGroupContainer,\n\t) {}\n\n\tpublic async initialize(): Promise<string[]> {\n\t\tconst groupContainer = await this.projectGroupContainer\n\t\tconst tenantMigrationsLogger = groupContainer.logger.child()\n\t\tconst tenantContainer = groupContainer.tenantContainer\n\t\tawait tenantContainer.migrationsRunner.run(tenantMigrationsLogger)\n\n\t\tconst projects: string[] = []\n\n\t\tconst tenantProjects = await tenantContainer.projectManager.getProjects(tenantContainer.databaseContext)\n\t\tfor (const { slug: projectSlug } of tenantProjects) {\n\t\t\tconst projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(projectSlug, { alias: false })\n\t\t\tif (!projectContainer) {\n\t\t\t\tthrow new Error()\n\t\t\t}\n\t\t\tconst project = projectContainer.project\n\t\t\tprojects.push(project.slug)\n\t\t}\n\t\treturn projects\n\t}\n}\n"],"names":[],"mappings":"AAEO,MAAM,YAAY;AAAA,EACxB,YACkB,uBAChB;AADgB,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAa,aAAgC;AAC5C,UAAM,iBAAiB,MAAM,KAAK;AAClC,UAAM,yBAAyB,eAAe,OAAO,MAAA;AACrD,UAAM,kBAAkB,eAAe;AACvC,UAAM,gBAAgB,iBAAiB,IAAI,sBAAsB;AAEjE,UAAM,WAAqB,CAAA;AAE3B,UAAM,iBAAiB,MAAM,gBAAgB,eAAe,YAAY,gBAAgB,eAAe;AACvG,eAAW,EAAE,MAAM,YAAA,KAAiB,gBAAgB;AACnD,YAAM,mBAAmB,MAAM,eAAe,yBAAyB,oBAAoB,aAAa,EAAE,OAAO,OAAO;AACxH,UAAI,CAAC,kBAAkB;AACtB,cAAM,IAAI,MAAA;AAAA,MACX;AACA,YAAM,UAAU,iBAAiB;AACjC,eAAS,KAAK,QAAQ,IAAI;AAAA,IAC3B;AACA,WAAO;AAAA,EACR;AACD;"}
1
+ {"version":3,"file":"Initializer.js","sources":["../../../../../packages/engine-http/src/bootstrap/Initializer.ts"],"sourcesContent":["import { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\n\nexport class Initializer {\n\tconstructor(\n\t\tprivate readonly projectGroupContainer: ProjectGroupContainer,\n\t) {}\n\n\tpublic async initialize(): Promise<string[]> {\n\t\tconst groupContainer = await this.projectGroupContainer\n\t\tconst tenantMigrationsLogger = groupContainer.logger.child()\n\t\tconst tenantContainer = groupContainer.tenantContainer\n\t\tawait tenantContainer.migrationsRunner.run(tenantMigrationsLogger)\n\n\t\tconst projects: string[] = []\n\n\t\tconst tenantProjects = await tenantContainer.projectManager.getProjects(tenantContainer.databaseContext)\n\t\tfor (const { slug: projectSlug } of tenantProjects) {\n\t\t\tconst projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(projectSlug, { alias: false })\n\t\t\tif (!projectContainer) {\n\t\t\t\tthrow new Error()\n\t\t\t}\n\t\t\tconst project = projectContainer.project\n\t\t\tprojects.push(project.slug)\n\t\t}\n\t\treturn projects\n\t}\n}\n"],"names":[],"mappings":"AAEO,MAAM,YAAY;AAAA,EACxB,YACkB,uBAChB;AADgB,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAa,aAAgC;AAC5C,UAAM,iBAAiB,MAAM,KAAK;AAClC,UAAM,yBAAyB,eAAe,OAAO,MAAA;AACrD,UAAM,kBAAkB,eAAe;AACvC,UAAM,gBAAgB,iBAAiB,IAAI,sBAAsB;AAEjE,UAAM,WAAqB,CAAA;AAE3B,UAAM,iBAAiB,MAAM,gBAAgB,eAAe,YAAY,gBAAgB,eAAe;AACvG,eAAW,EAAE,MAAM,YAAA,KAAiB,gBAAgB;AACnD,YAAM,mBAAmB,MAAM,eAAe,yBAAyB,oBAAoB,aAAa,EAAE,OAAO,OAAO;AACxH,UAAI,CAAC,kBAAkB;AACtB,cAAM,IAAI,MAAA;AAAA,MACX;AACA,YAAM,UAAU,iBAAiB;AACjC,eAAS,KAAK,QAAQ,IAAI;AAAA,IAC3B;AACA,WAAO;AAAA,EACR;AACD;"}
@@ -1,18 +1,58 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const HttpResponse = require("./HttpResponse.cjs");
4
+ const ipaddr = require("ipaddr.js");
4
5
  var __defProp = Object.defineProperty;
5
6
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
7
  var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
7
8
  const assumeIdentityHeader = "x-contember-assume-identity";
9
+ const forwardedClientIpHeader = "x-contember-client-ip";
10
+ const forwardedClientUserAgentHeader = "x-contember-client-user-agent";
11
+ const USER_AGENT_MAX_LENGTH = 512;
12
+ const GEO_COUNTRY_MAX_LENGTH = 64;
13
+ const readHeader = (request, name) => {
14
+ const value = request.headers[name];
15
+ if (Array.isArray(value)) {
16
+ return value[0];
17
+ }
18
+ return typeof value === "string" ? value : void 0;
19
+ };
20
+ const sanitizeGeoCountry = (value) => {
21
+ if (value === void 0) {
22
+ return void 0;
23
+ }
24
+ const trimmed = value.trim();
25
+ if (trimmed.length === 0) {
26
+ return void 0;
27
+ }
28
+ return trimmed.length > GEO_COUNTRY_MAX_LENGTH ? trimmed.slice(0, GEO_COUNTRY_MAX_LENGTH) : trimmed;
29
+ };
30
+ const sanitizeUserAgent = (value) => {
31
+ if (value === void 0) {
32
+ return void 0;
33
+ }
34
+ return value.length > USER_AGENT_MAX_LENGTH ? value.slice(0, USER_AGENT_MAX_LENGTH) : value;
35
+ };
36
+ const sanitizeIp = (value) => {
37
+ if (!value) {
38
+ return void 0;
39
+ }
40
+ try {
41
+ ipaddr.parse(value);
42
+ } catch {
43
+ return void 0;
44
+ }
45
+ return value;
46
+ };
8
47
  class Authenticator {
9
- constructor(tenantDatabase, tenantReadDatabase, apiKeyManager) {
48
+ constructor(tenantDatabase, tenantReadDatabase, apiKeyManager, geoCountryHeader) {
10
49
  this.tenantDatabase = tenantDatabase;
11
50
  this.tenantReadDatabase = tenantReadDatabase;
12
51
  this.apiKeyManager = apiKeyManager;
52
+ this.geoCountryHeader = geoCountryHeader;
13
53
  __publicField(this, "createAuthError", (message) => new HttpResponse.HttpErrorResponse(401, `Authorization failure: ${message}`));
14
54
  }
15
- async authenticate({ request, timer }) {
55
+ async authenticate({ request, timer, clientIp }) {
16
56
  const authHeader = request.headers.authorization;
17
57
  if (!authHeader) {
18
58
  return null;
@@ -23,7 +63,17 @@ class Authenticator {
23
63
  throw this.createAuthError(`invalid Authorization header format`);
24
64
  }
25
65
  const [, token] = match;
26
- const authResult = await timer("Auth", () => this.apiKeyManager.verifyAndProlong(this.tenantDatabase, this.tenantReadDatabase, token));
66
+ const socketIp = sanitizeIp(clientIp);
67
+ const socketUserAgent = sanitizeUserAgent(readHeader(request, "user-agent"));
68
+ const forwardedIp = sanitizeIp(readHeader(request, forwardedClientIpHeader));
69
+ const forwardedUserAgent = sanitizeUserAgent(readHeader(request, forwardedClientUserAgentHeader));
70
+ const forwardedGeoCountry = this.geoCountryHeader !== void 0 ? sanitizeGeoCountry(readHeader(request, this.geoCountryHeader.toLowerCase())) : void 0;
71
+ const socketInfo = { ip: socketIp, userAgent: socketUserAgent };
72
+ const forwardedInfo = forwardedIp !== void 0 || forwardedUserAgent !== void 0 ? { ip: forwardedIp, userAgent: forwardedUserAgent } : void 0;
73
+ const authResult = await timer(
74
+ "Auth",
75
+ () => this.apiKeyManager.verifyAndProlong(this.tenantDatabase, this.tenantReadDatabase, token, socketInfo, forwardedInfo)
76
+ );
27
77
  if (!authResult.ok) {
28
78
  throw this.createAuthError(authResult.errorMessage);
29
79
  }
@@ -31,9 +81,16 @@ class Authenticator {
31
81
  if (Array.isArray(assumedIdentityId)) {
32
82
  throw new HttpResponse.HttpErrorResponse(400, `Invalid ${assumedIdentityId} header format`);
33
83
  }
84
+ const trustForwarded = authResult.result.trustForwardedInfo && forwardedInfo !== void 0;
85
+ const trustGeo = trustForwarded && forwardedGeoCountry !== void 0;
34
86
  return {
35
87
  ...authResult.result,
36
- assumedIdentityId
88
+ assumedIdentityId,
89
+ clientIp: trustForwarded ? forwardedInfo?.ip ?? socketIp : socketIp,
90
+ clientUserAgent: trustForwarded ? forwardedInfo?.userAgent ?? socketUserAgent : socketUserAgent,
91
+ forwarderIp: trustForwarded ? socketIp : void 0,
92
+ forwarderUserAgent: trustForwarded ? socketUserAgent : void 0,
93
+ geoCountry: trustGeo ? forwardedGeoCountry : void 0
37
94
  };
38
95
  }
39
96
  }