@futdevpro/nts-dynamo 1.15.144 → 1.15.145

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 (369) hide show
  1. package/.c8rc.json +26 -26
  2. package/.copilot/patterns.json +7 -7
  3. package/.cursor/rules/__assistant_guide.mdc +30 -30
  4. package/.cursor/rules/_ag_backend-structure.mdc +85 -85
  5. package/.cursor/rules/_ag_backend.mdc +16 -16
  6. package/.cursor/rules/_ag_frontend-structure.mdc +86 -86
  7. package/.cursor/rules/_ag_frontend.mdc +39 -39
  8. package/.cursor/rules/_ag_import-rules.mdc +44 -44
  9. package/.cursor/rules/_ag_naming.mdc +115 -115
  10. package/.cursor/rules/_ag_should-be.mdc +6 -6
  11. package/.cursor/rules/ai_development_guide.md +60 -60
  12. package/.cursor/rules/cursor-rules.md +160 -160
  13. package/.cursor/rules/default-command.mdc +464 -464
  14. package/.cursor/rules/error_code_pattern.md +39 -39
  15. package/.cursor/rules/saved rule mcp server use.md +15 -15
  16. package/.dynamo/logs/cicd-pipeline/output.log +3034 -0
  17. package/.dynamo/logs/cicd-pipeline/status.json +74 -0
  18. package/.vscode/settings.json +10 -10
  19. package/HOWTO.md +15 -15
  20. package/LICENSE +21 -21
  21. package/__documentations/2026-08-18-artifact-compiler.md +3 -1
  22. package/__documentations/nts-integration-tests-2026-03-17.md +26 -26
  23. package/__documentations/plans/BEDROCK-HYPERPLAN.md +95 -95
  24. package/_specifications/BACKLOG.md +92 -92
  25. package/_specifications/TODO.md +15 -15
  26. package/_specifications/agent.md +138 -138
  27. package/build/_services/core/collection-growth-monitor.service.d.ts +1 -1
  28. package/build/_services/core/collection-growth-monitor.service.d.ts.map +1 -1
  29. package/build/_services/core/collection-growth-monitor.service.js +24 -5
  30. package/build/_services/core/collection-growth-monitor.service.js.map +1 -1
  31. package/eslint.config.js +3 -3
  32. package/nodemon.json +24 -24
  33. package/package.json +1 -1
  34. package/pnpm-workspace.yaml +2 -2
  35. package/scripts/run-coverage-tests.js +28 -28
  36. package/spec/support/helpers/spec-reporter-loader.js +359 -359
  37. package/spec/support/helpers/ts-node-helper.js +93 -93
  38. package/spec/support/jasmine.coverage.json +24 -24
  39. package/spec/support/jasmine.json +24 -24
  40. package/src/_collections/archive.util.spec.ts +57 -57
  41. package/src/_collections/archive.util.ts +18 -18
  42. package/src/_collections/atlas-default-db-options.const.ts +9 -9
  43. package/src/_collections/default-fallback-cache-max-age.const.spec.ts +11 -11
  44. package/src/_collections/default-fallback-cache-max-age.const.ts +2 -2
  45. package/src/_collections/default-not-found-page.const.spec.ts +19 -19
  46. package/src/_collections/default-not-found-page.const.ts +22 -22
  47. package/src/_collections/default-socket-path.const.spec.ts +12 -12
  48. package/src/_collections/default-socket-path.const.ts +2 -2
  49. package/src/_collections/get-environment-settings.util.spec.ts +210 -210
  50. package/src/_collections/get-environment-settings.util.ts +48 -48
  51. package/src/_collections/global-settings.const.ts +126 -126
  52. package/src/_collections/sample.env +21 -21
  53. package/src/_collections/signed-url.util.spec.ts +198 -198
  54. package/src/_collections/signed-url.util.ts +170 -170
  55. package/src/_collections/star.controller.spec.ts +224 -224
  56. package/src/_collections/star.controller.ts +129 -129
  57. package/src/_enums/data-model-type.enum.ts +14 -14
  58. package/src/_enums/data-service-function.enum.ts +24 -24
  59. package/src/_enums/predefined-data-types.enum.ts +16 -16
  60. package/src/_enums/route-security.enum.ts +12 -12
  61. package/src/_models/control-models/api-call-params.control-model.spec.ts +152 -152
  62. package/src/_models/control-models/api-call-params.control-model.ts +142 -142
  63. package/src/_models/control-models/app-ext-system-controls.control-model.spec.ts +52 -52
  64. package/src/_models/control-models/app-ext-system-controls.control-model.ts +9 -9
  65. package/src/_models/control-models/app-params.control-model.spec.ts +225 -225
  66. package/src/_models/control-models/app-params.control-model.ts +136 -136
  67. package/src/_models/control-models/app-system-controls.control-model.spec.ts +31 -31
  68. package/src/_models/control-models/app-system-controls.control-model.ts +9 -9
  69. package/src/_models/control-models/endpoint-params.control-model.spec.ts +669 -669
  70. package/src/_models/control-models/endpoint-params.control-model.ts +664 -664
  71. package/src/_models/control-models/http-settings.control-model.spec.ts +77 -77
  72. package/src/_models/control-models/http-settings.control-model.ts +37 -37
  73. package/src/_models/control-models/system-control.control-model.spec.ts +27 -27
  74. package/src/_models/control-models/system-control.control-model.ts +12 -12
  75. package/src/_models/interfaces/certification-settings.interface.ts +7 -7
  76. package/src/_models/interfaces/environment-settings.interface.ts +59 -59
  77. package/src/_models/interfaces/global-log-settings.interface.ts +171 -171
  78. package/src/_models/interfaces/global-service-settings.interface.ts +47 -47
  79. package/src/_models/interfaces/global-settings.interface.ts +294 -294
  80. package/src/_models/interfaces/routing-module-settings.interface.ts +21 -21
  81. package/src/_models/interfaces/static-client-settings.interface.spec.ts +29 -29
  82. package/src/_models/interfaces/static-client-settings.interface.ts +36 -36
  83. package/src/_models/types/db-update.type.ts +100 -100
  84. package/src/_modules/ai/_models/ai-input-interfaces.ts +117 -117
  85. package/src/_modules/ai/_models/ai-test-generation-result.interface.ts +16 -16
  86. package/src/_modules/ai/_modules/ai-mock/_services/ai-embedding-mock.service.spec.ts +115 -115
  87. package/src/_modules/ai/_modules/ai-mock/_services/ai-embedding-mock.service.ts +233 -233
  88. package/src/_modules/ai/_modules/anthropic/_services/aai-user-key.control-service.ts +138 -138
  89. package/src/_modules/ai/_modules/anthropic/index.ts +5 -5
  90. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.spec.ts +242 -242
  91. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.ts +639 -639
  92. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.spec.ts +295 -295
  93. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.ts +518 -518
  94. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.spec.ts +209 -209
  95. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.ts +85 -85
  96. package/src/_modules/ai/_modules/document-ai/_enums/dai-compare-result-type.enum.ts +7 -7
  97. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-chunk.data-model.ts +146 -146
  98. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-page.data-model.ts +162 -162
  99. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-document.data-model.ts +99 -99
  100. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-code-chunk.interface.ts +68 -68
  101. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-chunk-compare-result.interface.ts +18 -18
  102. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-page-compare-result.interface.ts +19 -19
  103. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-document-compare-result.interface.ts +25 -25
  104. package/src/_modules/ai/_modules/document-ai/index.ts +30 -30
  105. package/src/_modules/ai/_modules/fdp-ai/_services/fdpai-user-key.control-service.ts +189 -189
  106. package/src/_modules/ai/_modules/fdp-ai/index.ts +5 -5
  107. package/src/_modules/ai/_modules/open-ai/_collections/oai-global-settings.const.ts +9 -9
  108. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests-hu.conts.ts +82 -82
  109. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests.conts.ts +75 -75
  110. package/src/_modules/ai/_modules/open-ai/_enums/oai-gpt-message-role.enum.ts +45 -45
  111. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-global-settings.interface.ts +7 -7
  112. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-gpt-message.interface.ts +7 -7
  113. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-llm-predefined-requests.interface.ts +57 -57
  114. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-doc-chunk-data.service.ts +292 -292
  115. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-document.data-service.spec.ts +342 -342
  116. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.spec.ts +550 -550
  117. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.ts +630 -630
  118. package/src/_modules/ai/_modules/open-ai/_services/oai-embedding.control-service.spec.ts +332 -332
  119. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.spec.ts +462 -462
  120. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.ts +634 -634
  121. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.spec.ts +489 -489
  122. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.tools.spec.ts +173 -173
  123. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.ts +1085 -1085
  124. package/src/_modules/ai/_modules/open-ai/_services/oai-user-key.control-service.ts +157 -157
  125. package/src/_modules/ai/_services/ai-embedding-provider.registry.spec.ts +110 -110
  126. package/src/_modules/ai/_services/ai-embedding-provider.registry.ts +114 -114
  127. package/src/_modules/ai/_services/ai-embedding.service-base.spec.ts +98 -98
  128. package/src/_modules/ai/_services/ai-embedding.service-base.ts +48 -48
  129. package/src/_modules/ai/_services/ai-llm-chat.service-base.spec.ts +229 -229
  130. package/src/_modules/ai/_services/ai-llm-chat.service-base.ts +68 -68
  131. package/src/_modules/ai/_services/ai-llm.service-base.spec.ts +250 -250
  132. package/src/_modules/ai/_services/ai-llm.service-base.ts +599 -599
  133. package/src/_modules/ai/_services/ai-provider.service-base.spec.ts +158 -158
  134. package/src/_modules/ai/_services/ai-user-key.service-base.ts +59 -59
  135. package/src/_modules/ai/_services/lmstudio-embedding.control-service.spec.ts +197 -197
  136. package/src/_modules/ai/_services/lmstudio-embedding.control-service.ts +371 -371
  137. package/src/_modules/ai/index.ts +33 -33
  138. package/src/_modules/assistant/_collections/ass-global-settings.const.ts +13 -13
  139. package/src/_modules/assistant/_collections/ass.util.spec.ts +176 -176
  140. package/src/_modules/assistant/_collections/ass.util.ts +50 -50
  141. package/src/_modules/assistant/_models/ass-global-settings.interface.ts +15 -15
  142. package/src/_modules/assistant/_services/ass-io.control-service.spec.ts +140 -140
  143. package/src/_modules/assistant/_services/ass-main.control-service.spec.ts +192 -192
  144. package/src/_modules/assistant/_services/ass-main.control-service.ts +107 -107
  145. package/src/_modules/bot/_collections/bot-default-commands.const.ts +12 -12
  146. package/src/_modules/bot/_collections/bot-global-settings.const.ts +39 -39
  147. package/src/_modules/bot/_models/bot-channel-wrapper.interface.ts +62 -62
  148. package/src/_modules/bot/_models/bot-command.interface.ts +8 -8
  149. package/src/_modules/bot/_models/bot-global-settings.interface.ts +96 -96
  150. package/src/_modules/bot/_models/bot-last-mention-date.interface.ts +6 -6
  151. package/src/_modules/bot/_models/bot-last-message-date.interface.ts +5 -5
  152. package/src/_modules/bot/_models/bot-user-wrapper.interface.ts +41 -41
  153. package/src/_modules/bot/_modules/discord-bot/_models/dib-platform.types.ts +9 -9
  154. package/src/_modules/bot/_modules/discord-bot/_services/dib-messaging-provider.control-service.spec.ts +431 -431
  155. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.spec.ts +160 -160
  156. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.ts +55 -55
  157. package/src/_modules/bot/_modules/dynamo-bot/_models/dyb-platform.types.ts +15 -15
  158. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.spec.ts +374 -374
  159. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.ts +447 -447
  160. package/src/_modules/bot/_modules/dynamo-bot/index.ts +15 -15
  161. package/src/_modules/bot/_modules/slack-bot/_models/slb-platform.types.ts +9 -9
  162. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.spec.ts +344 -344
  163. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.ts +197 -197
  164. package/src/_modules/bot/_modules/teams-bot/_models/teb-platform.types.ts +9 -9
  165. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.spec.ts +345 -345
  166. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.ts +197 -197
  167. package/src/_modules/bot/_services/bot-commands.control-service.spec.ts +116 -116
  168. package/src/_modules/bot/_services/bot-io.control-service.spec.ts +285 -285
  169. package/src/_modules/bot/_services/bot-main.control-service.spec.ts +208 -208
  170. package/src/_modules/bot/_services/bot-messaging-provider.service-base.spec.ts +349 -349
  171. package/src/_modules/bot/_services/bot-routines.control-service.spec.ts +111 -111
  172. package/src/_modules/custom-data/custom-data.controller.spec.ts +49 -49
  173. package/src/_modules/custom-data/custom-data.controller.ts +67 -67
  174. package/src/_modules/custom-data/custom-data.data-service.spec.ts +54 -54
  175. package/src/_modules/custom-data/custom-data.data-service.ts +21 -21
  176. package/src/_modules/custom-data/get-custom-data-routing-module.util.spec.ts +28 -28
  177. package/src/_modules/custom-data/get-custom-data-routing-module.util.ts +24 -24
  178. package/src/_modules/custom-data/index.ts +9 -9
  179. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.spec.ts +161 -161
  180. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.ts +203 -203
  181. package/src/_modules/data-readers/_models/interfaces/dynts-sqlite-reader.interface.ts +33 -33
  182. package/src/_modules/data-readers/index.ts +11 -11
  183. package/src/_modules/defaults/_collections/default-endpoints.util.ts +487 -487
  184. package/src/_modules/defaults/_models/default-user.data-model.ts +72 -72
  185. package/src/_modules/defaults/_services/default-auth.service.spec.ts +269 -269
  186. package/src/_modules/defaults/_services/default-auth.service.ts +177 -177
  187. package/src/_modules/defaults/_services/default-socket-events.service.spec.ts +42 -42
  188. package/src/_modules/defaults/_services/default-socket-events.service.ts +61 -61
  189. package/src/_modules/defaults/_services/default-user.data-service.spec.ts +187 -187
  190. package/src/_modules/defaults/_services/default-user.data-service.ts +98 -98
  191. package/src/_modules/defaults/index.ts +17 -17
  192. package/src/_modules/discord-assistant/_collections/dias-global-settings.const.ts +19 -19
  193. package/src/_modules/discord-assistant/_collections/dias.util.spec.ts +366 -366
  194. package/src/_modules/discord-assistant/_collections/dias.util.ts +132 -132
  195. package/src/_modules/discord-assistant/_models/dias-global-settings.interface.ts +19 -19
  196. package/src/_modules/discord-assistant/_models/dias-knowledge.data-model.ts +52 -52
  197. package/src/_modules/discord-assistant/_services/dias-chunk.data-service.ts +177 -177
  198. package/src/_modules/discord-assistant/_services/dias-io.control-service.spec.ts +108 -108
  199. package/src/_modules/discord-assistant/_services/dias-io.control-service.ts +69 -69
  200. package/src/_modules/discord-assistant/_services/dias-main.control-service.spec.ts +22 -22
  201. package/src/_modules/discord-assistant/_services/dias-main.control-service.ts +27 -27
  202. package/src/_modules/discord-assistant/_services/dias.service-base.spec.ts +195 -195
  203. package/src/_modules/discord-assistant/_services/dias.service-base.ts +76 -76
  204. package/src/_modules/discord-assistant/index.ts +38 -38
  205. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.spec.ts +34 -34
  206. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.ts +11 -11
  207. package/src/_modules/discord-assistant-voiced/index.ts +36 -36
  208. package/src/_modules/discord-bot/_collections/dibo-default-commands.const.ts +16 -16
  209. package/src/_modules/discord-bot/_collections/dibo-global-settings.conts.ts +55 -55
  210. package/src/_modules/discord-bot/_collections/dibo-operations.util.spec.ts +214 -214
  211. package/src/_modules/discord-bot/_collections/dibo-operations.util.ts +387 -387
  212. package/src/_modules/discord-bot/_models/dibo-command.interface.ts +12 -12
  213. package/src/_modules/discord-bot/_models/dibo-global-settings.interface.ts +98 -98
  214. package/src/_modules/discord-bot/_models/dibo-last-mention-date.inteface.ts +7 -7
  215. package/src/_modules/discord-bot/_models/dibo-last-message-date.interface.ts +6 -6
  216. package/src/_modules/discord-bot/_services/dibo-commands.control-service.spec.ts +154 -154
  217. package/src/_modules/discord-bot/_services/dibo-commands.control-service.ts +153 -153
  218. package/src/_modules/discord-bot/_services/dibo-io.control-service.spec.ts +264 -264
  219. package/src/_modules/discord-bot/_services/dibo-io.control-service.ts +306 -306
  220. package/src/_modules/discord-bot/_services/dibo-main.control-service.spec.ts +408 -408
  221. package/src/_modules/discord-bot/_services/dibo-main.control-service.ts +487 -487
  222. package/src/_modules/discord-bot/_services/dibo-routines.control-service.spec.ts +105 -105
  223. package/src/_modules/discord-bot/index.ts +36 -36
  224. package/src/_modules/local-vector-search/_enums/lvs-search-mode.enum.ts +35 -35
  225. package/src/_modules/local-vector-search/_models/data-models/lvs-vector-persist.data-model.ts +59 -59
  226. package/src/_modules/local-vector-search/_models/lvs-search-result.interface.ts +17 -17
  227. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.spec.ts +418 -418
  228. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.ts +276 -276
  229. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.spec.ts +480 -480
  230. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.ts +416 -416
  231. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.spec.ts +214 -214
  232. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.ts +186 -186
  233. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.spec.ts +167 -167
  234. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.ts +130 -130
  235. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.spec.ts +509 -509
  236. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.ts +323 -323
  237. package/src/_modules/local-vector-search/index.ts +16 -16
  238. package/src/_modules/logs/index.ts +11 -11
  239. package/src/_modules/mcp/_models/interfaces/dynts-mcp.interface.ts +111 -111
  240. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.spec.ts +142 -142
  241. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.ts +120 -120
  242. package/src/_modules/mcp/_services/dynts-mcp.adapter.ts +168 -168
  243. package/src/_modules/mcp/index.ts +13 -13
  244. package/src/_modules/messaging/README.md +354 -354
  245. package/src/_modules/messaging/_collections/get-messaging-routing-module.util.ts +26 -26
  246. package/src/_modules/messaging/_collections/msg-global-settings.const.ts +22 -22
  247. package/src/_modules/messaging/_collections/msg.util.spec.ts +226 -226
  248. package/src/_modules/messaging/_models/msg-global-settings.interface.ts +37 -37
  249. package/src/_modules/messaging/_services/msg-conversation.data-service.ts +146 -146
  250. package/src/_modules/messaging/_services/msg-events.service.spec.ts +219 -219
  251. package/src/_modules/messaging/_services/msg-events.service.ts +267 -267
  252. package/src/_modules/messaging/_services/msg-integration.control-service.ts +179 -179
  253. package/src/_modules/messaging/_services/msg-main.control-service.spec.ts +147 -147
  254. package/src/_modules/messaging/_services/msg-main.control-service.ts +571 -571
  255. package/src/_modules/messaging/_services/msg-message.data-service.ts +129 -129
  256. package/src/_modules/messaging/_services/msg.controller.spec.ts +201 -201
  257. package/src/_modules/messaging/index.ts +30 -30
  258. package/src/_modules/mock/app-extended-server.mock.ts +201 -201
  259. package/src/_modules/mock/app-integration-test.mock.ts +51 -51
  260. package/src/_modules/mock/app-params.mock.spec.ts +21 -21
  261. package/src/_modules/mock/app-params.mock.ts +9 -9
  262. package/src/_modules/mock/app-server.mock.ts +188 -188
  263. package/src/_modules/mock/auth-service.mock.spec.ts +47 -47
  264. package/src/_modules/mock/auth-service.mock.ts +28 -28
  265. package/src/_modules/mock/controller.mock.spec.ts +26 -26
  266. package/src/_modules/mock/controller.mock.ts +16 -16
  267. package/src/_modules/mock/data-model.mock.spec.ts +111 -111
  268. package/src/_modules/mock/data-model.mock.ts +82 -82
  269. package/src/_modules/mock/email-service-collection.mock.spec.ts +24 -24
  270. package/src/_modules/mock/email-service-collection.mock.ts +15 -15
  271. package/src/_modules/mock/email-service.mock.spec.ts +17 -17
  272. package/src/_modules/mock/email-service.mock.ts +20 -20
  273. package/src/_modules/mock/email-template.mock.html +14 -14
  274. package/src/_modules/mock/endpoint.mock.ts +91 -91
  275. package/src/_modules/mock/socket-client.mock.spec.ts +40 -40
  276. package/src/_modules/mock/socket-client.mock.ts +45 -45
  277. package/src/_modules/mock/socket-server.mock.spec.ts +44 -44
  278. package/src/_modules/mock/socket-server.mock.ts +46 -46
  279. package/src/_modules/oauth2/_routes/oauth2.controller.spec.ts +107 -107
  280. package/src/_modules/oauth2/_routes/oauth2.controller.ts +98 -98
  281. package/src/_modules/oauth2/_services/oauth2.auth-service.spec.ts +254 -254
  282. package/src/_modules/oauth2/_services/oauth2.auth-service.ts +232 -232
  283. package/src/_modules/oauth2/_services/oauth2.control-service.spec.ts +585 -585
  284. package/src/_modules/oauth2/_services/oauth2.control-service.ts +653 -653
  285. package/src/_modules/oauth2/index.ts +17 -17
  286. package/src/_modules/scheduler/_models/scheduler-job.interface.ts +35 -35
  287. package/src/_modules/scheduler/get-scheduler-routing-module.util.ts +33 -33
  288. package/src/_modules/scheduler/index.ts +8 -8
  289. package/src/_modules/scheduler/scheduler.controller.spec.ts +42 -42
  290. package/src/_modules/scheduler/scheduler.controller.ts +69 -69
  291. package/src/_modules/scheduler/scheduler.service.spec.ts +141 -141
  292. package/src/_modules/scheduler/scheduler.service.ts +176 -176
  293. package/src/_modules/scoped-config/_enums/dynts-scoped-config-level.enum.ts +22 -22
  294. package/src/_modules/scoped-config/_models/data-models/dynts-scoped-config.data-model.ts +81 -81
  295. package/src/_modules/scoped-config/_models/interfaces/dynts-scoped-config.interface.ts +107 -107
  296. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.spec.ts +306 -306
  297. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.ts +295 -295
  298. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.spec.ts +118 -118
  299. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.ts +105 -105
  300. package/src/_modules/scoped-config/index.ts +17 -17
  301. package/src/_modules/server/errors/errors.control-service.spec.ts +238 -238
  302. package/src/_modules/server/errors/errors.control-service.ts +100 -100
  303. package/src/_modules/server/errors/errors.controller.ts +559 -559
  304. package/src/_modules/server/errors/errors.data-service.spec.ts +480 -480
  305. package/src/_modules/server/index.ts +30 -30
  306. package/src/_modules/server/server-status/server-status-snapshot.control-service.spec.ts +70 -70
  307. package/src/_modules/server/server-status/server-status-snapshot.control-service.ts +17 -17
  308. package/src/_modules/server/server-status/server-status-snapshot.data-service.spec.ts +77 -77
  309. package/src/_modules/server/server-status/server-status-snapshot.data-service.ts +37 -37
  310. package/src/_modules/server/server-status/server-status.control-service.spec.ts +672 -672
  311. package/src/_modules/server/server-status/server-status.control-service.ts +490 -490
  312. package/src/_modules/server/server-status/server-status.controller.spec.ts +276 -276
  313. package/src/_modules/server/server-status/server-status.controller.ts +336 -336
  314. package/src/_modules/socket/_enums/socket-security.enum.ts +11 -11
  315. package/src/_modules/socket/_models/socket-client-service-params.control-model.spec.ts +32 -32
  316. package/src/_modules/socket/_models/socket-client-service-params.control-model.ts +22 -22
  317. package/src/_modules/socket/_models/socket-presence.control-model.spec.ts +158 -158
  318. package/src/_modules/socket/_models/socket-presence.control-model.ts +209 -209
  319. package/src/_modules/socket/_models/socket-server-service-params.control-model.spec.ts +69 -69
  320. package/src/_modules/socket/_services/socket-client.service.spec.ts +15 -15
  321. package/src/_modules/socket/_services/socket-client.service.ts +260 -260
  322. package/src/_modules/socket/app-extended.integration.spec.ts +85 -85
  323. package/src/_modules/socket/app-extended.server.ts +648 -648
  324. package/src/_modules/socket/index.ts +42 -42
  325. package/src/_modules/test/get-test-routing-module.util.spec.ts +28 -28
  326. package/src/_modules/test/get-test-routing-module.util.ts +23 -23
  327. package/src/_modules/test/index.ts +11 -11
  328. package/src/_modules/test/test.controller.spec.ts +72 -72
  329. package/src/_modules/test/test.controller.ts +115 -115
  330. package/src/_modules/usage/get-usage-routing-module.util.ts +22 -22
  331. package/src/_modules/usage/index.ts +15 -15
  332. package/src/_modules/usage/usage.controller.spec.ts +106 -106
  333. package/src/_modules/usage/usage.controller.ts +140 -140
  334. package/src/_modules/usage/usage.data-service.spec.ts +332 -332
  335. package/src/_modules/usage/usage.data-service.ts +185 -185
  336. package/src/_services/base/api.service-base.spec.ts +125 -125
  337. package/src/_services/base/api.service-base.ts +74 -74
  338. package/src/_services/base/archive-data.service.spec.ts +209 -209
  339. package/src/_services/base/archive-data.service.ts +223 -223
  340. package/src/_services/base/data.service.spec.ts +784 -784
  341. package/src/_services/base/data.service.ts +2792 -2792
  342. package/src/_services/base/db.service.spec.ts +160 -160
  343. package/src/_services/base/db.service.ts +1698 -1698
  344. package/src/_services/base/singleton.service-base.spec.ts +28 -28
  345. package/src/_services/base/singleton.service-base.ts +24 -24
  346. package/src/_services/base/singleton.service.spec.ts +114 -114
  347. package/src/_services/base/singleton.service.ts +38 -38
  348. package/src/_services/core/api.service.spec.ts +140 -140
  349. package/src/_services/core/auth.service.spec.ts +159 -159
  350. package/src/_services/core/auth.service.ts +174 -174
  351. package/src/_services/core/collection-growth-monitor.service.spec.ts +53 -1
  352. package/src/_services/core/collection-growth-monitor.service.ts +29 -6
  353. package/src/_services/core/email.service.spec.ts +85 -85
  354. package/src/_services/core/email.service.ts +757 -757
  355. package/src/_services/core/global.service.spec.ts +292 -292
  356. package/src/_services/core/global.service.ts +487 -487
  357. package/src/_services/core/memory-guard.service.spec.ts +245 -245
  358. package/src/_services/core/memory-guard.service.ts +481 -481
  359. package/src/_services/core/service-collection.service.spec.ts +46 -46
  360. package/src/_services/core/service-collection.service.ts +6 -6
  361. package/src/_services/route/controller.service.spec.ts +53 -53
  362. package/src/_services/route/controller.service.ts +148 -148
  363. package/src/_services/route/routing-module.service.spec.ts +98 -98
  364. package/src/_services/route/routing-module.service.ts +330 -330
  365. package/src/_services/server/app.server.ts +2012 -2012
  366. package/src/_services/shared.static-service.spec.ts +99 -99
  367. package/src/_services/shared.static-service.ts +78 -78
  368. package/tsconfig.app.json +12 -12
  369. package/tsconfig.json +42 -42
@@ -1,2012 +1,2012 @@
1
-
2
- import Mongoose = require('mongoose');
3
- import Express = require('express');
4
- /* import Mongoose from 'mongoose';
5
- import Express from 'express'; */
6
-
7
- import * as BodyParser from 'body-parser';
8
- import * as FileSystem from 'fs';
9
- import * as Http from 'http';
10
- import * as Https from 'https';
11
- import * as Path from 'path';
12
- import * as dotenv from 'dotenv'
13
-
14
- /* import { version } from '../../../package.json'; */
15
-
16
- import {
17
- DyFM_AnyError,
18
- DyFM_Array,
19
- DyFM_Async,
20
- DyFM_Error,
21
- DyFM_error_defaults,
22
- DyFM_Error_Settings,
23
- DyFM_ErrorLevel,
24
- DyFM_Log,
25
- DyFM_resolveRetentionTtlSeconds,
26
- megabyte,
27
- second
28
- } from '@futdevpro/fsm-dynamo';
29
-
30
- import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
- import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
- import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
- import { DyNTS_ClientSafeError_Util } from '../../_collections/client-safe-error.util';
34
- import { DyNTS_getEnvironment_settings } from '../../_collections/get-environment-settings.util';
35
- import { DyNTS_createSecurityHeadersMiddleware } from '../../_collections/security-headers.util';
36
- import { DyNTS_createLoadShedMiddleware } from '../../_collections/load-shed.util';
37
- import { DyNTS_createAppVersionHeaderMiddleware } from '../../_collections/app-version-header.util';
38
- import { DyNTS_AppVersionHeader_Settings } from '../../_models/interfaces/app-version-header-settings.interface';
39
- import { DyNTS_SecurityHeaders_Settings } from '../../_models/interfaces/security-headers-settings.interface';
40
- import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
41
- import { DyNTS_resolveStaticCacheControlHeader } from '../../_collections/static-cache-control.util';
42
- import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
43
- import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
44
- import {
45
- DyNTS_AppSystemControls
46
- } from '../../_models/control-models/app-system-controls.control-model';
47
- import {
48
- DyNTS_Endpoint_Params
49
- } from '../../_models/control-models/endpoint-params.control-model';
50
- import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
51
- import {
52
- DyNTS_Certification_Settings
53
- } from '../../_models/interfaces/certification-settings.interface';
54
- import {
55
- DyNTS_GlobalService_Settings
56
- } from '../../_models/interfaces/global-service-settings.interface';
57
- import {
58
- DyNTS_StaticClient_Settings
59
- } from '../../_models/interfaces/static-client-settings.interface';
60
- import {
61
- DyNTS_Cors_Settings
62
- } from '../../_models/interfaces/cors-settings.interface';
63
- import { DyNTS_DBService } from '../base/db.service';
64
- import { DyNTS_SingletonService } from '../base/singleton.service';
65
- import { DyNTS_GlobalService } from '../core/global.service';
66
- import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
67
- import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
68
- import { DyNTS_EventLoopDiag } from '../core/event-loop-diag.service';
69
- import { DyNTS_RoutingModule } from '../route/routing-module.service';
70
- import { DyNTS_getStarRoute } from '../../_collections/star.controller';
71
-
72
- /**
73
- *
74
- * function MyDecorator(config: any) {
75
- return function (target: Function) {
76
- // attach metadata or modify target
77
- target.prototype.myMeta = config;
78
- };
79
- }
80
-
81
- @MyDecorator({ role: 'admin' })
82
- class User {
83
- printRole() {
84
- console.log((this as any).myMeta.role); // → "admin"
85
- }
86
- }
87
-
88
- */
89
-
90
- /**
91
- * This will be the MAIN service of our server project,
92
- * follow the types and type instructions while setting up your project
93
- *
94
- * In this service, there are abstract functions that you will need to implement,
95
- * where you need to set up the main params for your application.
96
- *
97
- * (after the example, you can find the list of services you can/should setup)
98
- *
99
- * @example
100
- * export class App extends DyNTS_AppExtended {
101
- *
102
- * ...
103
- *
104
- * // Setting up App params, and preparing project global settings
105
- * setupAppParams(): void {
106
- * this.params = new DyNTS_AppParams({
107
- * name: 'Warbots Server',
108
- * title: warbotsTitleLog,
109
- * version: version,
110
- * dbName: 'warbots',
111
- * });
112
- *
113
- * // dynamoNTS_GlobalSettings.logRequestsContent = false;
114
- * }
115
- *
116
- * ...
117
- *
118
- * // Setting up DBServices
119
- * setGlobalServiceCollection(): void {
120
- * DyNTS_GlobalService.setServices({
121
- * authService: AuthService.getInstance(),
122
- * emailServiceCollection: EmailServiceCollectionService.getInstance(),
123
- * dbModels: [
124
- * userModelParams,
125
- * userDataModelParams,
126
- * userOptionsModelParams,
127
- * userStatisticsModelParams,
128
- * userAchievementsModelParams,
129
- * userNotificationsModelParams,
130
- *
131
- * matchStatisticsModelParams,
132
- * matchDataModelParams,
133
-
134
- * DyFM_usageSession_dataParams,
135
- * DyFM_customData_dataParams,
136
- * ]
137
- * });
138
- * }
139
- *
140
- * ...
141
- *
142
- * // Setting up Routes
143
- * setupRoutingModules(): void {
144
- * this.httpPort = env.port;
145
-
146
- * this.routingModules = [
147
- * new DyNTS_RoutingModule({
148
- * route: '/user',
149
- * controllers: [
150
- * UserController.getInstance(),
151
- * UserDataController.getInstance(),
152
- * UserOptionsController.getInstance(),
153
- * UserStatisticsController.getInstance(),
154
- * UserAchievementsController.getInstance(),
155
- * UserNotificationsController.getInstance()
156
- * ]
157
- * }),
158
- * new DyNTS_RoutingModule({
159
- * route: '/match',
160
- * controllers: [
161
- * MatchController.getInstance(),
162
- * MatchDistributionController.getInstance(),
163
- * MatchStatisticsController.getInstance(),
164
- * ]
165
- * }),
166
- * new DyNTS_RoutingModule({
167
- * route: '/server',
168
- * controllers: [
169
- * ServerController.getInstance(),
170
- * ]
171
- * }),
172
-
173
- * getTestRoutingModule(),
174
- * getUsageRoutingModule()
175
- * ];
176
- * }
177
- * }
178
- *
179
- * //
180
- * // The Services available
181
- * //
182
- * // Authentication Service
183
- * // A commonly used basic service,
184
- * // which is necessary fur certain functions (such as registering call issuers)
185
- * //
186
- * // This will handle Authentication Token checking/refreshing,
187
- * // checking issuer's identifier and routeParams,
188
- * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
189
- * //
190
- * // You can create one with this Dynamo Object:
191
- * //
192
- *
193
- * @example
194
- * // follow the instructions on the abstract class (DyNTS_AuthService)
195
- * export class AuthService extends DyNTS_AuthService {}
196
- *
197
- *
198
- *
199
- * //
200
- */
201
-
202
- /**
203
- * This will be the MAIN service of our server project,
204
- * follow the types and type instructions while setting up your project
205
- *
206
- * In this service, there are abstract functions that you will need to implement,
207
- * where you need to set up the main params for your application.
208
- *
209
- * (after the example, you can find the list of services you can/should setup)
210
- *
211
- * You need to setup the following functions:
212
- * ```ts
213
- * // this is where you set up the main params for your application
214
- * getAppParams(): DyNTS_AppParams
215
- *
216
- * // this is where you connect your main services
217
- * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
218
- *
219
- * // this is where you set up your ports
220
- * getPorts(): DyNTS_PortSettings
221
- *
222
- * // this is where you set up your routes
223
- * getRoutingModules(): DyNTS_RoutingModule[]
224
- *
225
- *
226
- *
227
- * ```
228
- * optionally you can setup the following functions:
229
- * ```ts
230
- * // this is where you set up your certifications
231
- * getCertificationSettings(): DyNTS_CertificationSettings
232
- *
233
- * // this is where you set up additional root services
234
- * getRootServices(): DyNTS_SingletonService[]
235
- *
236
- * // this is where you set up your initial db entries
237
- * createEntries(): void
238
- *
239
- * // this is where you can define post setup processes
240
- * postProcess(): void
241
- *
242
- *
243
- *
244
- * ```
245
- *
246
- */
247
-
248
- /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
249
- export interface DyNTS_TtlIndexInfo {
250
- name?: string;
251
- key?: Record<string, number>;
252
- expireAfterSeconds?: number;
253
- }
254
-
255
- /**
256
- * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
257
- * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
258
- * in unit tests.
259
- */
260
- export interface DyNTS_TtlIndexCollection {
261
- indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
262
- createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
263
- dropIndex?: (name: string) => Promise<unknown>;
264
- }
265
-
266
- /**
267
- * FR-258 / SR-2 — outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
268
- * - `created`: no `__created` TTL index existed → one was created.
269
- * - `noop`: an index with the SAME TTL already existed → nothing done.
270
- * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) → left UNTOUCHED,
271
- * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
272
- * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
273
- * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
274
- * maintenance, not silently at every startup.
275
- */
276
- export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
277
-
278
- export abstract class DyNTS_App extends DyNTS_SingletonService {
279
-
280
- protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
281
- get started(): boolean {
282
- return this.systemControls.app.started;
283
- }
284
- protected get superStarted(): boolean {
285
- return this.systemControls.app.started;
286
- }
287
- protected constructErrors: (Error | DyFM_Error)[] = [];
288
-
289
- /* removed since cant use version from package.json
290
- private readonly _ntsVersion: string = 'v01.07.18';
291
- protected get ntsVersion(): string {
292
- return this._ntsVersion;
293
- } */
294
-
295
- get serverName(): string {
296
- return this.params.name;
297
- }
298
-
299
- private _params: DyNTS_App_Params;
300
- protected get params(): DyNTS_App_Params {
301
- return this._params;
302
- }
303
-
304
- protected mongoose = Mongoose;
305
-
306
- private _security: DyNTS_RouteSecurity;
307
- protected get security(): DyNTS_RouteSecurity {
308
- return this._security;
309
- }
310
-
311
- protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
312
- protected get portSettings(): DyNTS_Http_Settings {
313
- return this._portSettings;
314
- }
315
-
316
- private _cert?: DyNTS_Certification_Settings;
317
- protected get cert(): DyNTS_Certification_Settings {
318
- return this._cert;
319
- }
320
-
321
- protected openExpress: Express.Application;
322
- protected secureExpress: Express.Application;
323
- protected httpsServer: Https.Server;
324
- protected httpServer: Http.Server;
325
-
326
- private globalService: DyNTS_GlobalService;
327
- private _rootServices: DyNTS_SingletonService[] = [];
328
-
329
- private _routingModules: DyNTS_RoutingModule[] = [];
330
-
331
- protected readonly defaultReadyTimeout: number = 30 * second;
332
-
333
- override readonly defaultErrorUserMsg =
334
- `We encountered an unhandled Server Error, ` +
335
- `\nplease contact the responsible development team.` +
336
- `\n(Internal Server error)`;
337
-
338
- get logSetup(): boolean {
339
- return DyNTS_global_settings.log_settings.setup;
340
- }
341
- get deepLog(): boolean {
342
- return DyNTS_global_settings.log_settings.deep;
343
- }
344
- get fnLogs(): boolean {
345
- return DyNTS_global_settings.log_settings.functions;
346
- }
347
- debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
348
-
349
- constructor(/* extended?: boolean */){
350
- super();
351
-
352
- /* dotenv.config() */
353
-
354
- process.on(
355
- 'unhandledRejection',
356
- (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
357
- if (reason_theError instanceof DyFM_Error) {
358
- reason_theError.logSimple('Unhandled Rejection');
359
- } else {
360
- DyFM_Log.H_error(
361
- 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
362
- '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
363
- /* '\n ErrorCode:', (reason as any)?.code, */
364
- '\n\n Stack:',
365
- (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
366
- );
367
- }
368
-
369
- try {
370
- DyNTS_GlobalService.globalErrorHandler?.(
371
- new DyFM_Error({
372
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
373
- message:
374
- `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
375
- userMessage: this.defaultErrorUserMsg,
376
- addECToUserMsg: true,
377
- error: reason_theError as Error,
378
- additionalContent: {
379
- reason: reason_theError,
380
- rejectedPromise: p_passWhatIsThis_maybeThePromise,
381
- },
382
- systemVersion: DyNTS_global_settings.systemVersion,
383
- level: DyFM_ErrorLevel.critical,
384
- })
385
- );
386
- } catch (error) {
387
- DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
388
- }
389
- }
390
- );
391
-
392
- this.asyncConstruct(/* extended */).catch((error: any): void => {
393
- if (error instanceof DyFM_Error) {
394
- if (error.additionalContent?.constructErrors?.length) {
395
- error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
396
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
397
- /* if (errorItem instanceof DyFM_Error) {
398
- errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
399
- } else {
400
- DyFM_Log.H_warn(
401
- '(constructor asyncConstruct.catch) additional error content:\n',
402
- errorItem
403
- );
404
- } */
405
- });
406
- } else {
407
- DyFM_Log.H_warn(
408
- '(constructor asyncConstruct.catch) additional error content:\n',
409
- error?.additionalContent
410
- );
411
- }
412
- }
413
-
414
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
415
- /* if (
416
- !DyNTS_global_settings.log_settings.highDetailedLogs &&
417
- (error instanceof DyFM_Error)
418
- ) {
419
- error.logSimple(
420
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
421
- '\n all error messages (from this stack):\n\n"' +
422
- error._messages.join('"\n\n"') + '"\n\n'
423
- );
424
- } else if (error instanceof DyFM_Error) {
425
- DyFM_Log.H_error(
426
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
427
- `\n ERROR:`, error
428
- );
429
- } */
430
-
431
- const message: string =
432
- (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
433
- (errorItem: DyFM_Error): string[] => {
434
- return errorItem?._messages ?? [];
435
- }
436
- )?.join?.('\n') ??
437
- (error as DyFM_Error)?.errors?.flatMap(
438
- (errorItem: DyFM_AnyError): string[] =>
439
- (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
440
- )?.join?.('\n') ??
441
- error?.message ??
442
- 'UNKNOWN';
443
-
444
- DyFM_Log.testError('Application start failed:\n', message);
445
-
446
- process.exit(1);
447
- });
448
- }
449
-
450
- protected async asyncConstruct(extended?: boolean): Promise<void> {
451
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
452
-
453
- try {
454
- this.systemControls.app.init = true;
455
- this._params = this.getAppParams();
456
- DyFM_Log.log(
457
- `\n\n\n\n\n\n\n\n\n\n` +
458
- `Starting ${this._params?.name}... ` +
459
- /* `v${version}` + */
460
- `\n\n\n\n\n\n\n\n\n\n`
461
- );
462
-
463
- if (!this._params) {
464
- throw new Error('getAppParams() must return a DyNTS_AppParams object!');
465
- }
466
-
467
- if (this.params.systemShortCodeName) {
468
- DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
469
- }
470
-
471
- if (this.params.systemName) {
472
- DyNTS_global_settings.systemName = this.params.systemName;
473
- DyFM_error_defaults.issuerSystem = this.params.systemName;
474
- }
475
-
476
- if (this.params.version) {
477
- DyNTS_global_settings.systemVersion = this.params.version;
478
- DyFM_error_defaults.systemVersion = this.params.version;
479
- }
480
-
481
- process.stdout.write(
482
- String.fromCharCode(27) + ']0;' +
483
- this._params?.name +
484
- String.fromCharCode(7)
485
- );
486
-
487
- DyFM_error_defaults.issuerSystem = this._params.systemName;
488
-
489
- this.overrideDynamoNTSGlobalSettings?.();
490
-
491
- if (DyNTS_global_settings.log_settings.setup) {
492
- DyFM_Log.S_info(`env settings;\n`, {
493
- systemName: DyNTS_global_settings.systemName,
494
- systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
495
- systemVersion: DyNTS_global_settings.systemVersion,
496
- environment: DyNTS_global_settings.env_settings.environment,
497
- /* log_settings: DyNTS_global_settings.log_settings,
498
- env_settings: DyNTS_global_settings.env_settings, */
499
- });
500
- }
501
-
502
- this.globalService = DyNTS_GlobalService.getInstance();
503
- await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
504
- DyNTS_GlobalService.setParams(this.params);
505
-
506
- if (this.getPortSettings) {
507
- this._portSettings = this.getPortSettings();
508
- }
509
-
510
- if (this.getCertificationSettings) {
511
- this._cert = this.getCertificationSettings();
512
- }
513
-
514
- if (this.getApiBasePath) {
515
- DyNTS_global_settings.baseUrl = this.getApiBasePath();
516
- }
517
-
518
- if (this.getRoutingModules) {
519
- this._routingModules = this.getRoutingModules();
520
-
521
- // ezt egyelőre csak tesztelem, nem kerül be
522
- /* if (
523
- !DyNTS_global_settings.dontCreateDefaultRoute &&
524
- !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
525
- ) {
526
- this._routingModules.push(
527
- DyNTS_getStarRoute()
528
- );
529
- } */
530
- }
531
-
532
- if (this._params.dbUri) {
533
- await this.startDB();
534
-
535
- // createEntries csak akkor fut, ha a DB tényleg fel-jött.
536
- // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
537
- // és nem próbálunk meg írni egy nem létező kapcsolatra.
538
- if (this.createEntries && this.systemControls.mongoose.started) {
539
- await this.createEntries();
540
- }
541
- } else {
542
- DyFM_Log.log(
543
- `\nNo database connection created.`,
544
- );
545
- }
546
-
547
- if (this._routingModules?.length) {
548
- if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
549
-
550
- this.setSecurity();
551
-
552
- await this.initExpresses();
553
- await this.startExpresses();
554
-
555
- if (this._security !== DyNTS_RouteSecurity.secure) {
556
- await this.mountOpenRoutes();
557
- }
558
-
559
- if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
560
- await this.mountSecureRoutes();
561
- }
562
-
563
- // Generikus, auth-agnosztikus extension-point: custom middleware az API
564
- // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
565
- await this.mountCustomMiddleware();
566
-
567
- await this.mountStaticClient();
568
-
569
- if (this.logSetup) {
570
- DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
571
- }
572
- } else {
573
- DyFM_Log.warn(
574
- `\nNo routes mounted!`,
575
- );
576
- }
577
-
578
- if (this.getRootServices) {
579
- this._rootServices = await this.getRootServices();
580
- }
581
-
582
- if (this.postProcess) {
583
- await this.postProcess().catch((error: any): void => {
584
- DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
585
- DyNTS_GlobalService.globalErrorHandler?.(error);
586
- });
587
- }
588
-
589
- // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
590
- // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
591
- // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
592
- // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
593
- try {
594
- if (DyNTS_global_settings.memoryGuard?.enabled) {
595
- DyNTS_MemoryGuard.getInstance().install();
596
- }
597
- } catch (memoryGuardError: unknown) {
598
- DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
599
- }
600
-
601
- // BFR-OVERSEER-007 — event-loop-lag diag a MemoryGuard MELLÉ: a „process él, HTTP néma" wedge
602
- // belső mérése (natív histogram, olcsó). Observation-only, sosem dob; a /server/diag olvas belőle.
603
- try {
604
- DyNTS_EventLoopDiag.getInstance().install();
605
- } catch (eventLoopDiagError: unknown) {
606
- DyFM_Log.warn('[DyNTS_EventLoopDiag] auto-install skipped (non-fatal):', eventLoopDiagError);
607
- }
608
-
609
- // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
610
- // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
611
- // OOM. Default-on, observation-only, never throws.
612
- try {
613
- if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
614
- DyNTS_CollectionGrowthMonitor.getInstance().install();
615
- }
616
- } catch (cgmError: unknown) {
617
- DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
618
- }
619
-
620
- if (!extended) {
621
- await this.ready();
622
-
623
- if (this.params.title) {
624
- DyFM_Log.success(this.params.title);
625
- }
626
- DyFM_Log.info(`Version: ${this.params.version}`);
627
- /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
628
- DyFM_Log.H_success(`${this.params.name} started successfully.`);
629
- }
630
- } catch (error) {
631
- this.constructErrors.push(error);
632
-
633
- if (this.deepLog) {
634
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
635
- DyFM_Log.H_error(
636
- `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
637
- `\n\n construct ERRORS:`, this.constructErrors,
638
- '\n\nlast error:', error
639
- );
640
- } else {
641
- DyFM_Log.H_error(
642
- `"${this._params.name}" start failed (in asyncConstruct). `,
643
- `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
644
- '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
645
- );
646
- }
647
- }
648
-
649
- throw new DyFM_Error({
650
- ...this._getDefaultErrorSettings('asyncConstruct', error),
651
-
652
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
653
- additionalContent: {
654
- constructErrors: this.constructErrors,
655
- systemControls: this.systemControls,
656
- systemReadies: {
657
- app: this.systemControls.app.getIsReady(),
658
- mongoose: this.systemControls.mongoose.getIsReady(),
659
- httpServer: this.systemControls.httpServer.getIsReady(),
660
- httpsServer: this.systemControls.httpsServer.getIsReady(),
661
- },
662
- },
663
- });
664
- }
665
- }
666
-
667
- async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
668
- try {
669
- if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
670
-
671
- await DyFM_Async.delay(100);
672
-
673
- let ready: boolean = false;
674
- const start: number = +new Date();
675
-
676
- if (this.constructErrors.length) {
677
- if (this.deepLog) {
678
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
679
- DyFM_Log.H_error(
680
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
681
- `\n construct ERRORS:`, this.constructErrors
682
- );
683
- } else {
684
- DyFM_Log.H_error(
685
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
686
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
687
- );
688
- }
689
- }
690
-
691
- throw new DyFM_Error({
692
- ...this._getDefaultErrorSettings(
693
- 'ready',
694
- new Error(`"${this._params.name}" start failed.`)
695
- ),
696
-
697
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
698
- additionalContent:
699
- this.constructErrors.length === 1 ?
700
- { error: this.constructErrors[0] } :
701
- { errors: this.constructErrors },
702
- });
703
- }
704
-
705
- while (!ready && +new Date() - start < timeout) {
706
- if (this.systemControls.app.init) {
707
- ready = (
708
- this.systemControls.mongoose.getIsReady() &&
709
- this.systemControls.httpServer.getIsReady() &&
710
- this.systemControls.httpsServer.getIsReady()
711
- );
712
- } else {
713
- DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
714
- }
715
-
716
- if (!ready) {
717
- await DyFM_Async.wait(100);
718
- }
719
- }
720
-
721
- if (timeout < +new Date() - start) {
722
- if (this.deepLog) {
723
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
724
- DyFM_Log.H_error(
725
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
726
- `\n construct ERRORS:`, this.constructErrors
727
- );
728
- } else {
729
- DyFM_Log.H_error(
730
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
731
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
732
- );
733
- }
734
- }
735
-
736
- throw new DyFM_Error({
737
- ...this._getDefaultErrorSettings(
738
- 'ready',
739
- new Error(`"${this._params.name}" start failed. TIMEOUT`)
740
- ),
741
-
742
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
743
- additionalContent: {
744
- constructErrors: this.constructErrors,
745
- systemControls: this.systemControls,
746
- systemReadies: {
747
- mongoose: this.systemControls.mongoose.getIsReady(),
748
- httpServer: this.systemControls.httpServer.getIsReady(),
749
- httpsServer: this.systemControls.httpsServer.getIsReady(),
750
- },
751
- },
752
- });
753
- }
754
-
755
- if (this.constructErrors.length) {
756
- if (this.deepLog) {
757
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
758
- DyFM_Log.H_error(
759
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
760
- `\n construct ERRORS:`, this.constructErrors
761
- );
762
- } else {
763
- DyFM_Log.H_error(
764
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
765
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
766
- );
767
- }
768
- }
769
-
770
- throw new DyFM_Error({
771
- ...this._getDefaultErrorSettings(
772
- 'ready',
773
- new Error(`"${this._params.name}" start failed.`)
774
- ),
775
-
776
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
777
- additionalContent: this.constructErrors,
778
- });
779
- }
780
-
781
- if (ready) {
782
- this.systemControls.app.started = true;
783
-
784
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
785
-
786
- return;
787
- }
788
-
789
- this.systemControls.app.started = false;
790
-
791
- let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
792
-
793
- if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
794
- msg += `\nMongoose start failed.`;
795
- }
796
-
797
- if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
798
- msg += `\nHTTP Server start failed.`;
799
- }
800
-
801
- if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
802
- msg += `\nHTTPS Server start failed.`;
803
- }
804
-
805
- DyFM_Log.error(msg, this.constructErrors);
806
-
807
- throw new DyFM_Error({
808
- ...this._getDefaultErrorSettings('ready', new Error(msg)),
809
-
810
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
811
- additionalContent: {
812
- constructErrors: this.constructErrors,
813
- systemControls: this.systemControls,
814
- systemReadies: {
815
- app: this.systemControls.app.getIsReady(),
816
- mongoose: this.systemControls.mongoose.getIsReady(),
817
- httpServer: this.systemControls.httpServer.getIsReady(),
818
- httpsServer: this.systemControls.httpsServer.getIsReady(),
819
- },
820
- },
821
- error: this.constructErrors?.[0] ?? new Error(),
822
- });
823
- } catch (error) {
824
- throw new DyFM_Error({
825
- ...this._getDefaultErrorSettings('ready', error),
826
-
827
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
828
- });
829
- }
830
- }
831
-
832
- protected getSimplifiedConstructErrors(): string[] {
833
- return this.constructErrors.map((error: any): any => {
834
- if (error instanceof DyFM_Error) {
835
- return error.getErrorSimplified();
836
- } else {
837
- return error;
838
- }
839
- });
840
- }
841
-
842
- async stop(dontLog?: boolean): Promise<void> {
843
- try {
844
- DyFM_Log.info('\nstopping server...\n');
845
-
846
- await this.ready();
847
-
848
- if (this.started) {
849
-
850
- if (this.systemControls.mongoose.init) {
851
- DyFM_Log.info(`\nstopping Mongoose....`);
852
-
853
- let tryCount: number = 0;
854
-
855
- while (
856
- !this.systemControls.mongoose.started &&
857
- !this.constructErrors.length &&
858
- tryCount++ < 10
859
- ) {
860
- DyFM_Log.warn(`Mongoose not even started yet....`);
861
- await DyFM_Async.wait(second);
862
- }
863
- this.systemControls.mongoose.started = false;
864
-
865
- if (this.mongoose) {
866
- await DyFM_Array.asyncForEach(
867
- Object.keys(this.mongoose.models),
868
- async (modelName): Promise<void> => {
869
- this.mongoose.deleteModel(modelName);
870
- }
871
- );
872
-
873
- const disconnect: Promise<void> = new Promise((resolve): void => {
874
- this.mongoose.connection.on('disconnecting', (): void => {
875
- resolve();
876
- });
877
- });
878
-
879
- await this.mongoose.disconnect();
880
- await this.mongoose.connection.close();
881
- await disconnect;
882
-
883
- this.mongoose.connection.removeAllListeners();
884
-
885
- while (
886
- this.mongoose.connection.readyState !== 0 &&
887
- !this.constructErrors.length
888
- ) {
889
- DyFM_Log.warn(`\nMongoose still not disconnected....`);
890
- await DyFM_Async.wait(second);
891
- }
892
- } else {
893
- DyFM_Log.error(`\nMongoose not found.`);
894
- }
895
- this.systemControls.mongoose.init = false;
896
- }
897
-
898
- if (this.systemControls.httpServer.init) {
899
- this.systemControls.httpServer.started = false;
900
-
901
- if (this.httpServer) {
902
- await new Promise((resolve): void => {
903
- this.httpServer.close(resolve);
904
- });
905
- } else {
906
- DyFM_Log.error(`\nHTTP Server not found.`);
907
- }
908
- this.systemControls.httpServer.init = false;
909
- }
910
-
911
- if (this.systemControls.httpsServer.init) {
912
- this.systemControls.httpsServer.started = false;
913
-
914
- if (this.httpsServer) {
915
- await new Promise((resolve): void => {
916
- this.httpsServer.close(resolve);
917
- });
918
- } else {
919
- DyFM_Log.error(`\nHTTPS Server not found.`);
920
- }
921
- this.systemControls.httpsServer.init = false;
922
- }
923
-
924
- await DyFM_Async.wait(second);
925
-
926
- if (!dontLog) {
927
- DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
928
- }
929
- }
930
- } catch (error) {
931
- throw new DyFM_Error({
932
- ...this._getDefaultErrorSettings('stop', error),
933
-
934
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
935
- });
936
- }
937
- }
938
-
939
- /**
940
- *
941
- */
942
- private async startDB(): Promise<void> {
943
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
944
- else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
945
-
946
- if (!this._params.dbUri) {
947
- throw new DyFM_Error({
948
- ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
949
-
950
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
951
- });
952
- }
953
-
954
- if (!this._params.dbOptions) {
955
- throw new DyFM_Error({
956
- ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
957
-
958
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
959
- });
960
- }
961
-
962
- if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
963
- throw new DyFM_Error({
964
- ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
965
-
966
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
967
- });
968
- }
969
-
970
- try {
971
- await new Promise<void>(
972
- (resolve, reject): void => {
973
- this.systemControls.mongoose.init = true;
974
-
975
- this.mongoose.connection
976
- .once('open', (): void => {
977
- this.systemControls.mongoose.started = true;
978
- DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
979
-
980
- resolve();
981
-
982
- // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
983
- // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
984
- // compete with boot-readiness. We delay it well past the deploy health-probe window so a
985
- // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
986
- // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
987
- // rebuilds a live index — see ensureRetentionTtlIndex.)
988
- const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
989
- void this.installRetentionTtlIndexes();
990
- }, 30000);
991
- if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
992
- })
993
- .on('error', (error): void => {
994
- if (!this.systemControls.mongoose.started) {
995
- // Initial DB-csatlakozás sikertelen:
996
- // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
997
- // App startup-ot (nincs constructErrors push, nincs reject).
998
- // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
999
- // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
1000
- // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
1001
- this.systemControls.mongoose.init = false;
1002
-
1003
- const d_error: DyFM_Error = new DyFM_Error({
1004
- ...this._getDefaultErrorSettings('startDB', error),
1005
-
1006
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
1007
- message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
1008
- `ERROR: ${error}`,
1009
- level: DyFM_ErrorLevel.serious,
1010
- });
1011
-
1012
- DyFM_Log.H_error(
1013
- `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
1014
- `\nServer will continue WITHOUT DB connection.` +
1015
- `\nDB-using endpoints will fail at runtime until connection recovers.`
1016
- );
1017
-
1018
- if (this.debugLog) DyFM_Log.S_error(
1019
- `\nMongoDB connect ERROR: `,
1020
- error
1021
- );
1022
-
1023
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1024
-
1025
- resolve();
1026
-
1027
- } else {
1028
- if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1029
-
1030
- const d_error: DyFM_Error = new DyFM_Error({
1031
- ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1032
-
1033
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1034
- message: `MongoDB ERROR: ${error}`,
1035
- level: DyFM_ErrorLevel.critical,
1036
- });
1037
-
1038
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1039
- }
1040
- });
1041
-
1042
- try {
1043
- this.mongoose.connect(
1044
- this._params.dbUri,
1045
- this._params.dbOptions
1046
- /* {
1047
- directConnection: true,
1048
- } */
1049
- );
1050
- } catch (error) {
1051
- throw new DyFM_Error({
1052
- ...this._getDefaultErrorSettings('startDB', error),
1053
-
1054
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1055
- });
1056
- }
1057
- }
1058
- );
1059
- } catch (error) {
1060
- throw new DyFM_Error({
1061
- ...this._getDefaultErrorSettings('startDB', error),
1062
-
1063
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1064
- });
1065
- }
1066
-
1067
- // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1068
- // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1069
- // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1070
- // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1071
- // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1072
- // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1073
- // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1074
- try {
1075
- startMongoReconnectGuard({
1076
- getReadyState: (): number => this.mongoose.connection.readyState,
1077
- reconnect: async (): Promise<void> => {
1078
- await this.mongoose.disconnect().catch((): void => undefined);
1079
- await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1080
- },
1081
- log: (msg: string): void => DyFM_Log.warn(msg),
1082
- });
1083
- } catch (guardErr) {
1084
- DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1085
- }
1086
- }
1087
-
1088
- /**
1089
- * FR-258 / SR-2 — install MongoDB TTL indexes for every data-model that declared `retention`.
1090
- *
1091
- * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1092
- * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1093
- * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1094
- * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1095
- * against the unbounded-collection-growth → in-memory-load → GC-thrash/OOM class.
1096
- *
1097
- * Guarantees:
1098
- * - **Non-fatal** — any error is logged but NEVER blocks startup (called fire-and-forget).
1099
- * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1100
- * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1101
- * (the field index is restored immediately, so query coverage is preserved).
1102
- */
1103
- private async installRetentionTtlIndexes(): Promise<void> {
1104
- try {
1105
- const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1106
- let ensured: number = 0;
1107
-
1108
- for (const service of services) {
1109
- const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1110
- if (!ttlSeconds) { continue; }
1111
-
1112
- const dataName: string = service.dataParams.dataName;
1113
- // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1114
- const collection: DyNTS_TtlIndexCollection | undefined =
1115
- (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1116
- if (!collection || typeof collection.createIndex !== 'function') { continue; }
1117
-
1118
- try {
1119
- const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1120
- if (action === 'created') {
1121
- ensured++;
1122
- if (this.logSetup) {
1123
- DyFM_Log.success(
1124
- `[FR-258 retention] TTL index created on "${dataName}" — ` +
1125
- `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1126
- );
1127
- }
1128
- } else if (action === 'differs') {
1129
- // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1130
- DyFM_Log.warn(
1131
- `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1132
- `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1133
- `Apply the change via maintenance if intended.`,
1134
- );
1135
- }
1136
- } catch (idxErr: unknown) {
1137
- DyFM_Log.warn(
1138
- `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1139
- `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1140
- );
1141
- }
1142
- }
1143
-
1144
- if (ensured > 0) {
1145
- DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1146
- }
1147
- } catch (err: unknown) {
1148
- DyFM_Log.warn(
1149
- `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1150
- `${err instanceof Error ? err.message : String(err)}`,
1151
- );
1152
- }
1153
- }
1154
-
1155
- /**
1156
- * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1157
- * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1158
- * - no existing `__created` index → create it → `'created'`
1159
- * - existing with the SAME TTL → no-op → `'noop'`
1160
- * - existing with a DIFFERENT TTL / non-TTL → leave it as-is → `'differs'` (warn only — NO drop+recreate)
1161
- *
1162
- * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1163
- * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1164
- * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1165
- * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1166
- * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1167
- */
1168
- static async ensureRetentionTtlIndex(
1169
- collection: DyNTS_TtlIndexCollection,
1170
- ttlSeconds: number,
1171
- ): Promise<DyNTS_TtlIndexAction> {
1172
- const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1173
- ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1174
- : [];
1175
- const existing: DyNTS_TtlIndexInfo | undefined =
1176
- existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1177
-
1178
- if (!existing) {
1179
- await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1180
- return 'created';
1181
- }
1182
- if (existing.expireAfterSeconds === ttlSeconds) {
1183
- return 'noop';
1184
- }
1185
- // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1186
- // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1187
- return 'differs';
1188
- }
1189
-
1190
- /**
1191
- *
1192
- */
1193
- private async initExpresses(): Promise<void> {
1194
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1195
-
1196
- try {
1197
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1198
- if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1199
- let errorMsg: string =
1200
- `\nYou have open routes, but httpPort is not set!` +
1201
- `\nThere are ${this._routingModules.filter(
1202
- m => m.security != DyNTS_RouteSecurity.secure
1203
- ).length} open/both routes` +
1204
- `\nroot security: ${this._security}` +
1205
- `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1206
-
1207
- errorMsg += '\n\nThe routes setted to use open server:';
1208
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1209
- if (module.security != DyNTS_RouteSecurity.secure) {
1210
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1211
- errorMsg += `\n subroutes using open sever:`;
1212
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1213
- if (endpoint.security != DyNTS_RouteSecurity.secure) {
1214
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1215
- }
1216
- });
1217
- }
1218
- });
1219
-
1220
- const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1221
- const errorStack: string[] = error.stack.split('\n');
1222
-
1223
- errorStack.splice(1, 2);
1224
- error.stack = errorStack.join('\n');
1225
-
1226
- DyFM_Log.error(errorMsg);
1227
-
1228
- throw error;
1229
- }
1230
-
1231
- await this.initOpenExpress();
1232
- }
1233
-
1234
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1235
- if (!this._cert || !this._portSettings.httpsPort) {
1236
- let errorMsg: string =
1237
- `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1238
- `\nThere are ${this._routingModules.filter(
1239
- m => m.security && m.security !== DyNTS_RouteSecurity.open
1240
- ).length} secure routes` +
1241
- `\nroot security: ${this._security}` +
1242
- `\nset...` +
1243
- `\n(missing exact howto...)` +
1244
- /* `\n httpsPort and` +
1245
- `\n cert: {` +
1246
- `\n keyPath: FileSystem.PathLike,` +
1247
- `\n certPath: FileSystem.PathLike,` +
1248
- `\n }` + */
1249
- `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1250
-
1251
- errorMsg += '\n\nThe routes setted to use secure server:';
1252
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1253
- if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1254
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1255
- errorMsg += `\n location: ${module.stackLocation}`;
1256
- errorMsg += `\n subroutes using secure sever:`;
1257
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1258
- if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1259
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1260
- errorMsg += `\n location: ${endpoint.stackLocation}`;
1261
- }
1262
- });
1263
- }
1264
- });
1265
-
1266
- const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1267
- const errorStack: string[] = error.stack.split('\n');
1268
-
1269
- errorStack.splice(1, 2);
1270
- error.stack = errorStack.join('\n');
1271
-
1272
- DyFM_Log.error(errorMsg);
1273
-
1274
- throw error;
1275
- }
1276
-
1277
- await this.initSecureExpress();
1278
- }
1279
- } catch (error) {
1280
- throw new DyFM_Error({
1281
- ...this._getDefaultErrorSettings('initExpresses', error),
1282
-
1283
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1284
- });
1285
- }
1286
- }
1287
-
1288
- /**
1289
- *
1290
- */
1291
- protected async initOpenExpress(): Promise<void> {
1292
- if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1293
- this.openExpress = Express();
1294
- this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1295
- this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1296
- this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1297
- // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (az OPTIONS preflight-válaszok is kapják).
1298
- this.mountSecurityHeaders(this.openExpress);
1299
- // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1300
- this.mountCors(this.openExpress);
1301
- // FR-292 — a deployolt app-verzio minden valaszon. A CORS UTAN kell, mert az
1302
- // `Access-Control-Expose-Headers`-hoz HOZZAFUZ (kulonben a CORS felulirna).
1303
- this.mountAppVersionHeader(this.openExpress);
1304
- // BFR-OVERSEER-009 — opt-in auto-load-shed 503 CRITICAL memória-nyomásnál (esszenciális utak kivételével).
1305
- if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1306
- this.openExpress.use(DyNTS_createLoadShedMiddleware());
1307
- }
1308
- }
1309
-
1310
- /**
1311
- *
1312
- */
1313
- protected async initSecureExpress(): Promise<void> {
1314
- if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1315
- this.secureExpress = Express();
1316
- this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1317
- this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1318
- // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (mint az open expressen).
1319
- this.mountSecurityHeaders(this.secureExpress);
1320
- // FR-041 — CORS allowlist enforcement (same as open express).
1321
- this.mountCors(this.secureExpress);
1322
- // FR-292 — a deployolt app-verzio minden valaszon (mint az open expressen).
1323
- this.mountAppVersionHeader(this.secureExpress);
1324
- // BFR-OVERSEER-009 — opt-in auto-load-shed 503 (mint az open expressen).
1325
- if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1326
- this.secureExpress.use(DyNTS_createLoadShedMiddleware());
1327
- }
1328
-
1329
- const options = {
1330
- key: FileSystem.readFileSync(this._cert.keyPath),
1331
- cert: FileSystem.readFileSync(this._cert.certPath),
1332
- maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1333
- };
1334
-
1335
- this.httpsServer = Https.createServer(options, this.secureExpress);
1336
- }
1337
-
1338
- /**
1339
- *
1340
- */
1341
- private async startExpresses(): Promise<void> {
1342
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1343
-
1344
- try {
1345
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1346
- await new Promise<void>((resolve, reject): void => {
1347
- this.systemControls.httpsServer.init = true;
1348
- this.httpsServer
1349
- .listen(
1350
- this._portSettings.httpsPort,
1351
- this.params.secureHost,
1352
- this.params.expressBacklog,
1353
- (): void => {
1354
- this.systemControls.httpsServer.started = true;
1355
- DyFM_Log.success(
1356
- `\nHTTPS (secure) server is listening on port: ` +
1357
- `${this.params.secureHost}:${this._portSettings.httpsPort}`
1358
- );
1359
-
1360
- resolve();
1361
- })
1362
- .on('error', (error): void => {
1363
- if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1364
-
1365
- if (!this.systemControls.httpsServer.started) {
1366
- const d_error: DyFM_Error = new DyFM_Error({
1367
- ...this._getDefaultErrorSettings('startExpresses', error),
1368
-
1369
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1370
- message: `HTTPS (secure) start server ERROR`,
1371
- });
1372
-
1373
- this.constructErrors.push(d_error);
1374
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1375
-
1376
- reject(d_error);
1377
-
1378
- } else {
1379
- const d_error: DyFM_Error = new DyFM_Error({
1380
- ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1381
-
1382
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1383
- message: `HTTPS (secure) server ERROR`,
1384
- level: DyFM_ErrorLevel.serious,
1385
- });
1386
-
1387
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1388
- }
1389
- })
1390
- .on('uncaughtException', (exception): void => {
1391
- const d_error: DyFM_Error = new DyFM_Error({
1392
- ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1393
-
1394
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1395
- message: `HTTPS (secure) server uncaughtException`,
1396
- level: DyFM_ErrorLevel.critical,
1397
- });
1398
-
1399
- if (this.debugLog) DyFM_Log.warn(
1400
- `\nHTTPS (secure) server uncaughtException`,
1401
- d_error
1402
- );
1403
-
1404
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1405
- });
1406
- });
1407
- }
1408
-
1409
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1410
- this.systemControls.httpServer.init = true;
1411
- await new Promise<void>((resolve, reject): void => {
1412
- this.httpServer = this.openExpress
1413
- .listen(
1414
- this._portSettings.httpPort,
1415
- this.params.openHost,
1416
- this.params.expressBacklog,
1417
- (): void => {
1418
- this.systemControls.httpServer.started = true;
1419
-
1420
- const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1421
-
1422
- if (this._portSettings.httpPort === 0) {
1423
- DyFM_Log.H_warn(
1424
- `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1425
- `\n (httpPort was set to 0 — this is intended for testing only)`
1426
- );
1427
- }
1428
-
1429
- DyFM_Log.success(
1430
- `\nHTTP (open) server is listening on port: ` +
1431
- `${this.params.openHost}:${resolvedPort}`
1432
- );
1433
-
1434
- resolve();
1435
- }
1436
- )
1437
- .on('error', (error): void => {
1438
- if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1439
-
1440
- if (!this.systemControls.httpServer.started) {
1441
- const d_error: DyFM_Error = new DyFM_Error({
1442
- ...this._getDefaultErrorSettings('startExpresses', error),
1443
-
1444
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1445
- message: `HTTP (open) start server ERROR`,
1446
- });
1447
-
1448
- this.constructErrors.push(d_error);
1449
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1450
-
1451
- reject(d_error);
1452
-
1453
- } else {
1454
- const d_error: DyFM_Error = new DyFM_Error({
1455
- ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1456
-
1457
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1458
- message: `HTTP (open) server ERROR`,
1459
- level: DyFM_ErrorLevel.serious,
1460
- });
1461
-
1462
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1463
- }
1464
- })
1465
- .on('uncaughtException', (exception): void => {
1466
- const d_error: DyFM_Error = new DyFM_Error({
1467
- ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1468
-
1469
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1470
- message: `HTTP (open) server uncaughtException`,
1471
- level: DyFM_ErrorLevel.critical,
1472
- });
1473
-
1474
- if (this.debugLog) {
1475
- DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1476
- }
1477
-
1478
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1479
- });
1480
- });
1481
- }
1482
- } catch (error) {
1483
- throw new DyFM_Error({
1484
- ...this._getDefaultErrorSettings('startExpresses', error),
1485
-
1486
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1487
- });
1488
- }
1489
- }
1490
-
1491
- /**
1492
- *
1493
- */
1494
- private async expressErrorHandling(error, req, res, next): Promise<void> {
1495
- try {
1496
- if (error) {
1497
- const d_error: DyFM_Error = new DyFM_Error({
1498
- ...this._getDefaultErrorSettings('expressErrorHandling', error),
1499
-
1500
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1501
- message: `Express ERROR`,
1502
- additionalContent: {
1503
- req,
1504
- res,
1505
- },
1506
- level: DyFM_ErrorLevel.error,
1507
- });
1508
-
1509
- await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1510
-
1511
- // Kliens-safe strip (BFR-FDPAUTHSERVICE-002): az express-error út eddig NYERS error-t küldött
1512
- // (0 strip) — DyFM-nél belső stack/verzió/issuer, axios-jellegű error-nál akár auth-header is
1513
- // kimehetett. A strip-szabályok SSOT-ja a DyNTS_ClientSafeError_Util.
1514
- res.send(DyNTS_ClientSafeError_Util.toClientSafe(error))
1515
- } else {
1516
- DyFM_Log.H_error(
1517
- 'WTF??? express error; without error?...' +
1518
- '\nerr:', error,
1519
- '\nreq:', req,
1520
- '\nres:', res
1521
- );
1522
- }
1523
- } catch (error) {
1524
- DyFM_Log.H_error(
1525
- 'MULTILEVEL ERROR (expressErrorHandling)....' +
1526
- '\n', error
1527
- );
1528
- }
1529
- }
1530
-
1531
- /**
1532
- *
1533
- */
1534
- private async mountSecureRoutes (): Promise<void> {
1535
- try {
1536
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1537
-
1538
- if (!this.secureExpress) {
1539
- throw new Error(
1540
- 'secureExpress was not initialized. ' +
1541
- 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1542
- '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1543
- '\n\nYou need to set cert files in getCertificationSettings.'
1544
- );
1545
- }
1546
-
1547
- this.secureExpress.use(
1548
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1549
- );
1550
-
1551
- await DyFM_Array.asyncForEach(
1552
- this._routingModules,
1553
- async (module: DyNTS_RoutingModule): Promise<void> => {
1554
- if (module.security !== DyNTS_RouteSecurity.open) {
1555
- if (this.logSetup) {
1556
- DyFM_Log.log(`route mount (secure): ${module.route}`);
1557
- }
1558
-
1559
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1560
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1561
- );
1562
-
1563
- if (1 < existingRoutes.length) {
1564
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1565
- /* const errorStack: string[] = error.stack.split('\n');
1566
-
1567
- errorStack.splice(1, 4);
1568
- error.stack = errorStack.join('\n'); */
1569
- error.stack = module.stackLocation;
1570
-
1571
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1572
-
1573
- throw new DyFM_Error({
1574
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1575
-
1576
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1577
- message: `ROUTE DUPLICATION: ${module.route}`,
1578
- });
1579
- }
1580
-
1581
- this.secureExpress.use(module.route, module.secureRouter);
1582
- }
1583
- }
1584
- );
1585
- } catch (error) {
1586
- throw new DyFM_Error({
1587
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1588
-
1589
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1590
- });
1591
- }
1592
- }
1593
-
1594
- /**
1595
- *
1596
- */
1597
- private async mountOpenRoutes(): Promise<void> {
1598
- try {
1599
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1600
-
1601
- if (!this.openExpress) {
1602
- throw new Error(
1603
- 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1604
- '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1605
- );
1606
- }
1607
-
1608
- this.openExpress.use(
1609
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1610
- );
1611
-
1612
- await DyFM_Array.asyncForEach(
1613
- this._routingModules,
1614
- async (module: DyNTS_RoutingModule): Promise<void> => {
1615
- if (module.security !== DyNTS_RouteSecurity.secure) {
1616
- if (this.logSetup) {
1617
- DyFM_Log.log(`route mount (open): ${module.route}`);
1618
- }
1619
-
1620
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1621
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1622
- );
1623
-
1624
- if (1 < existingRoutes.length) {
1625
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1626
- /* const errorStack: string[] = error.stack.split('\n');
1627
-
1628
- errorStack.splice(1, 4);
1629
- error.stack = errorStack.join('\n'); */
1630
- error.stack = module.stackLocation;
1631
-
1632
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1633
-
1634
- throw new DyFM_Error({
1635
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1636
-
1637
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1638
- message: `ROUTE DUPLICATION: ${module.route}`,
1639
- });
1640
- }
1641
-
1642
- this.openExpress.use(module.route, module.openRouter);
1643
- }
1644
- }
1645
- );
1646
- } catch (error) {
1647
- throw new DyFM_Error({
1648
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1649
-
1650
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1651
- });
1652
- }
1653
- }
1654
-
1655
- /**
1656
- * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1657
- * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1658
- * adds the canonical `Access-Control-*` companion headers, and short-circuits
1659
- * the OPTIONS preflight with a 204.
1660
- *
1661
- * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1662
- * back-compat for apps that have always been same-origin and never needed
1663
- * CORS (the typical pre-FR-041 case).
1664
- *
1665
- * Why hand-rolled instead of the `cors` npm package:
1666
- * - ~30 lines, zero new dependency.
1667
- * - Full control over Vary/credentials/preflight semantics.
1668
- * - Aligns with FDP "no unnecessary deps" philosophy.
1669
- */
1670
- /**
1671
- * BFR-011 / SEC-R2-8 — security response-headerek mountolása (a `mountCors` tükörképe).
1672
- * A `DyNTS_global_settings.securityHeaders` alapján (default-ON) minden válaszra ráteszi a
1673
- * biztonsági headereket + eltávolítja az `x-powered-by`-t. A CORS-mount ELŐTT hívandó, hogy az
1674
- * OPTIONS preflight-válaszok (amiket a mountCors 204-gyel rövidre zár) is megkapják.
1675
- */
1676
- protected mountSecurityHeaders(express: Express.Application): void {
1677
- const settings: DyNTS_SecurityHeaders_Settings | undefined = DyNTS_global_settings.securityHeaders;
1678
- if (!settings || !settings.enabled) {
1679
- return;
1680
- }
1681
-
1682
- if (settings.removePoweredBy !== false) {
1683
- express.disable('x-powered-by');
1684
- }
1685
-
1686
- express.use(DyNTS_createSecurityHeadersMiddleware(
1687
- settings,
1688
- DyNTS_getEnvironment_settings().environment,
1689
- ));
1690
- }
1691
-
1692
- /**
1693
- * FR-292 — a deployolt app-verziot minden valaszra rateszi (`X-App-Version`), hogy a
1694
- * bongeszoben NYITVA HAGYOTT SPA eszrevegye, ha kozben ujabb kliens-build ment ki.
1695
- *
1696
- * Nem polling: a jelzes a MAR MENO API-hivasokon utazik. Az `enabled` default TRUE — egy
1697
- * informativ response-header, ami se PII-t, se belso reszletet nem szivarogtat, viszont
1698
- * enelkul minden app kulon-kulon epitene ugyanezt.
1699
- */
1700
- protected mountAppVersionHeader(express: Express.Application): void {
1701
- const settings: DyNTS_AppVersionHeader_Settings | undefined = DyNTS_global_settings.appVersionHeader;
1702
- if (settings?.enabled === false) {
1703
- return;
1704
- }
1705
- express.use(DyNTS_createAppVersionHeaderMiddleware(
1706
- (): string => DyNTS_global_settings.systemVersion,
1707
- settings?.headerName,
1708
- ));
1709
- }
1710
-
1711
- protected mountCors(express: Express.Application): void {
1712
- const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1713
- if (!settings) {
1714
- return;
1715
- }
1716
-
1717
- const allowCreds: boolean = settings.allowCredentials !== false;
1718
- const methods: string[] = settings.allowedMethods ?? [
1719
- 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1720
- ];
1721
- const headers: string[] = settings.allowedHeaders ?? [
1722
- 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1723
- ];
1724
- const exposed: string[] = settings.exposedHeaders ?? [
1725
- 'Content-Length', 'Content-Type',
1726
- ];
1727
- const maxAge: number = settings.maxAgeSeconds ?? 86400;
1728
-
1729
- const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1730
- if (settings.allowedOrigins === '*') return true;
1731
- if (typeof settings.allowedOrigins === 'function') {
1732
- return settings.allowedOrigins(origin);
1733
- }
1734
- return settings.allowedOrigins.includes(origin);
1735
- };
1736
-
1737
- express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1738
- const origin: string | undefined = req.headers.origin;
1739
- if (origin && isAllowed(origin)) {
1740
- // Echo the matching origin (NOT wildcard) because credentials require it.
1741
- res.setHeader('Access-Control-Allow-Origin', origin);
1742
- if (allowCreds) {
1743
- res.setHeader('Access-Control-Allow-Credentials', 'true');
1744
- }
1745
- res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1746
- res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1747
- res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1748
- res.setHeader('Access-Control-Max-Age', String(maxAge));
1749
- res.setHeader('Vary', 'Origin');
1750
- }
1751
- if (req.method === 'OPTIONS') {
1752
- res.status(204).end();
1753
- return;
1754
- }
1755
- next();
1756
- });
1757
- }
1758
-
1759
- /**
1760
- * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1761
- * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1762
- * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1763
- * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1764
- * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1765
- */
1766
- private async mountCustomMiddleware(): Promise<void> {
1767
- if (!this.registerCustomMiddleware) {
1768
- return;
1769
- }
1770
-
1771
- if (this.openExpress) {
1772
- await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1773
- }
1774
-
1775
- if (this.secureExpress) {
1776
- await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1777
- }
1778
-
1779
- if (this.logSetup) {
1780
- DyFM_Log.log('\nCustom middleware registered (pre-static).');
1781
- }
1782
- }
1783
-
1784
- /**
1785
- * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1786
- * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1787
- * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1788
- * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1789
- */
1790
- private async mountStaticClient(): Promise<void> {
1791
- const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1792
- if (!settings) {
1793
- return;
1794
- }
1795
-
1796
- const absoluteRoot: string = Path.isAbsolute(settings.root)
1797
- ? settings.root
1798
- : Path.resolve(process.cwd(), settings.root);
1799
-
1800
- const hasAssetCache: boolean =
1801
- settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1802
- const staticOptions: { setHeaders: (res: Express.Response, filePath: string) => void } | undefined =
1803
- hasAssetCache && settings.assetCacheMaxAge !== undefined
1804
- ? {
1805
- setHeaders: (res: Express.Response, filePath: string): void => {
1806
- // A HTML entry-fájlok (index.html) no-cache-t kapnak, a hash-elt asset-ek
1807
- // immutable long-cache-t — lásd DyNTS_resolveStaticCacheControlHeader (served-stale-index fix).
1808
- res.setHeader(
1809
- 'Cache-Control',
1810
- DyNTS_resolveStaticCacheControlHeader({
1811
- filePath: filePath,
1812
- assetCacheMaxAge: settings.assetCacheMaxAge!,
1813
- assetCacheImmutable: settings.assetCacheImmutable === true,
1814
- }),
1815
- );
1816
- },
1817
- }
1818
- : undefined;
1819
-
1820
- const staticMiddleware: Express.Handler =
1821
- staticOptions
1822
- ? Express.static(absoluteRoot, staticOptions)
1823
- : Express.static(absoluteRoot);
1824
-
1825
- const fallbackMaxAge: number =
1826
- settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1827
-
1828
- // API-namespace guard (BFR-DYNAMOBUILDER-001): a catch-all fallback NE fedje az API-prefixeket —
1829
- // egy ismeretlen `GET /api/...` 404 JSON-t kapjon, ne megtévesztő `200 + index.html`-t.
1830
- // Konfigurálható (fallbackExcludePrefixes); default a bevett FDP namespace-pár.
1831
- const excludePrefixes: string[] = settings.fallbackExcludePrefixes ?? ['/api', '/auth-api'];
1832
- const isApiNamespacePath = (path: string): boolean =>
1833
- excludePrefixes.some((prefix: string): boolean => path === prefix || path.startsWith(`${prefix}/`));
1834
-
1835
- if (this.openExpress) {
1836
- this.openExpress.use('/', staticMiddleware);
1837
- if (settings.fallbackPath) {
1838
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1839
- if (isApiNamespacePath(req.path)) {
1840
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1841
- return;
1842
- }
1843
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1844
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1845
- });
1846
- } else {
1847
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1848
- if (isApiNamespacePath(req.path)) {
1849
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1850
- return;
1851
- }
1852
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1853
- });
1854
- }
1855
- }
1856
-
1857
- if (this.secureExpress) {
1858
- this.secureExpress.use('/', staticMiddleware);
1859
- if (settings.fallbackPath) {
1860
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1861
- if (isApiNamespacePath(req.path)) {
1862
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1863
- return;
1864
- }
1865
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1866
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1867
- });
1868
- } else {
1869
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1870
- if (isApiNamespacePath(req.path)) {
1871
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1872
- return;
1873
- }
1874
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1875
- });
1876
- }
1877
- }
1878
-
1879
- if (this.logSetup) {
1880
- DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1881
- }
1882
- }
1883
-
1884
- /**
1885
- *
1886
- */
1887
- private setSecurity(): void {
1888
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1889
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1890
- if (!module.security) {
1891
- DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1892
-
1893
- } else if (!this._security) {
1894
- this._security = module.security;
1895
-
1896
- } else if (this._security !== module.security) {
1897
- this._security = DyNTS_RouteSecurity.both;
1898
- }
1899
- });
1900
-
1901
- if (!this._security) {
1902
- let msg = `Could not set security for the server! (${this.security})`;
1903
-
1904
- msg += '\n RoutingModules:';
1905
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1906
- msg += `\n ${module.route} (security: ${module.security})`;
1907
- });
1908
-
1909
- if (this._routingModules.length === 0) {
1910
- msg += '\n - no RoutingModule found -\n';
1911
- }
1912
- DyFM_Log.warn(msg);
1913
- }
1914
- }
1915
-
1916
- private _getDefaultErrorSettings(
1917
- fnName: string,
1918
- error: DyFM_AnyError
1919
- ): DyFM_Error_Settings {
1920
- return {
1921
- status: (error as DyFM_Error)?.___status ?? 500,
1922
- message: (error as Error)?.message ??
1923
- (error as DyFM_Error)?._message ??
1924
- `${fnName} was UNSUCCESSFUL (NTS)`,
1925
- userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1926
- addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1927
- issuerService: `${this?.constructor?.name}-DyNTS_App`,
1928
- level: DyFM_ErrorLevel.fatal,
1929
- error: error,
1930
- systemVersion: DyNTS_global_settings.systemVersion,
1931
- };
1932
- }
1933
-
1934
- /**
1935
- * MISSING Description (TODO)
1936
- */
1937
- abstract getAppParams(): DyNTS_App_Params;
1938
-
1939
- /**
1940
- * MISSING Description (TODO)
1941
- */
1942
- abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1943
-
1944
- /**
1945
- * MISSING Description (TODO)
1946
- */
1947
- abstract getPortSettings(): DyNTS_Http_Settings;
1948
-
1949
- /**
1950
- * MISSING Description (TODO)
1951
- */
1952
- overrideDynamoNTSGlobalSettings?(): void;
1953
-
1954
- /**
1955
- * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1956
- * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1957
- */
1958
- getApiBasePath?(): string;
1959
-
1960
- /**
1961
- * MISSING Description (TODO)
1962
- */
1963
- getRoutingModules?(): DyNTS_RoutingModule[];
1964
-
1965
- /**
1966
- * MISSING Description (TODO)
1967
- */
1968
- getRootServices?(): Promise<any[]>;
1969
-
1970
- /**
1971
- * MISSING Description (TODO)
1972
- */
1973
- getCertificationSettings?(): DyNTS_Certification_Settings;
1974
-
1975
- /**
1976
- * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1977
- * Opcionális fallbackPath pl. SPA index.html-hez.
1978
- */
1979
- getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1980
-
1981
- /**
1982
- * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1983
- * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1984
- * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1985
- * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1986
- * Ha undefined → no CORS headers, no preflight handling — back-compat.
1987
- */
1988
- getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1989
-
1990
- /**
1991
- * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1992
- * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1993
- * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1994
- * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1995
- * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1996
- */
1997
- registerCustomMiddleware?(
1998
- express: Express.Application,
1999
- security: DyNTS_RouteSecurity,
2000
- ): void | Promise<void>;
2001
-
2002
- /**
2003
- * MISSING Description (TODO)
2004
- */
2005
- createEntries?(): Promise<void>;
2006
-
2007
- /**
2008
- * MISSING Description (TODO)
2009
- */
2010
- postProcess?(): Promise<void>;
2011
-
2012
- }
1
+
2
+ import Mongoose = require('mongoose');
3
+ import Express = require('express');
4
+ /* import Mongoose from 'mongoose';
5
+ import Express from 'express'; */
6
+
7
+ import * as BodyParser from 'body-parser';
8
+ import * as FileSystem from 'fs';
9
+ import * as Http from 'http';
10
+ import * as Https from 'https';
11
+ import * as Path from 'path';
12
+ import * as dotenv from 'dotenv'
13
+
14
+ /* import { version } from '../../../package.json'; */
15
+
16
+ import {
17
+ DyFM_AnyError,
18
+ DyFM_Array,
19
+ DyFM_Async,
20
+ DyFM_Error,
21
+ DyFM_error_defaults,
22
+ DyFM_Error_Settings,
23
+ DyFM_ErrorLevel,
24
+ DyFM_Log,
25
+ DyFM_resolveRetentionTtlSeconds,
26
+ megabyte,
27
+ second
28
+ } from '@futdevpro/fsm-dynamo';
29
+
30
+ import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
+ import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
+ import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
+ import { DyNTS_ClientSafeError_Util } from '../../_collections/client-safe-error.util';
34
+ import { DyNTS_getEnvironment_settings } from '../../_collections/get-environment-settings.util';
35
+ import { DyNTS_createSecurityHeadersMiddleware } from '../../_collections/security-headers.util';
36
+ import { DyNTS_createLoadShedMiddleware } from '../../_collections/load-shed.util';
37
+ import { DyNTS_createAppVersionHeaderMiddleware } from '../../_collections/app-version-header.util';
38
+ import { DyNTS_AppVersionHeader_Settings } from '../../_models/interfaces/app-version-header-settings.interface';
39
+ import { DyNTS_SecurityHeaders_Settings } from '../../_models/interfaces/security-headers-settings.interface';
40
+ import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
41
+ import { DyNTS_resolveStaticCacheControlHeader } from '../../_collections/static-cache-control.util';
42
+ import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
43
+ import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
44
+ import {
45
+ DyNTS_AppSystemControls
46
+ } from '../../_models/control-models/app-system-controls.control-model';
47
+ import {
48
+ DyNTS_Endpoint_Params
49
+ } from '../../_models/control-models/endpoint-params.control-model';
50
+ import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
51
+ import {
52
+ DyNTS_Certification_Settings
53
+ } from '../../_models/interfaces/certification-settings.interface';
54
+ import {
55
+ DyNTS_GlobalService_Settings
56
+ } from '../../_models/interfaces/global-service-settings.interface';
57
+ import {
58
+ DyNTS_StaticClient_Settings
59
+ } from '../../_models/interfaces/static-client-settings.interface';
60
+ import {
61
+ DyNTS_Cors_Settings
62
+ } from '../../_models/interfaces/cors-settings.interface';
63
+ import { DyNTS_DBService } from '../base/db.service';
64
+ import { DyNTS_SingletonService } from '../base/singleton.service';
65
+ import { DyNTS_GlobalService } from '../core/global.service';
66
+ import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
67
+ import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
68
+ import { DyNTS_EventLoopDiag } from '../core/event-loop-diag.service';
69
+ import { DyNTS_RoutingModule } from '../route/routing-module.service';
70
+ import { DyNTS_getStarRoute } from '../../_collections/star.controller';
71
+
72
+ /**
73
+ *
74
+ * function MyDecorator(config: any) {
75
+ return function (target: Function) {
76
+ // attach metadata or modify target
77
+ target.prototype.myMeta = config;
78
+ };
79
+ }
80
+
81
+ @MyDecorator({ role: 'admin' })
82
+ class User {
83
+ printRole() {
84
+ console.log((this as any).myMeta.role); // → "admin"
85
+ }
86
+ }
87
+
88
+ */
89
+
90
+ /**
91
+ * This will be the MAIN service of our server project,
92
+ * follow the types and type instructions while setting up your project
93
+ *
94
+ * In this service, there are abstract functions that you will need to implement,
95
+ * where you need to set up the main params for your application.
96
+ *
97
+ * (after the example, you can find the list of services you can/should setup)
98
+ *
99
+ * @example
100
+ * export class App extends DyNTS_AppExtended {
101
+ *
102
+ * ...
103
+ *
104
+ * // Setting up App params, and preparing project global settings
105
+ * setupAppParams(): void {
106
+ * this.params = new DyNTS_AppParams({
107
+ * name: 'Warbots Server',
108
+ * title: warbotsTitleLog,
109
+ * version: version,
110
+ * dbName: 'warbots',
111
+ * });
112
+ *
113
+ * // dynamoNTS_GlobalSettings.logRequestsContent = false;
114
+ * }
115
+ *
116
+ * ...
117
+ *
118
+ * // Setting up DBServices
119
+ * setGlobalServiceCollection(): void {
120
+ * DyNTS_GlobalService.setServices({
121
+ * authService: AuthService.getInstance(),
122
+ * emailServiceCollection: EmailServiceCollectionService.getInstance(),
123
+ * dbModels: [
124
+ * userModelParams,
125
+ * userDataModelParams,
126
+ * userOptionsModelParams,
127
+ * userStatisticsModelParams,
128
+ * userAchievementsModelParams,
129
+ * userNotificationsModelParams,
130
+ *
131
+ * matchStatisticsModelParams,
132
+ * matchDataModelParams,
133
+
134
+ * DyFM_usageSession_dataParams,
135
+ * DyFM_customData_dataParams,
136
+ * ]
137
+ * });
138
+ * }
139
+ *
140
+ * ...
141
+ *
142
+ * // Setting up Routes
143
+ * setupRoutingModules(): void {
144
+ * this.httpPort = env.port;
145
+
146
+ * this.routingModules = [
147
+ * new DyNTS_RoutingModule({
148
+ * route: '/user',
149
+ * controllers: [
150
+ * UserController.getInstance(),
151
+ * UserDataController.getInstance(),
152
+ * UserOptionsController.getInstance(),
153
+ * UserStatisticsController.getInstance(),
154
+ * UserAchievementsController.getInstance(),
155
+ * UserNotificationsController.getInstance()
156
+ * ]
157
+ * }),
158
+ * new DyNTS_RoutingModule({
159
+ * route: '/match',
160
+ * controllers: [
161
+ * MatchController.getInstance(),
162
+ * MatchDistributionController.getInstance(),
163
+ * MatchStatisticsController.getInstance(),
164
+ * ]
165
+ * }),
166
+ * new DyNTS_RoutingModule({
167
+ * route: '/server',
168
+ * controllers: [
169
+ * ServerController.getInstance(),
170
+ * ]
171
+ * }),
172
+
173
+ * getTestRoutingModule(),
174
+ * getUsageRoutingModule()
175
+ * ];
176
+ * }
177
+ * }
178
+ *
179
+ * //
180
+ * // The Services available
181
+ * //
182
+ * // Authentication Service
183
+ * // A commonly used basic service,
184
+ * // which is necessary fur certain functions (such as registering call issuers)
185
+ * //
186
+ * // This will handle Authentication Token checking/refreshing,
187
+ * // checking issuer's identifier and routeParams,
188
+ * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
189
+ * //
190
+ * // You can create one with this Dynamo Object:
191
+ * //
192
+ *
193
+ * @example
194
+ * // follow the instructions on the abstract class (DyNTS_AuthService)
195
+ * export class AuthService extends DyNTS_AuthService {}
196
+ *
197
+ *
198
+ *
199
+ * //
200
+ */
201
+
202
+ /**
203
+ * This will be the MAIN service of our server project,
204
+ * follow the types and type instructions while setting up your project
205
+ *
206
+ * In this service, there are abstract functions that you will need to implement,
207
+ * where you need to set up the main params for your application.
208
+ *
209
+ * (after the example, you can find the list of services you can/should setup)
210
+ *
211
+ * You need to setup the following functions:
212
+ * ```ts
213
+ * // this is where you set up the main params for your application
214
+ * getAppParams(): DyNTS_AppParams
215
+ *
216
+ * // this is where you connect your main services
217
+ * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
218
+ *
219
+ * // this is where you set up your ports
220
+ * getPorts(): DyNTS_PortSettings
221
+ *
222
+ * // this is where you set up your routes
223
+ * getRoutingModules(): DyNTS_RoutingModule[]
224
+ *
225
+ *
226
+ *
227
+ * ```
228
+ * optionally you can setup the following functions:
229
+ * ```ts
230
+ * // this is where you set up your certifications
231
+ * getCertificationSettings(): DyNTS_CertificationSettings
232
+ *
233
+ * // this is where you set up additional root services
234
+ * getRootServices(): DyNTS_SingletonService[]
235
+ *
236
+ * // this is where you set up your initial db entries
237
+ * createEntries(): void
238
+ *
239
+ * // this is where you can define post setup processes
240
+ * postProcess(): void
241
+ *
242
+ *
243
+ *
244
+ * ```
245
+ *
246
+ */
247
+
248
+ /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
249
+ export interface DyNTS_TtlIndexInfo {
250
+ name?: string;
251
+ key?: Record<string, number>;
252
+ expireAfterSeconds?: number;
253
+ }
254
+
255
+ /**
256
+ * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
257
+ * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
258
+ * in unit tests.
259
+ */
260
+ export interface DyNTS_TtlIndexCollection {
261
+ indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
262
+ createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
263
+ dropIndex?: (name: string) => Promise<unknown>;
264
+ }
265
+
266
+ /**
267
+ * FR-258 / SR-2 — outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
268
+ * - `created`: no `__created` TTL index existed → one was created.
269
+ * - `noop`: an index with the SAME TTL already existed → nothing done.
270
+ * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) → left UNTOUCHED,
271
+ * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
272
+ * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
273
+ * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
274
+ * maintenance, not silently at every startup.
275
+ */
276
+ export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
277
+
278
+ export abstract class DyNTS_App extends DyNTS_SingletonService {
279
+
280
+ protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
281
+ get started(): boolean {
282
+ return this.systemControls.app.started;
283
+ }
284
+ protected get superStarted(): boolean {
285
+ return this.systemControls.app.started;
286
+ }
287
+ protected constructErrors: (Error | DyFM_Error)[] = [];
288
+
289
+ /* removed since cant use version from package.json
290
+ private readonly _ntsVersion: string = 'v01.07.18';
291
+ protected get ntsVersion(): string {
292
+ return this._ntsVersion;
293
+ } */
294
+
295
+ get serverName(): string {
296
+ return this.params.name;
297
+ }
298
+
299
+ private _params: DyNTS_App_Params;
300
+ protected get params(): DyNTS_App_Params {
301
+ return this._params;
302
+ }
303
+
304
+ protected mongoose = Mongoose;
305
+
306
+ private _security: DyNTS_RouteSecurity;
307
+ protected get security(): DyNTS_RouteSecurity {
308
+ return this._security;
309
+ }
310
+
311
+ protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
312
+ protected get portSettings(): DyNTS_Http_Settings {
313
+ return this._portSettings;
314
+ }
315
+
316
+ private _cert?: DyNTS_Certification_Settings;
317
+ protected get cert(): DyNTS_Certification_Settings {
318
+ return this._cert;
319
+ }
320
+
321
+ protected openExpress: Express.Application;
322
+ protected secureExpress: Express.Application;
323
+ protected httpsServer: Https.Server;
324
+ protected httpServer: Http.Server;
325
+
326
+ private globalService: DyNTS_GlobalService;
327
+ private _rootServices: DyNTS_SingletonService[] = [];
328
+
329
+ private _routingModules: DyNTS_RoutingModule[] = [];
330
+
331
+ protected readonly defaultReadyTimeout: number = 30 * second;
332
+
333
+ override readonly defaultErrorUserMsg =
334
+ `We encountered an unhandled Server Error, ` +
335
+ `\nplease contact the responsible development team.` +
336
+ `\n(Internal Server error)`;
337
+
338
+ get logSetup(): boolean {
339
+ return DyNTS_global_settings.log_settings.setup;
340
+ }
341
+ get deepLog(): boolean {
342
+ return DyNTS_global_settings.log_settings.deep;
343
+ }
344
+ get fnLogs(): boolean {
345
+ return DyNTS_global_settings.log_settings.functions;
346
+ }
347
+ debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
348
+
349
+ constructor(/* extended?: boolean */){
350
+ super();
351
+
352
+ /* dotenv.config() */
353
+
354
+ process.on(
355
+ 'unhandledRejection',
356
+ (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
357
+ if (reason_theError instanceof DyFM_Error) {
358
+ reason_theError.logSimple('Unhandled Rejection');
359
+ } else {
360
+ DyFM_Log.H_error(
361
+ 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
362
+ '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
363
+ /* '\n ErrorCode:', (reason as any)?.code, */
364
+ '\n\n Stack:',
365
+ (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
366
+ );
367
+ }
368
+
369
+ try {
370
+ DyNTS_GlobalService.globalErrorHandler?.(
371
+ new DyFM_Error({
372
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
373
+ message:
374
+ `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
375
+ userMessage: this.defaultErrorUserMsg,
376
+ addECToUserMsg: true,
377
+ error: reason_theError as Error,
378
+ additionalContent: {
379
+ reason: reason_theError,
380
+ rejectedPromise: p_passWhatIsThis_maybeThePromise,
381
+ },
382
+ systemVersion: DyNTS_global_settings.systemVersion,
383
+ level: DyFM_ErrorLevel.critical,
384
+ })
385
+ );
386
+ } catch (error) {
387
+ DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
388
+ }
389
+ }
390
+ );
391
+
392
+ this.asyncConstruct(/* extended */).catch((error: any): void => {
393
+ if (error instanceof DyFM_Error) {
394
+ if (error.additionalContent?.constructErrors?.length) {
395
+ error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
396
+ DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
397
+ /* if (errorItem instanceof DyFM_Error) {
398
+ errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
399
+ } else {
400
+ DyFM_Log.H_warn(
401
+ '(constructor asyncConstruct.catch) additional error content:\n',
402
+ errorItem
403
+ );
404
+ } */
405
+ });
406
+ } else {
407
+ DyFM_Log.H_warn(
408
+ '(constructor asyncConstruct.catch) additional error content:\n',
409
+ error?.additionalContent
410
+ );
411
+ }
412
+ }
413
+
414
+ DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
415
+ /* if (
416
+ !DyNTS_global_settings.log_settings.highDetailedLogs &&
417
+ (error instanceof DyFM_Error)
418
+ ) {
419
+ error.logSimple(
420
+ `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
421
+ '\n all error messages (from this stack):\n\n"' +
422
+ error._messages.join('"\n\n"') + '"\n\n'
423
+ );
424
+ } else if (error instanceof DyFM_Error) {
425
+ DyFM_Log.H_error(
426
+ `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
427
+ `\n ERROR:`, error
428
+ );
429
+ } */
430
+
431
+ const message: string =
432
+ (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
433
+ (errorItem: DyFM_Error): string[] => {
434
+ return errorItem?._messages ?? [];
435
+ }
436
+ )?.join?.('\n') ??
437
+ (error as DyFM_Error)?.errors?.flatMap(
438
+ (errorItem: DyFM_AnyError): string[] =>
439
+ (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
440
+ )?.join?.('\n') ??
441
+ error?.message ??
442
+ 'UNKNOWN';
443
+
444
+ DyFM_Log.testError('Application start failed:\n', message);
445
+
446
+ process.exit(1);
447
+ });
448
+ }
449
+
450
+ protected async asyncConstruct(extended?: boolean): Promise<void> {
451
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
452
+
453
+ try {
454
+ this.systemControls.app.init = true;
455
+ this._params = this.getAppParams();
456
+ DyFM_Log.log(
457
+ `\n\n\n\n\n\n\n\n\n\n` +
458
+ `Starting ${this._params?.name}... ` +
459
+ /* `v${version}` + */
460
+ `\n\n\n\n\n\n\n\n\n\n`
461
+ );
462
+
463
+ if (!this._params) {
464
+ throw new Error('getAppParams() must return a DyNTS_AppParams object!');
465
+ }
466
+
467
+ if (this.params.systemShortCodeName) {
468
+ DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
469
+ }
470
+
471
+ if (this.params.systemName) {
472
+ DyNTS_global_settings.systemName = this.params.systemName;
473
+ DyFM_error_defaults.issuerSystem = this.params.systemName;
474
+ }
475
+
476
+ if (this.params.version) {
477
+ DyNTS_global_settings.systemVersion = this.params.version;
478
+ DyFM_error_defaults.systemVersion = this.params.version;
479
+ }
480
+
481
+ process.stdout.write(
482
+ String.fromCharCode(27) + ']0;' +
483
+ this._params?.name +
484
+ String.fromCharCode(7)
485
+ );
486
+
487
+ DyFM_error_defaults.issuerSystem = this._params.systemName;
488
+
489
+ this.overrideDynamoNTSGlobalSettings?.();
490
+
491
+ if (DyNTS_global_settings.log_settings.setup) {
492
+ DyFM_Log.S_info(`env settings;\n`, {
493
+ systemName: DyNTS_global_settings.systemName,
494
+ systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
495
+ systemVersion: DyNTS_global_settings.systemVersion,
496
+ environment: DyNTS_global_settings.env_settings.environment,
497
+ /* log_settings: DyNTS_global_settings.log_settings,
498
+ env_settings: DyNTS_global_settings.env_settings, */
499
+ });
500
+ }
501
+
502
+ this.globalService = DyNTS_GlobalService.getInstance();
503
+ await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
504
+ DyNTS_GlobalService.setParams(this.params);
505
+
506
+ if (this.getPortSettings) {
507
+ this._portSettings = this.getPortSettings();
508
+ }
509
+
510
+ if (this.getCertificationSettings) {
511
+ this._cert = this.getCertificationSettings();
512
+ }
513
+
514
+ if (this.getApiBasePath) {
515
+ DyNTS_global_settings.baseUrl = this.getApiBasePath();
516
+ }
517
+
518
+ if (this.getRoutingModules) {
519
+ this._routingModules = this.getRoutingModules();
520
+
521
+ // ezt egyelőre csak tesztelem, nem kerül be
522
+ /* if (
523
+ !DyNTS_global_settings.dontCreateDefaultRoute &&
524
+ !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
525
+ ) {
526
+ this._routingModules.push(
527
+ DyNTS_getStarRoute()
528
+ );
529
+ } */
530
+ }
531
+
532
+ if (this._params.dbUri) {
533
+ await this.startDB();
534
+
535
+ // createEntries csak akkor fut, ha a DB tényleg fel-jött.
536
+ // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
537
+ // és nem próbálunk meg írni egy nem létező kapcsolatra.
538
+ if (this.createEntries && this.systemControls.mongoose.started) {
539
+ await this.createEntries();
540
+ }
541
+ } else {
542
+ DyFM_Log.log(
543
+ `\nNo database connection created.`,
544
+ );
545
+ }
546
+
547
+ if (this._routingModules?.length) {
548
+ if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
549
+
550
+ this.setSecurity();
551
+
552
+ await this.initExpresses();
553
+ await this.startExpresses();
554
+
555
+ if (this._security !== DyNTS_RouteSecurity.secure) {
556
+ await this.mountOpenRoutes();
557
+ }
558
+
559
+ if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
560
+ await this.mountSecureRoutes();
561
+ }
562
+
563
+ // Generikus, auth-agnosztikus extension-point: custom middleware az API
564
+ // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
565
+ await this.mountCustomMiddleware();
566
+
567
+ await this.mountStaticClient();
568
+
569
+ if (this.logSetup) {
570
+ DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
571
+ }
572
+ } else {
573
+ DyFM_Log.warn(
574
+ `\nNo routes mounted!`,
575
+ );
576
+ }
577
+
578
+ if (this.getRootServices) {
579
+ this._rootServices = await this.getRootServices();
580
+ }
581
+
582
+ if (this.postProcess) {
583
+ await this.postProcess().catch((error: any): void => {
584
+ DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
585
+ DyNTS_GlobalService.globalErrorHandler?.(error);
586
+ });
587
+ }
588
+
589
+ // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
590
+ // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
591
+ // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
592
+ // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
593
+ try {
594
+ if (DyNTS_global_settings.memoryGuard?.enabled) {
595
+ DyNTS_MemoryGuard.getInstance().install();
596
+ }
597
+ } catch (memoryGuardError: unknown) {
598
+ DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
599
+ }
600
+
601
+ // BFR-OVERSEER-007 — event-loop-lag diag a MemoryGuard MELLÉ: a „process él, HTTP néma" wedge
602
+ // belső mérése (natív histogram, olcsó). Observation-only, sosem dob; a /server/diag olvas belőle.
603
+ try {
604
+ DyNTS_EventLoopDiag.getInstance().install();
605
+ } catch (eventLoopDiagError: unknown) {
606
+ DyFM_Log.warn('[DyNTS_EventLoopDiag] auto-install skipped (non-fatal):', eventLoopDiagError);
607
+ }
608
+
609
+ // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
610
+ // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
611
+ // OOM. Default-on, observation-only, never throws.
612
+ try {
613
+ if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
614
+ DyNTS_CollectionGrowthMonitor.getInstance().install();
615
+ }
616
+ } catch (cgmError: unknown) {
617
+ DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
618
+ }
619
+
620
+ if (!extended) {
621
+ await this.ready();
622
+
623
+ if (this.params.title) {
624
+ DyFM_Log.success(this.params.title);
625
+ }
626
+ DyFM_Log.info(`Version: ${this.params.version}`);
627
+ /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
628
+ DyFM_Log.H_success(`${this.params.name} started successfully.`);
629
+ }
630
+ } catch (error) {
631
+ this.constructErrors.push(error);
632
+
633
+ if (this.deepLog) {
634
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
635
+ DyFM_Log.H_error(
636
+ `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
637
+ `\n\n construct ERRORS:`, this.constructErrors,
638
+ '\n\nlast error:', error
639
+ );
640
+ } else {
641
+ DyFM_Log.H_error(
642
+ `"${this._params.name}" start failed (in asyncConstruct). `,
643
+ `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
644
+ '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
645
+ );
646
+ }
647
+ }
648
+
649
+ throw new DyFM_Error({
650
+ ...this._getDefaultErrorSettings('asyncConstruct', error),
651
+
652
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
653
+ additionalContent: {
654
+ constructErrors: this.constructErrors,
655
+ systemControls: this.systemControls,
656
+ systemReadies: {
657
+ app: this.systemControls.app.getIsReady(),
658
+ mongoose: this.systemControls.mongoose.getIsReady(),
659
+ httpServer: this.systemControls.httpServer.getIsReady(),
660
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
661
+ },
662
+ },
663
+ });
664
+ }
665
+ }
666
+
667
+ async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
668
+ try {
669
+ if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
670
+
671
+ await DyFM_Async.delay(100);
672
+
673
+ let ready: boolean = false;
674
+ const start: number = +new Date();
675
+
676
+ if (this.constructErrors.length) {
677
+ if (this.deepLog) {
678
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
679
+ DyFM_Log.H_error(
680
+ `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
681
+ `\n construct ERRORS:`, this.constructErrors
682
+ );
683
+ } else {
684
+ DyFM_Log.H_error(
685
+ `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
686
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
687
+ );
688
+ }
689
+ }
690
+
691
+ throw new DyFM_Error({
692
+ ...this._getDefaultErrorSettings(
693
+ 'ready',
694
+ new Error(`"${this._params.name}" start failed.`)
695
+ ),
696
+
697
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
698
+ additionalContent:
699
+ this.constructErrors.length === 1 ?
700
+ { error: this.constructErrors[0] } :
701
+ { errors: this.constructErrors },
702
+ });
703
+ }
704
+
705
+ while (!ready && +new Date() - start < timeout) {
706
+ if (this.systemControls.app.init) {
707
+ ready = (
708
+ this.systemControls.mongoose.getIsReady() &&
709
+ this.systemControls.httpServer.getIsReady() &&
710
+ this.systemControls.httpsServer.getIsReady()
711
+ );
712
+ } else {
713
+ DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
714
+ }
715
+
716
+ if (!ready) {
717
+ await DyFM_Async.wait(100);
718
+ }
719
+ }
720
+
721
+ if (timeout < +new Date() - start) {
722
+ if (this.deepLog) {
723
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
724
+ DyFM_Log.H_error(
725
+ `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
726
+ `\n construct ERRORS:`, this.constructErrors
727
+ );
728
+ } else {
729
+ DyFM_Log.H_error(
730
+ `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
731
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
732
+ );
733
+ }
734
+ }
735
+
736
+ throw new DyFM_Error({
737
+ ...this._getDefaultErrorSettings(
738
+ 'ready',
739
+ new Error(`"${this._params.name}" start failed. TIMEOUT`)
740
+ ),
741
+
742
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
743
+ additionalContent: {
744
+ constructErrors: this.constructErrors,
745
+ systemControls: this.systemControls,
746
+ systemReadies: {
747
+ mongoose: this.systemControls.mongoose.getIsReady(),
748
+ httpServer: this.systemControls.httpServer.getIsReady(),
749
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
750
+ },
751
+ },
752
+ });
753
+ }
754
+
755
+ if (this.constructErrors.length) {
756
+ if (this.deepLog) {
757
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
758
+ DyFM_Log.H_error(
759
+ `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
760
+ `\n construct ERRORS:`, this.constructErrors
761
+ );
762
+ } else {
763
+ DyFM_Log.H_error(
764
+ `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
765
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
766
+ );
767
+ }
768
+ }
769
+
770
+ throw new DyFM_Error({
771
+ ...this._getDefaultErrorSettings(
772
+ 'ready',
773
+ new Error(`"${this._params.name}" start failed.`)
774
+ ),
775
+
776
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
777
+ additionalContent: this.constructErrors,
778
+ });
779
+ }
780
+
781
+ if (ready) {
782
+ this.systemControls.app.started = true;
783
+
784
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
785
+
786
+ return;
787
+ }
788
+
789
+ this.systemControls.app.started = false;
790
+
791
+ let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
792
+
793
+ if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
794
+ msg += `\nMongoose start failed.`;
795
+ }
796
+
797
+ if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
798
+ msg += `\nHTTP Server start failed.`;
799
+ }
800
+
801
+ if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
802
+ msg += `\nHTTPS Server start failed.`;
803
+ }
804
+
805
+ DyFM_Log.error(msg, this.constructErrors);
806
+
807
+ throw new DyFM_Error({
808
+ ...this._getDefaultErrorSettings('ready', new Error(msg)),
809
+
810
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
811
+ additionalContent: {
812
+ constructErrors: this.constructErrors,
813
+ systemControls: this.systemControls,
814
+ systemReadies: {
815
+ app: this.systemControls.app.getIsReady(),
816
+ mongoose: this.systemControls.mongoose.getIsReady(),
817
+ httpServer: this.systemControls.httpServer.getIsReady(),
818
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
819
+ },
820
+ },
821
+ error: this.constructErrors?.[0] ?? new Error(),
822
+ });
823
+ } catch (error) {
824
+ throw new DyFM_Error({
825
+ ...this._getDefaultErrorSettings('ready', error),
826
+
827
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
828
+ });
829
+ }
830
+ }
831
+
832
+ protected getSimplifiedConstructErrors(): string[] {
833
+ return this.constructErrors.map((error: any): any => {
834
+ if (error instanceof DyFM_Error) {
835
+ return error.getErrorSimplified();
836
+ } else {
837
+ return error;
838
+ }
839
+ });
840
+ }
841
+
842
+ async stop(dontLog?: boolean): Promise<void> {
843
+ try {
844
+ DyFM_Log.info('\nstopping server...\n');
845
+
846
+ await this.ready();
847
+
848
+ if (this.started) {
849
+
850
+ if (this.systemControls.mongoose.init) {
851
+ DyFM_Log.info(`\nstopping Mongoose....`);
852
+
853
+ let tryCount: number = 0;
854
+
855
+ while (
856
+ !this.systemControls.mongoose.started &&
857
+ !this.constructErrors.length &&
858
+ tryCount++ < 10
859
+ ) {
860
+ DyFM_Log.warn(`Mongoose not even started yet....`);
861
+ await DyFM_Async.wait(second);
862
+ }
863
+ this.systemControls.mongoose.started = false;
864
+
865
+ if (this.mongoose) {
866
+ await DyFM_Array.asyncForEach(
867
+ Object.keys(this.mongoose.models),
868
+ async (modelName): Promise<void> => {
869
+ this.mongoose.deleteModel(modelName);
870
+ }
871
+ );
872
+
873
+ const disconnect: Promise<void> = new Promise((resolve): void => {
874
+ this.mongoose.connection.on('disconnecting', (): void => {
875
+ resolve();
876
+ });
877
+ });
878
+
879
+ await this.mongoose.disconnect();
880
+ await this.mongoose.connection.close();
881
+ await disconnect;
882
+
883
+ this.mongoose.connection.removeAllListeners();
884
+
885
+ while (
886
+ this.mongoose.connection.readyState !== 0 &&
887
+ !this.constructErrors.length
888
+ ) {
889
+ DyFM_Log.warn(`\nMongoose still not disconnected....`);
890
+ await DyFM_Async.wait(second);
891
+ }
892
+ } else {
893
+ DyFM_Log.error(`\nMongoose not found.`);
894
+ }
895
+ this.systemControls.mongoose.init = false;
896
+ }
897
+
898
+ if (this.systemControls.httpServer.init) {
899
+ this.systemControls.httpServer.started = false;
900
+
901
+ if (this.httpServer) {
902
+ await new Promise((resolve): void => {
903
+ this.httpServer.close(resolve);
904
+ });
905
+ } else {
906
+ DyFM_Log.error(`\nHTTP Server not found.`);
907
+ }
908
+ this.systemControls.httpServer.init = false;
909
+ }
910
+
911
+ if (this.systemControls.httpsServer.init) {
912
+ this.systemControls.httpsServer.started = false;
913
+
914
+ if (this.httpsServer) {
915
+ await new Promise((resolve): void => {
916
+ this.httpsServer.close(resolve);
917
+ });
918
+ } else {
919
+ DyFM_Log.error(`\nHTTPS Server not found.`);
920
+ }
921
+ this.systemControls.httpsServer.init = false;
922
+ }
923
+
924
+ await DyFM_Async.wait(second);
925
+
926
+ if (!dontLog) {
927
+ DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
928
+ }
929
+ }
930
+ } catch (error) {
931
+ throw new DyFM_Error({
932
+ ...this._getDefaultErrorSettings('stop', error),
933
+
934
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
935
+ });
936
+ }
937
+ }
938
+
939
+ /**
940
+ *
941
+ */
942
+ private async startDB(): Promise<void> {
943
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
944
+ else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
945
+
946
+ if (!this._params.dbUri) {
947
+ throw new DyFM_Error({
948
+ ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
949
+
950
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
951
+ });
952
+ }
953
+
954
+ if (!this._params.dbOptions) {
955
+ throw new DyFM_Error({
956
+ ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
957
+
958
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
959
+ });
960
+ }
961
+
962
+ if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
963
+ throw new DyFM_Error({
964
+ ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
965
+
966
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
967
+ });
968
+ }
969
+
970
+ try {
971
+ await new Promise<void>(
972
+ (resolve, reject): void => {
973
+ this.systemControls.mongoose.init = true;
974
+
975
+ this.mongoose.connection
976
+ .once('open', (): void => {
977
+ this.systemControls.mongoose.started = true;
978
+ DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
979
+
980
+ resolve();
981
+
982
+ // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
983
+ // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
984
+ // compete with boot-readiness. We delay it well past the deploy health-probe window so a
985
+ // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
986
+ // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
987
+ // rebuilds a live index — see ensureRetentionTtlIndex.)
988
+ const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
989
+ void this.installRetentionTtlIndexes();
990
+ }, 30000);
991
+ if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
992
+ })
993
+ .on('error', (error): void => {
994
+ if (!this.systemControls.mongoose.started) {
995
+ // Initial DB-csatlakozás sikertelen:
996
+ // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
997
+ // App startup-ot (nincs constructErrors push, nincs reject).
998
+ // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
999
+ // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
1000
+ // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
1001
+ this.systemControls.mongoose.init = false;
1002
+
1003
+ const d_error: DyFM_Error = new DyFM_Error({
1004
+ ...this._getDefaultErrorSettings('startDB', error),
1005
+
1006
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
1007
+ message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
1008
+ `ERROR: ${error}`,
1009
+ level: DyFM_ErrorLevel.serious,
1010
+ });
1011
+
1012
+ DyFM_Log.H_error(
1013
+ `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
1014
+ `\nServer will continue WITHOUT DB connection.` +
1015
+ `\nDB-using endpoints will fail at runtime until connection recovers.`
1016
+ );
1017
+
1018
+ if (this.debugLog) DyFM_Log.S_error(
1019
+ `\nMongoDB connect ERROR: `,
1020
+ error
1021
+ );
1022
+
1023
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1024
+
1025
+ resolve();
1026
+
1027
+ } else {
1028
+ if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1029
+
1030
+ const d_error: DyFM_Error = new DyFM_Error({
1031
+ ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1032
+
1033
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1034
+ message: `MongoDB ERROR: ${error}`,
1035
+ level: DyFM_ErrorLevel.critical,
1036
+ });
1037
+
1038
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1039
+ }
1040
+ });
1041
+
1042
+ try {
1043
+ this.mongoose.connect(
1044
+ this._params.dbUri,
1045
+ this._params.dbOptions
1046
+ /* {
1047
+ directConnection: true,
1048
+ } */
1049
+ );
1050
+ } catch (error) {
1051
+ throw new DyFM_Error({
1052
+ ...this._getDefaultErrorSettings('startDB', error),
1053
+
1054
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1055
+ });
1056
+ }
1057
+ }
1058
+ );
1059
+ } catch (error) {
1060
+ throw new DyFM_Error({
1061
+ ...this._getDefaultErrorSettings('startDB', error),
1062
+
1063
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1064
+ });
1065
+ }
1066
+
1067
+ // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1068
+ // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1069
+ // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1070
+ // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1071
+ // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1072
+ // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1073
+ // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1074
+ try {
1075
+ startMongoReconnectGuard({
1076
+ getReadyState: (): number => this.mongoose.connection.readyState,
1077
+ reconnect: async (): Promise<void> => {
1078
+ await this.mongoose.disconnect().catch((): void => undefined);
1079
+ await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1080
+ },
1081
+ log: (msg: string): void => DyFM_Log.warn(msg),
1082
+ });
1083
+ } catch (guardErr) {
1084
+ DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1085
+ }
1086
+ }
1087
+
1088
+ /**
1089
+ * FR-258 / SR-2 — install MongoDB TTL indexes for every data-model that declared `retention`.
1090
+ *
1091
+ * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1092
+ * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1093
+ * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1094
+ * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1095
+ * against the unbounded-collection-growth → in-memory-load → GC-thrash/OOM class.
1096
+ *
1097
+ * Guarantees:
1098
+ * - **Non-fatal** — any error is logged but NEVER blocks startup (called fire-and-forget).
1099
+ * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1100
+ * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1101
+ * (the field index is restored immediately, so query coverage is preserved).
1102
+ */
1103
+ private async installRetentionTtlIndexes(): Promise<void> {
1104
+ try {
1105
+ const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1106
+ let ensured: number = 0;
1107
+
1108
+ for (const service of services) {
1109
+ const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1110
+ if (!ttlSeconds) { continue; }
1111
+
1112
+ const dataName: string = service.dataParams.dataName;
1113
+ // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1114
+ const collection: DyNTS_TtlIndexCollection | undefined =
1115
+ (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1116
+ if (!collection || typeof collection.createIndex !== 'function') { continue; }
1117
+
1118
+ try {
1119
+ const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1120
+ if (action === 'created') {
1121
+ ensured++;
1122
+ if (this.logSetup) {
1123
+ DyFM_Log.success(
1124
+ `[FR-258 retention] TTL index created on "${dataName}" — ` +
1125
+ `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1126
+ );
1127
+ }
1128
+ } else if (action === 'differs') {
1129
+ // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1130
+ DyFM_Log.warn(
1131
+ `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1132
+ `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1133
+ `Apply the change via maintenance if intended.`,
1134
+ );
1135
+ }
1136
+ } catch (idxErr: unknown) {
1137
+ DyFM_Log.warn(
1138
+ `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1139
+ `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1140
+ );
1141
+ }
1142
+ }
1143
+
1144
+ if (ensured > 0) {
1145
+ DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1146
+ }
1147
+ } catch (err: unknown) {
1148
+ DyFM_Log.warn(
1149
+ `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1150
+ `${err instanceof Error ? err.message : String(err)}`,
1151
+ );
1152
+ }
1153
+ }
1154
+
1155
+ /**
1156
+ * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1157
+ * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1158
+ * - no existing `__created` index → create it → `'created'`
1159
+ * - existing with the SAME TTL → no-op → `'noop'`
1160
+ * - existing with a DIFFERENT TTL / non-TTL → leave it as-is → `'differs'` (warn only — NO drop+recreate)
1161
+ *
1162
+ * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1163
+ * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1164
+ * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1165
+ * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1166
+ * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1167
+ */
1168
+ static async ensureRetentionTtlIndex(
1169
+ collection: DyNTS_TtlIndexCollection,
1170
+ ttlSeconds: number,
1171
+ ): Promise<DyNTS_TtlIndexAction> {
1172
+ const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1173
+ ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1174
+ : [];
1175
+ const existing: DyNTS_TtlIndexInfo | undefined =
1176
+ existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1177
+
1178
+ if (!existing) {
1179
+ await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1180
+ return 'created';
1181
+ }
1182
+ if (existing.expireAfterSeconds === ttlSeconds) {
1183
+ return 'noop';
1184
+ }
1185
+ // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1186
+ // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1187
+ return 'differs';
1188
+ }
1189
+
1190
+ /**
1191
+ *
1192
+ */
1193
+ private async initExpresses(): Promise<void> {
1194
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1195
+
1196
+ try {
1197
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1198
+ if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1199
+ let errorMsg: string =
1200
+ `\nYou have open routes, but httpPort is not set!` +
1201
+ `\nThere are ${this._routingModules.filter(
1202
+ m => m.security != DyNTS_RouteSecurity.secure
1203
+ ).length} open/both routes` +
1204
+ `\nroot security: ${this._security}` +
1205
+ `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1206
+
1207
+ errorMsg += '\n\nThe routes setted to use open server:';
1208
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1209
+ if (module.security != DyNTS_RouteSecurity.secure) {
1210
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1211
+ errorMsg += `\n subroutes using open sever:`;
1212
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1213
+ if (endpoint.security != DyNTS_RouteSecurity.secure) {
1214
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1215
+ }
1216
+ });
1217
+ }
1218
+ });
1219
+
1220
+ const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1221
+ const errorStack: string[] = error.stack.split('\n');
1222
+
1223
+ errorStack.splice(1, 2);
1224
+ error.stack = errorStack.join('\n');
1225
+
1226
+ DyFM_Log.error(errorMsg);
1227
+
1228
+ throw error;
1229
+ }
1230
+
1231
+ await this.initOpenExpress();
1232
+ }
1233
+
1234
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1235
+ if (!this._cert || !this._portSettings.httpsPort) {
1236
+ let errorMsg: string =
1237
+ `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1238
+ `\nThere are ${this._routingModules.filter(
1239
+ m => m.security && m.security !== DyNTS_RouteSecurity.open
1240
+ ).length} secure routes` +
1241
+ `\nroot security: ${this._security}` +
1242
+ `\nset...` +
1243
+ `\n(missing exact howto...)` +
1244
+ /* `\n httpsPort and` +
1245
+ `\n cert: {` +
1246
+ `\n keyPath: FileSystem.PathLike,` +
1247
+ `\n certPath: FileSystem.PathLike,` +
1248
+ `\n }` + */
1249
+ `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1250
+
1251
+ errorMsg += '\n\nThe routes setted to use secure server:';
1252
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1253
+ if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1254
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1255
+ errorMsg += `\n location: ${module.stackLocation}`;
1256
+ errorMsg += `\n subroutes using secure sever:`;
1257
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1258
+ if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1259
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1260
+ errorMsg += `\n location: ${endpoint.stackLocation}`;
1261
+ }
1262
+ });
1263
+ }
1264
+ });
1265
+
1266
+ const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1267
+ const errorStack: string[] = error.stack.split('\n');
1268
+
1269
+ errorStack.splice(1, 2);
1270
+ error.stack = errorStack.join('\n');
1271
+
1272
+ DyFM_Log.error(errorMsg);
1273
+
1274
+ throw error;
1275
+ }
1276
+
1277
+ await this.initSecureExpress();
1278
+ }
1279
+ } catch (error) {
1280
+ throw new DyFM_Error({
1281
+ ...this._getDefaultErrorSettings('initExpresses', error),
1282
+
1283
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1284
+ });
1285
+ }
1286
+ }
1287
+
1288
+ /**
1289
+ *
1290
+ */
1291
+ protected async initOpenExpress(): Promise<void> {
1292
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1293
+ this.openExpress = Express();
1294
+ this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1295
+ this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1296
+ this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1297
+ // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (az OPTIONS preflight-válaszok is kapják).
1298
+ this.mountSecurityHeaders(this.openExpress);
1299
+ // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1300
+ this.mountCors(this.openExpress);
1301
+ // FR-292 — a deployolt app-verzio minden valaszon. A CORS UTAN kell, mert az
1302
+ // `Access-Control-Expose-Headers`-hoz HOZZAFUZ (kulonben a CORS felulirna).
1303
+ this.mountAppVersionHeader(this.openExpress);
1304
+ // BFR-OVERSEER-009 — opt-in auto-load-shed 503 CRITICAL memória-nyomásnál (esszenciális utak kivételével).
1305
+ if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1306
+ this.openExpress.use(DyNTS_createLoadShedMiddleware());
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ *
1312
+ */
1313
+ protected async initSecureExpress(): Promise<void> {
1314
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1315
+ this.secureExpress = Express();
1316
+ this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1317
+ this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1318
+ // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (mint az open expressen).
1319
+ this.mountSecurityHeaders(this.secureExpress);
1320
+ // FR-041 — CORS allowlist enforcement (same as open express).
1321
+ this.mountCors(this.secureExpress);
1322
+ // FR-292 — a deployolt app-verzio minden valaszon (mint az open expressen).
1323
+ this.mountAppVersionHeader(this.secureExpress);
1324
+ // BFR-OVERSEER-009 — opt-in auto-load-shed 503 (mint az open expressen).
1325
+ if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1326
+ this.secureExpress.use(DyNTS_createLoadShedMiddleware());
1327
+ }
1328
+
1329
+ const options = {
1330
+ key: FileSystem.readFileSync(this._cert.keyPath),
1331
+ cert: FileSystem.readFileSync(this._cert.certPath),
1332
+ maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1333
+ };
1334
+
1335
+ this.httpsServer = Https.createServer(options, this.secureExpress);
1336
+ }
1337
+
1338
+ /**
1339
+ *
1340
+ */
1341
+ private async startExpresses(): Promise<void> {
1342
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1343
+
1344
+ try {
1345
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1346
+ await new Promise<void>((resolve, reject): void => {
1347
+ this.systemControls.httpsServer.init = true;
1348
+ this.httpsServer
1349
+ .listen(
1350
+ this._portSettings.httpsPort,
1351
+ this.params.secureHost,
1352
+ this.params.expressBacklog,
1353
+ (): void => {
1354
+ this.systemControls.httpsServer.started = true;
1355
+ DyFM_Log.success(
1356
+ `\nHTTPS (secure) server is listening on port: ` +
1357
+ `${this.params.secureHost}:${this._portSettings.httpsPort}`
1358
+ );
1359
+
1360
+ resolve();
1361
+ })
1362
+ .on('error', (error): void => {
1363
+ if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1364
+
1365
+ if (!this.systemControls.httpsServer.started) {
1366
+ const d_error: DyFM_Error = new DyFM_Error({
1367
+ ...this._getDefaultErrorSettings('startExpresses', error),
1368
+
1369
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1370
+ message: `HTTPS (secure) start server ERROR`,
1371
+ });
1372
+
1373
+ this.constructErrors.push(d_error);
1374
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1375
+
1376
+ reject(d_error);
1377
+
1378
+ } else {
1379
+ const d_error: DyFM_Error = new DyFM_Error({
1380
+ ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1381
+
1382
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1383
+ message: `HTTPS (secure) server ERROR`,
1384
+ level: DyFM_ErrorLevel.serious,
1385
+ });
1386
+
1387
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1388
+ }
1389
+ })
1390
+ .on('uncaughtException', (exception): void => {
1391
+ const d_error: DyFM_Error = new DyFM_Error({
1392
+ ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1393
+
1394
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1395
+ message: `HTTPS (secure) server uncaughtException`,
1396
+ level: DyFM_ErrorLevel.critical,
1397
+ });
1398
+
1399
+ if (this.debugLog) DyFM_Log.warn(
1400
+ `\nHTTPS (secure) server uncaughtException`,
1401
+ d_error
1402
+ );
1403
+
1404
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1405
+ });
1406
+ });
1407
+ }
1408
+
1409
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1410
+ this.systemControls.httpServer.init = true;
1411
+ await new Promise<void>((resolve, reject): void => {
1412
+ this.httpServer = this.openExpress
1413
+ .listen(
1414
+ this._portSettings.httpPort,
1415
+ this.params.openHost,
1416
+ this.params.expressBacklog,
1417
+ (): void => {
1418
+ this.systemControls.httpServer.started = true;
1419
+
1420
+ const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1421
+
1422
+ if (this._portSettings.httpPort === 0) {
1423
+ DyFM_Log.H_warn(
1424
+ `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1425
+ `\n (httpPort was set to 0 — this is intended for testing only)`
1426
+ );
1427
+ }
1428
+
1429
+ DyFM_Log.success(
1430
+ `\nHTTP (open) server is listening on port: ` +
1431
+ `${this.params.openHost}:${resolvedPort}`
1432
+ );
1433
+
1434
+ resolve();
1435
+ }
1436
+ )
1437
+ .on('error', (error): void => {
1438
+ if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1439
+
1440
+ if (!this.systemControls.httpServer.started) {
1441
+ const d_error: DyFM_Error = new DyFM_Error({
1442
+ ...this._getDefaultErrorSettings('startExpresses', error),
1443
+
1444
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1445
+ message: `HTTP (open) start server ERROR`,
1446
+ });
1447
+
1448
+ this.constructErrors.push(d_error);
1449
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1450
+
1451
+ reject(d_error);
1452
+
1453
+ } else {
1454
+ const d_error: DyFM_Error = new DyFM_Error({
1455
+ ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1456
+
1457
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1458
+ message: `HTTP (open) server ERROR`,
1459
+ level: DyFM_ErrorLevel.serious,
1460
+ });
1461
+
1462
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1463
+ }
1464
+ })
1465
+ .on('uncaughtException', (exception): void => {
1466
+ const d_error: DyFM_Error = new DyFM_Error({
1467
+ ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1468
+
1469
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1470
+ message: `HTTP (open) server uncaughtException`,
1471
+ level: DyFM_ErrorLevel.critical,
1472
+ });
1473
+
1474
+ if (this.debugLog) {
1475
+ DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1476
+ }
1477
+
1478
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1479
+ });
1480
+ });
1481
+ }
1482
+ } catch (error) {
1483
+ throw new DyFM_Error({
1484
+ ...this._getDefaultErrorSettings('startExpresses', error),
1485
+
1486
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1487
+ });
1488
+ }
1489
+ }
1490
+
1491
+ /**
1492
+ *
1493
+ */
1494
+ private async expressErrorHandling(error, req, res, next): Promise<void> {
1495
+ try {
1496
+ if (error) {
1497
+ const d_error: DyFM_Error = new DyFM_Error({
1498
+ ...this._getDefaultErrorSettings('expressErrorHandling', error),
1499
+
1500
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1501
+ message: `Express ERROR`,
1502
+ additionalContent: {
1503
+ req,
1504
+ res,
1505
+ },
1506
+ level: DyFM_ErrorLevel.error,
1507
+ });
1508
+
1509
+ await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1510
+
1511
+ // Kliens-safe strip (BFR-FDPAUTHSERVICE-002): az express-error út eddig NYERS error-t küldött
1512
+ // (0 strip) — DyFM-nél belső stack/verzió/issuer, axios-jellegű error-nál akár auth-header is
1513
+ // kimehetett. A strip-szabályok SSOT-ja a DyNTS_ClientSafeError_Util.
1514
+ res.send(DyNTS_ClientSafeError_Util.toClientSafe(error))
1515
+ } else {
1516
+ DyFM_Log.H_error(
1517
+ 'WTF??? express error; without error?...' +
1518
+ '\nerr:', error,
1519
+ '\nreq:', req,
1520
+ '\nres:', res
1521
+ );
1522
+ }
1523
+ } catch (error) {
1524
+ DyFM_Log.H_error(
1525
+ 'MULTILEVEL ERROR (expressErrorHandling)....' +
1526
+ '\n', error
1527
+ );
1528
+ }
1529
+ }
1530
+
1531
+ /**
1532
+ *
1533
+ */
1534
+ private async mountSecureRoutes (): Promise<void> {
1535
+ try {
1536
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1537
+
1538
+ if (!this.secureExpress) {
1539
+ throw new Error(
1540
+ 'secureExpress was not initialized. ' +
1541
+ 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1542
+ '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1543
+ '\n\nYou need to set cert files in getCertificationSettings.'
1544
+ );
1545
+ }
1546
+
1547
+ this.secureExpress.use(
1548
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1549
+ );
1550
+
1551
+ await DyFM_Array.asyncForEach(
1552
+ this._routingModules,
1553
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1554
+ if (module.security !== DyNTS_RouteSecurity.open) {
1555
+ if (this.logSetup) {
1556
+ DyFM_Log.log(`route mount (secure): ${module.route}`);
1557
+ }
1558
+
1559
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1560
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1561
+ );
1562
+
1563
+ if (1 < existingRoutes.length) {
1564
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1565
+ /* const errorStack: string[] = error.stack.split('\n');
1566
+
1567
+ errorStack.splice(1, 4);
1568
+ error.stack = errorStack.join('\n'); */
1569
+ error.stack = module.stackLocation;
1570
+
1571
+ DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1572
+
1573
+ throw new DyFM_Error({
1574
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1575
+
1576
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1577
+ message: `ROUTE DUPLICATION: ${module.route}`,
1578
+ });
1579
+ }
1580
+
1581
+ this.secureExpress.use(module.route, module.secureRouter);
1582
+ }
1583
+ }
1584
+ );
1585
+ } catch (error) {
1586
+ throw new DyFM_Error({
1587
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1588
+
1589
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1590
+ });
1591
+ }
1592
+ }
1593
+
1594
+ /**
1595
+ *
1596
+ */
1597
+ private async mountOpenRoutes(): Promise<void> {
1598
+ try {
1599
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1600
+
1601
+ if (!this.openExpress) {
1602
+ throw new Error(
1603
+ 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1604
+ '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1605
+ );
1606
+ }
1607
+
1608
+ this.openExpress.use(
1609
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1610
+ );
1611
+
1612
+ await DyFM_Array.asyncForEach(
1613
+ this._routingModules,
1614
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1615
+ if (module.security !== DyNTS_RouteSecurity.secure) {
1616
+ if (this.logSetup) {
1617
+ DyFM_Log.log(`route mount (open): ${module.route}`);
1618
+ }
1619
+
1620
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1621
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1622
+ );
1623
+
1624
+ if (1 < existingRoutes.length) {
1625
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1626
+ /* const errorStack: string[] = error.stack.split('\n');
1627
+
1628
+ errorStack.splice(1, 4);
1629
+ error.stack = errorStack.join('\n'); */
1630
+ error.stack = module.stackLocation;
1631
+
1632
+ DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1633
+
1634
+ throw new DyFM_Error({
1635
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1636
+
1637
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1638
+ message: `ROUTE DUPLICATION: ${module.route}`,
1639
+ });
1640
+ }
1641
+
1642
+ this.openExpress.use(module.route, module.openRouter);
1643
+ }
1644
+ }
1645
+ );
1646
+ } catch (error) {
1647
+ throw new DyFM_Error({
1648
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1649
+
1650
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1651
+ });
1652
+ }
1653
+ }
1654
+
1655
+ /**
1656
+ * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1657
+ * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1658
+ * adds the canonical `Access-Control-*` companion headers, and short-circuits
1659
+ * the OPTIONS preflight with a 204.
1660
+ *
1661
+ * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1662
+ * back-compat for apps that have always been same-origin and never needed
1663
+ * CORS (the typical pre-FR-041 case).
1664
+ *
1665
+ * Why hand-rolled instead of the `cors` npm package:
1666
+ * - ~30 lines, zero new dependency.
1667
+ * - Full control over Vary/credentials/preflight semantics.
1668
+ * - Aligns with FDP "no unnecessary deps" philosophy.
1669
+ */
1670
+ /**
1671
+ * BFR-011 / SEC-R2-8 — security response-headerek mountolása (a `mountCors` tükörképe).
1672
+ * A `DyNTS_global_settings.securityHeaders` alapján (default-ON) minden válaszra ráteszi a
1673
+ * biztonsági headereket + eltávolítja az `x-powered-by`-t. A CORS-mount ELŐTT hívandó, hogy az
1674
+ * OPTIONS preflight-válaszok (amiket a mountCors 204-gyel rövidre zár) is megkapják.
1675
+ */
1676
+ protected mountSecurityHeaders(express: Express.Application): void {
1677
+ const settings: DyNTS_SecurityHeaders_Settings | undefined = DyNTS_global_settings.securityHeaders;
1678
+ if (!settings || !settings.enabled) {
1679
+ return;
1680
+ }
1681
+
1682
+ if (settings.removePoweredBy !== false) {
1683
+ express.disable('x-powered-by');
1684
+ }
1685
+
1686
+ express.use(DyNTS_createSecurityHeadersMiddleware(
1687
+ settings,
1688
+ DyNTS_getEnvironment_settings().environment,
1689
+ ));
1690
+ }
1691
+
1692
+ /**
1693
+ * FR-292 — a deployolt app-verziot minden valaszra rateszi (`X-App-Version`), hogy a
1694
+ * bongeszoben NYITVA HAGYOTT SPA eszrevegye, ha kozben ujabb kliens-build ment ki.
1695
+ *
1696
+ * Nem polling: a jelzes a MAR MENO API-hivasokon utazik. Az `enabled` default TRUE — egy
1697
+ * informativ response-header, ami se PII-t, se belso reszletet nem szivarogtat, viszont
1698
+ * enelkul minden app kulon-kulon epitene ugyanezt.
1699
+ */
1700
+ protected mountAppVersionHeader(express: Express.Application): void {
1701
+ const settings: DyNTS_AppVersionHeader_Settings | undefined = DyNTS_global_settings.appVersionHeader;
1702
+ if (settings?.enabled === false) {
1703
+ return;
1704
+ }
1705
+ express.use(DyNTS_createAppVersionHeaderMiddleware(
1706
+ (): string => DyNTS_global_settings.systemVersion,
1707
+ settings?.headerName,
1708
+ ));
1709
+ }
1710
+
1711
+ protected mountCors(express: Express.Application): void {
1712
+ const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1713
+ if (!settings) {
1714
+ return;
1715
+ }
1716
+
1717
+ const allowCreds: boolean = settings.allowCredentials !== false;
1718
+ const methods: string[] = settings.allowedMethods ?? [
1719
+ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1720
+ ];
1721
+ const headers: string[] = settings.allowedHeaders ?? [
1722
+ 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1723
+ ];
1724
+ const exposed: string[] = settings.exposedHeaders ?? [
1725
+ 'Content-Length', 'Content-Type',
1726
+ ];
1727
+ const maxAge: number = settings.maxAgeSeconds ?? 86400;
1728
+
1729
+ const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1730
+ if (settings.allowedOrigins === '*') return true;
1731
+ if (typeof settings.allowedOrigins === 'function') {
1732
+ return settings.allowedOrigins(origin);
1733
+ }
1734
+ return settings.allowedOrigins.includes(origin);
1735
+ };
1736
+
1737
+ express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1738
+ const origin: string | undefined = req.headers.origin;
1739
+ if (origin && isAllowed(origin)) {
1740
+ // Echo the matching origin (NOT wildcard) because credentials require it.
1741
+ res.setHeader('Access-Control-Allow-Origin', origin);
1742
+ if (allowCreds) {
1743
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
1744
+ }
1745
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1746
+ res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1747
+ res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1748
+ res.setHeader('Access-Control-Max-Age', String(maxAge));
1749
+ res.setHeader('Vary', 'Origin');
1750
+ }
1751
+ if (req.method === 'OPTIONS') {
1752
+ res.status(204).end();
1753
+ return;
1754
+ }
1755
+ next();
1756
+ });
1757
+ }
1758
+
1759
+ /**
1760
+ * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1761
+ * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1762
+ * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1763
+ * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1764
+ * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1765
+ */
1766
+ private async mountCustomMiddleware(): Promise<void> {
1767
+ if (!this.registerCustomMiddleware) {
1768
+ return;
1769
+ }
1770
+
1771
+ if (this.openExpress) {
1772
+ await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1773
+ }
1774
+
1775
+ if (this.secureExpress) {
1776
+ await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1777
+ }
1778
+
1779
+ if (this.logSetup) {
1780
+ DyFM_Log.log('\nCustom middleware registered (pre-static).');
1781
+ }
1782
+ }
1783
+
1784
+ /**
1785
+ * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1786
+ * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1787
+ * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1788
+ * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1789
+ */
1790
+ private async mountStaticClient(): Promise<void> {
1791
+ const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1792
+ if (!settings) {
1793
+ return;
1794
+ }
1795
+
1796
+ const absoluteRoot: string = Path.isAbsolute(settings.root)
1797
+ ? settings.root
1798
+ : Path.resolve(process.cwd(), settings.root);
1799
+
1800
+ const hasAssetCache: boolean =
1801
+ settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1802
+ const staticOptions: { setHeaders: (res: Express.Response, filePath: string) => void } | undefined =
1803
+ hasAssetCache && settings.assetCacheMaxAge !== undefined
1804
+ ? {
1805
+ setHeaders: (res: Express.Response, filePath: string): void => {
1806
+ // A HTML entry-fájlok (index.html) no-cache-t kapnak, a hash-elt asset-ek
1807
+ // immutable long-cache-t — lásd DyNTS_resolveStaticCacheControlHeader (served-stale-index fix).
1808
+ res.setHeader(
1809
+ 'Cache-Control',
1810
+ DyNTS_resolveStaticCacheControlHeader({
1811
+ filePath: filePath,
1812
+ assetCacheMaxAge: settings.assetCacheMaxAge!,
1813
+ assetCacheImmutable: settings.assetCacheImmutable === true,
1814
+ }),
1815
+ );
1816
+ },
1817
+ }
1818
+ : undefined;
1819
+
1820
+ const staticMiddleware: Express.Handler =
1821
+ staticOptions
1822
+ ? Express.static(absoluteRoot, staticOptions)
1823
+ : Express.static(absoluteRoot);
1824
+
1825
+ const fallbackMaxAge: number =
1826
+ settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1827
+
1828
+ // API-namespace guard (BFR-DYNAMOBUILDER-001): a catch-all fallback NE fedje az API-prefixeket —
1829
+ // egy ismeretlen `GET /api/...` 404 JSON-t kapjon, ne megtévesztő `200 + index.html`-t.
1830
+ // Konfigurálható (fallbackExcludePrefixes); default a bevett FDP namespace-pár.
1831
+ const excludePrefixes: string[] = settings.fallbackExcludePrefixes ?? ['/api', '/auth-api'];
1832
+ const isApiNamespacePath = (path: string): boolean =>
1833
+ excludePrefixes.some((prefix: string): boolean => path === prefix || path.startsWith(`${prefix}/`));
1834
+
1835
+ if (this.openExpress) {
1836
+ this.openExpress.use('/', staticMiddleware);
1837
+ if (settings.fallbackPath) {
1838
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1839
+ if (isApiNamespacePath(req.path)) {
1840
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1841
+ return;
1842
+ }
1843
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1844
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1845
+ });
1846
+ } else {
1847
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1848
+ if (isApiNamespacePath(req.path)) {
1849
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1850
+ return;
1851
+ }
1852
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1853
+ });
1854
+ }
1855
+ }
1856
+
1857
+ if (this.secureExpress) {
1858
+ this.secureExpress.use('/', staticMiddleware);
1859
+ if (settings.fallbackPath) {
1860
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1861
+ if (isApiNamespacePath(req.path)) {
1862
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1863
+ return;
1864
+ }
1865
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1866
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1867
+ });
1868
+ } else {
1869
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1870
+ if (isApiNamespacePath(req.path)) {
1871
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1872
+ return;
1873
+ }
1874
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1875
+ });
1876
+ }
1877
+ }
1878
+
1879
+ if (this.logSetup) {
1880
+ DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1881
+ }
1882
+ }
1883
+
1884
+ /**
1885
+ *
1886
+ */
1887
+ private setSecurity(): void {
1888
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1889
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1890
+ if (!module.security) {
1891
+ DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1892
+
1893
+ } else if (!this._security) {
1894
+ this._security = module.security;
1895
+
1896
+ } else if (this._security !== module.security) {
1897
+ this._security = DyNTS_RouteSecurity.both;
1898
+ }
1899
+ });
1900
+
1901
+ if (!this._security) {
1902
+ let msg = `Could not set security for the server! (${this.security})`;
1903
+
1904
+ msg += '\n RoutingModules:';
1905
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1906
+ msg += `\n ${module.route} (security: ${module.security})`;
1907
+ });
1908
+
1909
+ if (this._routingModules.length === 0) {
1910
+ msg += '\n - no RoutingModule found -\n';
1911
+ }
1912
+ DyFM_Log.warn(msg);
1913
+ }
1914
+ }
1915
+
1916
+ private _getDefaultErrorSettings(
1917
+ fnName: string,
1918
+ error: DyFM_AnyError
1919
+ ): DyFM_Error_Settings {
1920
+ return {
1921
+ status: (error as DyFM_Error)?.___status ?? 500,
1922
+ message: (error as Error)?.message ??
1923
+ (error as DyFM_Error)?._message ??
1924
+ `${fnName} was UNSUCCESSFUL (NTS)`,
1925
+ userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1926
+ addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1927
+ issuerService: `${this?.constructor?.name}-DyNTS_App`,
1928
+ level: DyFM_ErrorLevel.fatal,
1929
+ error: error,
1930
+ systemVersion: DyNTS_global_settings.systemVersion,
1931
+ };
1932
+ }
1933
+
1934
+ /**
1935
+ * MISSING Description (TODO)
1936
+ */
1937
+ abstract getAppParams(): DyNTS_App_Params;
1938
+
1939
+ /**
1940
+ * MISSING Description (TODO)
1941
+ */
1942
+ abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1943
+
1944
+ /**
1945
+ * MISSING Description (TODO)
1946
+ */
1947
+ abstract getPortSettings(): DyNTS_Http_Settings;
1948
+
1949
+ /**
1950
+ * MISSING Description (TODO)
1951
+ */
1952
+ overrideDynamoNTSGlobalSettings?(): void;
1953
+
1954
+ /**
1955
+ * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1956
+ * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1957
+ */
1958
+ getApiBasePath?(): string;
1959
+
1960
+ /**
1961
+ * MISSING Description (TODO)
1962
+ */
1963
+ getRoutingModules?(): DyNTS_RoutingModule[];
1964
+
1965
+ /**
1966
+ * MISSING Description (TODO)
1967
+ */
1968
+ getRootServices?(): Promise<any[]>;
1969
+
1970
+ /**
1971
+ * MISSING Description (TODO)
1972
+ */
1973
+ getCertificationSettings?(): DyNTS_Certification_Settings;
1974
+
1975
+ /**
1976
+ * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1977
+ * Opcionális fallbackPath pl. SPA index.html-hez.
1978
+ */
1979
+ getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1980
+
1981
+ /**
1982
+ * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1983
+ * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1984
+ * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1985
+ * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1986
+ * Ha undefined → no CORS headers, no preflight handling — back-compat.
1987
+ */
1988
+ getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1989
+
1990
+ /**
1991
+ * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1992
+ * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1993
+ * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1994
+ * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1995
+ * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1996
+ */
1997
+ registerCustomMiddleware?(
1998
+ express: Express.Application,
1999
+ security: DyNTS_RouteSecurity,
2000
+ ): void | Promise<void>;
2001
+
2002
+ /**
2003
+ * MISSING Description (TODO)
2004
+ */
2005
+ createEntries?(): Promise<void>;
2006
+
2007
+ /**
2008
+ * MISSING Description (TODO)
2009
+ */
2010
+ postProcess?(): Promise<void>;
2011
+
2012
+ }