@omnizap-system/omnizap 2.5.12

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 (425) hide show
  1. package/.clusterfuzzlite/Dockerfile +10 -0
  2. package/.env.example +907 -0
  3. package/.github/codeql/codeql-config.yml +10 -0
  4. package/.github/dependabot.yml +35 -0
  5. package/.github/workflows/ci.yml +73 -0
  6. package/.github/workflows/codeql.yml +106 -0
  7. package/.github/workflows/db-migration-check.yml +98 -0
  8. package/.github/workflows/dependency-review.yml +22 -0
  9. package/.github/workflows/deploy.yml +95 -0
  10. package/.github/workflows/release.yml +106 -0
  11. package/.github/workflows/security-attest-provenance.yml +51 -0
  12. package/.github/workflows/security-gitleaks.yml +34 -0
  13. package/.github/workflows/security-runner-hardening.yml +31 -0
  14. package/.github/workflows/security-scorecard.yml +44 -0
  15. package/.github/workflows/security-zap-baseline.yml +44 -0
  16. package/.github/workflows/security-zap-full-scan.yml +43 -0
  17. package/.github/workflows/security-zizmor.yml +36 -0
  18. package/.github/workflows/wiki-sync.yml +44 -0
  19. package/.gitleaks.toml +15 -0
  20. package/.prettierrc +34 -0
  21. package/CODE_OF_CONDUCT.md +114 -0
  22. package/LICENSE +56 -0
  23. package/README.md +110 -0
  24. package/SECURITY.md +110 -0
  25. package/app/config/index.js +4 -0
  26. package/app/configParts/adminIdentity.js +92 -0
  27. package/app/configParts/baileysConfig.js +1818 -0
  28. package/app/configParts/groupUtils.js +692 -0
  29. package/app/configParts/loggerConfig.js +394 -0
  30. package/app/configParts/messagePersistenceService.js +305 -0
  31. package/app/connection/baileysCompatibility.test.js +40 -0
  32. package/app/connection/baileysDbAuthState.js +344 -0
  33. package/app/connection/socketController.js +2243 -0
  34. package/app/controllers/messageController.js +7 -0
  35. package/app/controllers/messagePipeline/commandMiddleware.js +146 -0
  36. package/app/controllers/messagePipeline/conversationMiddleware.js +183 -0
  37. package/app/controllers/messagePipeline/messagePipelineMiddlewares.test.js +522 -0
  38. package/app/controllers/messagePipeline/postProcessingMiddleware.js +41 -0
  39. package/app/controllers/messagePipeline/preProcessingMiddlewares.js +166 -0
  40. package/app/controllers/messageProcessingPipeline.js +699 -0
  41. package/app/modules/adminModule/AGENT.md +4056 -0
  42. package/app/modules/adminModule/adminAiHelpService.js +56 -0
  43. package/app/modules/adminModule/adminConfigRuntime.js +177 -0
  44. package/app/modules/adminModule/commandConfig.json +7122 -0
  45. package/app/modules/adminModule/groupCommandHandlers.js +1823 -0
  46. package/app/modules/adminModule/groupCommandHandlers.test.js +350 -0
  47. package/app/modules/adminModule/groupEventHandlers.js +399 -0
  48. package/app/modules/aiModule/AGENT.md +547 -0
  49. package/app/modules/aiModule/aiAiHelpService.js +14 -0
  50. package/app/modules/aiModule/aiConfigRuntime.js +135 -0
  51. package/app/modules/aiModule/catCommand.js +967 -0
  52. package/app/modules/aiModule/commandConfig.json +981 -0
  53. package/app/modules/analyticsModule/messageAnalysisEventRepository.js +83 -0
  54. package/app/modules/gameModule/AGENT.md +196 -0
  55. package/app/modules/gameModule/commandConfig.json +366 -0
  56. package/app/modules/gameModule/diceCommand.js +42 -0
  57. package/app/modules/gameModule/gameAiHelpService.js +14 -0
  58. package/app/modules/gameModule/gameConfigRuntime.js +68 -0
  59. package/app/modules/menuModule/AGENT.md +205 -0
  60. package/app/modules/menuModule/commandConfig.json +366 -0
  61. package/app/modules/menuModule/common.js +316 -0
  62. package/app/modules/menuModule/menuAiHelpService.js +14 -0
  63. package/app/modules/menuModule/menuConfigRuntime.js +68 -0
  64. package/app/modules/menuModule/menus.js +66 -0
  65. package/app/modules/playModule/AGENT.md +321 -0
  66. package/app/modules/playModule/commandConfig.json +584 -0
  67. package/app/modules/playModule/playAiHelpService.js +14 -0
  68. package/app/modules/playModule/playCommand.js +1417 -0
  69. package/app/modules/playModule/playConfigRuntime.js +68 -0
  70. package/app/modules/quoteModule/AGENT.md +199 -0
  71. package/app/modules/quoteModule/commandConfig.json +366 -0
  72. package/app/modules/quoteModule/quoteAiHelpService.js +14 -0
  73. package/app/modules/quoteModule/quoteCommand.js +842 -0
  74. package/app/modules/quoteModule/quoteConfigRuntime.js +68 -0
  75. package/app/modules/rpgPokemonModule/AGENT.md +229 -0
  76. package/app/modules/rpgPokemonModule/commandConfig.json +386 -0
  77. package/app/modules/rpgPokemonModule/rpgBattleCanvasRenderer.js +795 -0
  78. package/app/modules/rpgPokemonModule/rpgBattleService.js +2110 -0
  79. package/app/modules/rpgPokemonModule/rpgBattleService.test.js +770 -0
  80. package/app/modules/rpgPokemonModule/rpgEvolutionUtils.js +22 -0
  81. package/app/modules/rpgPokemonModule/rpgPokemonAiHelpService.js +14 -0
  82. package/app/modules/rpgPokemonModule/rpgPokemonCommand.js +174 -0
  83. package/app/modules/rpgPokemonModule/rpgPokemonConfigRuntime.js +68 -0
  84. package/app/modules/rpgPokemonModule/rpgPokemonDomain.js +192 -0
  85. package/app/modules/rpgPokemonModule/rpgPokemonDomain.test.js +93 -0
  86. package/app/modules/rpgPokemonModule/rpgPokemonEvolution.test.js +46 -0
  87. package/app/modules/rpgPokemonModule/rpgPokemonMessages.js +746 -0
  88. package/app/modules/rpgPokemonModule/rpgPokemonRepository.js +1847 -0
  89. package/app/modules/rpgPokemonModule/rpgPokemonService.js +6839 -0
  90. package/app/modules/rpgPokemonModule/rpgProfileCanvasRenderer.js +354 -0
  91. package/app/modules/statsModule/AGENT.md +320 -0
  92. package/app/modules/statsModule/commandConfig.json +540 -0
  93. package/app/modules/statsModule/globalRankingCommand.js +64 -0
  94. package/app/modules/statsModule/rankingCommand.js +41 -0
  95. package/app/modules/statsModule/rankingCommon.js +1305 -0
  96. package/app/modules/statsModule/statsAiHelpService.js +14 -0
  97. package/app/modules/statsModule/statsConfigRuntime.js +68 -0
  98. package/app/modules/stickerModule/AGENT.md +692 -0
  99. package/app/modules/stickerModule/addStickerMetadata.js +239 -0
  100. package/app/modules/stickerModule/commandConfig.json +1216 -0
  101. package/app/modules/stickerModule/convertToWebp.js +367 -0
  102. package/app/modules/stickerModule/stickerAiHelpService.js +14 -0
  103. package/app/modules/stickerModule/stickerCommand.js +446 -0
  104. package/app/modules/stickerModule/stickerConfigRuntime.js +68 -0
  105. package/app/modules/stickerModule/stickerConvertCommand.js +159 -0
  106. package/app/modules/stickerModule/stickerTextCommand.js +653 -0
  107. package/app/modules/stickerPackModule/AGENT.md +215 -0
  108. package/app/modules/stickerPackModule/autoPackCollectorRuntime.js +20 -0
  109. package/app/modules/stickerPackModule/autoPackCollectorService.js +357 -0
  110. package/app/modules/stickerPackModule/commandConfig.json +387 -0
  111. package/app/modules/stickerPackModule/domainEventOutboxRepository.js +227 -0
  112. package/app/modules/stickerPackModule/domainEvents.js +52 -0
  113. package/app/modules/stickerPackModule/semanticReclassificationEngine.js +429 -0
  114. package/app/modules/stickerPackModule/semanticReclassificationEngine.test.js +75 -0
  115. package/app/modules/stickerPackModule/semanticThemeClusterService.js +544 -0
  116. package/app/modules/stickerPackModule/stickerAssetClassificationRepository.js +400 -0
  117. package/app/modules/stickerPackModule/stickerAssetRepository.js +400 -0
  118. package/app/modules/stickerPackModule/stickerAssetReprocessQueueRepository.js +175 -0
  119. package/app/modules/stickerPackModule/stickerAutoPackByTagsRuntime.js +3702 -0
  120. package/app/modules/stickerPackModule/stickerClassificationBackgroundRuntime.js +559 -0
  121. package/app/modules/stickerPackModule/stickerClassificationService.js +557 -0
  122. package/app/modules/stickerPackModule/stickerDedicatedTaskWorkerRuntime.js +249 -0
  123. package/app/modules/stickerPackModule/stickerDomainEventBus.js +65 -0
  124. package/app/modules/stickerPackModule/stickerDomainEventConsumerRuntime.js +208 -0
  125. package/app/modules/stickerPackModule/stickerMarketplaceDriftService.js +99 -0
  126. package/app/modules/stickerPackModule/stickerObjectStorageService.js +285 -0
  127. package/app/modules/stickerPackModule/stickerPackAiHelpService.js +14 -0
  128. package/app/modules/stickerPackModule/stickerPackCommandHandlers.js +1148 -0
  129. package/app/modules/stickerPackModule/stickerPackConfigRuntime.js +68 -0
  130. package/app/modules/stickerPackModule/stickerPackEngagementRepository.js +152 -0
  131. package/app/modules/stickerPackModule/stickerPackErrors.js +30 -0
  132. package/app/modules/stickerPackModule/stickerPackInteractionEventRepository.js +101 -0
  133. package/app/modules/stickerPackModule/stickerPackItemRepository.js +432 -0
  134. package/app/modules/stickerPackModule/stickerPackMarketplaceService.js +313 -0
  135. package/app/modules/stickerPackModule/stickerPackMessageService.js +268 -0
  136. package/app/modules/stickerPackModule/stickerPackRepository.js +450 -0
  137. package/app/modules/stickerPackModule/stickerPackScoreSnapshotRepository.js +179 -0
  138. package/app/modules/stickerPackModule/stickerPackScoreSnapshotRuntime.js +271 -0
  139. package/app/modules/stickerPackModule/stickerPackService.js +733 -0
  140. package/app/modules/stickerPackModule/stickerPackServiceRuntime.js +32 -0
  141. package/app/modules/stickerPackModule/stickerPackUtils.js +107 -0
  142. package/app/modules/stickerPackModule/stickerStorageService.js +559 -0
  143. package/app/modules/stickerPackModule/stickerWorkerPipelineRuntime.js +242 -0
  144. package/app/modules/stickerPackModule/stickerWorkerTaskQueueRepository.js +242 -0
  145. package/app/modules/systemMetricsModule/AGENT.md +193 -0
  146. package/app/modules/systemMetricsModule/commandConfig.json +344 -0
  147. package/app/modules/systemMetricsModule/pingCommand.js +399 -0
  148. package/app/modules/systemMetricsModule/systemMetricsAiHelpService.js +14 -0
  149. package/app/modules/systemMetricsModule/systemMetricsConfigRuntime.js +68 -0
  150. package/app/modules/tiktokModule/AGENT.md +196 -0
  151. package/app/modules/tiktokModule/commandConfig.json +366 -0
  152. package/app/modules/tiktokModule/tiktokAiHelpService.js +14 -0
  153. package/app/modules/tiktokModule/tiktokCommand.js +716 -0
  154. package/app/modules/tiktokModule/tiktokConfigRuntime.js +68 -0
  155. package/app/modules/userModule/AGENT.md +200 -0
  156. package/app/modules/userModule/commandConfig.json +386 -0
  157. package/app/modules/userModule/userAiHelpService.js +14 -0
  158. package/app/modules/userModule/userCommand.js +1155 -0
  159. package/app/modules/userModule/userConfigRuntime.js +68 -0
  160. package/app/modules/waifuPicsModule/AGENT.md +431 -0
  161. package/app/modules/waifuPicsModule/commandConfig.json +780 -0
  162. package/app/modules/waifuPicsModule/waifuPicsAiHelpService.js +14 -0
  163. package/app/modules/waifuPicsModule/waifuPicsCommand.js +586 -0
  164. package/app/modules/waifuPicsModule/waifuPicsConfigRuntime.js +68 -0
  165. package/app/observability/metrics.js +766 -0
  166. package/app/services/ai/aiHelpResponseCacheRepository.js +280 -0
  167. package/app/services/ai/aiLearningRepository.js +400 -0
  168. package/app/services/ai/commandConfigEnrichmentRepository.js +769 -0
  169. package/app/services/ai/commandConfigEnrichmentService.js +452 -0
  170. package/app/services/ai/commandConfigValidationService.js +443 -0
  171. package/app/services/ai/commandToolBuilderService.js +192 -0
  172. package/app/services/ai/conversationRouterService.js +516 -0
  173. package/app/services/ai/geminiService.js +115 -0
  174. package/app/services/ai/geminiService.test.js +87 -0
  175. package/app/services/ai/globalModuleAiHelpService.js +1412 -0
  176. package/app/services/ai/globalToolCallingService.js +203 -0
  177. package/app/services/ai/messageCommandExecutionService.js +391 -0
  178. package/app/services/ai/moduleAiHelpCoreService.js +1099 -0
  179. package/app/services/ai/moduleAiHelpWrapperFactory.js +65 -0
  180. package/app/services/ai/moduleCommandConfigRuntimeService.js +113 -0
  181. package/app/services/ai/moduleToolExecutorService.js +464 -0
  182. package/app/services/ai/moduleToolRegistryService.js +178 -0
  183. package/app/services/ai/toolCandidateSelectorService.js +781 -0
  184. package/app/services/auth/googleWebLinkService.js +80 -0
  185. package/app/services/auth/whatsappLoginLinkService.js +230 -0
  186. package/app/services/external/pokeApiService.js +398 -0
  187. package/app/services/group/groupMetadataService.js +311 -0
  188. package/app/services/infra/dbWriteQueue.js +874 -0
  189. package/app/services/infra/featureFlagService.js +131 -0
  190. package/app/services/infra/queueUtils.js +55 -0
  191. package/app/services/messaging/captchaService.js +491 -0
  192. package/app/services/messaging/messagePersistenceService.js +1 -0
  193. package/app/services/messaging/newsBroadcastService.js +347 -0
  194. package/app/services/sticker/stickerFocusService.js +347 -0
  195. package/app/services/sticker/stickerFocusService.test.js +43 -0
  196. package/app/store/aiPromptStore.js +38 -0
  197. package/app/store/conversationSessionStore.js +131 -0
  198. package/app/store/groupConfigStore.js +58 -0
  199. package/app/store/premiumUserStore.js +54 -0
  200. package/app/utils/antiLink/antiLinkModule.js +700 -0
  201. package/app/utils/http/getImageBufferModule.js +18 -0
  202. package/app/utils/json/jsonSanitizer.js +113 -0
  203. package/app/utils/json/jsonSanitizer.test.js +40 -0
  204. package/app/utils/systemMetrics/systemMetricsModule.js +88 -0
  205. package/app/workers/aiLearningWorker.js +605 -0
  206. package/app/workers/commandConfigEnrichmentWorker.js +242 -0
  207. package/database/index.js +2075 -0
  208. package/database/init.js +151 -0
  209. package/database/migrations/.gitkeep +0 -0
  210. package/database/migrations/20260307_d0_hardening_down.sql +64 -0
  211. package/database/migrations/20260307_d0_hardening_up.sql +79 -0
  212. package/database/migrations/20260307_d1_terms_acceptance_down.sql +11 -0
  213. package/database/migrations/20260307_d1_terms_acceptance_up.sql +37 -0
  214. package/database/migrations/20260307_d2_auth_hardening_down.sql +75 -0
  215. package/database/migrations/20260307_d2_auth_hardening_up.sql +100 -0
  216. package/database/migrations/20260314_d7_canonical_sender_down.sql +53 -0
  217. package/database/migrations/20260314_d7_canonical_sender_up.sql +114 -0
  218. package/database/migrations/20260406_d30_security_analytics_down.sql +95 -0
  219. package/database/migrations/20260406_d30_security_analytics_up.sql +292 -0
  220. package/database/migrations/20260407_d31_web_google_session_token_hardening_down.sql +2 -0
  221. package/database/migrations/20260407_d31_web_google_session_token_hardening_up.sql +17 -0
  222. package/database/migrations/20260408_d32_ai_help_response_cache_down.sql +1 -0
  223. package/database/migrations/20260408_d32_ai_help_response_cache_up.sql +22 -0
  224. package/database/migrations/20260409_d33_ai_learning_tables_down.sql +4 -0
  225. package/database/migrations/20260409_d33_ai_learning_tables_up.sql +52 -0
  226. package/database/migrations/20260410_d34_command_config_enrichment_down.sql +3 -0
  227. package/database/migrations/20260410_d34_command_config_enrichment_up.sql +48 -0
  228. package/database/schema.sql +1186 -0
  229. package/docker-compose.yml +104 -0
  230. package/docs/audits/stickerCatalogController-out-of-scope.md +103 -0
  231. package/docs/audits/stickerCatalogController-symbols.md +58 -0
  232. package/docs/compliance/acceptable-use-policy-2026-03-07.md +35 -0
  233. package/docs/compliance/dpa-b2b-standard-2026-03-07.md +80 -0
  234. package/docs/compliance/monthly-compliance-checklist-2026-03-07.md +88 -0
  235. package/docs/compliance/notice-and-takedown-policy-2026-03-07.md +34 -0
  236. package/docs/compliance/privacy-policy-2026-03-07.md +75 -0
  237. package/docs/compliance/subprocessors-inventory-2026-03-07.md +16 -0
  238. package/docs/database/production-db-evolution-runbook-2026q1.md +365 -0
  239. package/docs/security/dsar-lgpd-runbook-2026-03-07.md +86 -0
  240. package/docs/security/incident-response-lgpd-anpd-runbook-2026-03-07.md +77 -0
  241. package/docs/security/network-hardening-runbook-2026-03-07.md +137 -0
  242. package/docs/seo/omnizap-seo-playbook-br-2026-02-28.md +238 -0
  243. package/docs/seo/satellite-page-template.md +116 -0
  244. package/docs/seo/satellite-pages-phase1.json +364 -0
  245. package/docs/wiki/Home.md +120 -0
  246. package/docs/wiki/pair-extraordinaire-2026-03-08.md +3 -0
  247. package/docs/wiki/recent-changes-2026-03-08.md +47 -0
  248. package/ecosystem.prod.config.cjs +135 -0
  249. package/eslint.config.js +89 -0
  250. package/index.js +488 -0
  251. package/ml/clip_classifier/Dockerfile +18 -0
  252. package/ml/clip_classifier/README.md +118 -0
  253. package/ml/clip_classifier/adaptive_scoring.py +40 -0
  254. package/ml/clip_classifier/classifier.py +654 -0
  255. package/ml/clip_classifier/embedding_store.py +481 -0
  256. package/ml/clip_classifier/env_loader.py +15 -0
  257. package/ml/clip_classifier/llm_label_expander.py +144 -0
  258. package/ml/clip_classifier/main.py +213 -0
  259. package/ml/clip_classifier/requirements.txt +10 -0
  260. package/ml/clip_classifier/similarity_engine.py +74 -0
  261. package/new-logo.png +0 -0
  262. package/observability/alert-rules.yml +60 -0
  263. package/observability/grafana/dashboards/omnizap-mysql.json +136 -0
  264. package/observability/grafana/dashboards/omnizap-overview.json +170 -0
  265. package/observability/grafana/provisioning/dashboards/dashboards.yml +11 -0
  266. package/observability/grafana/provisioning/datasources/datasources.yml +15 -0
  267. package/observability/loki-config.yml +38 -0
  268. package/observability/mysql-setup.sql +46 -0
  269. package/observability/prometheus.yml +35 -0
  270. package/observability/promtail-config.yml +84 -0
  271. package/observability/sticker-catalog-slo.md +83 -0
  272. package/observability/sticker-scale-hardening-rollout.md +128 -0
  273. package/package.json +144 -0
  274. package/public/apple-touch-icon.png +0 -0
  275. package/public/assets/css/commands-react.input.css +71 -0
  276. package/public/assets/css/create-pack-react.input.css +31 -0
  277. package/public/assets/css/home-react.input.css +106 -0
  278. package/public/assets/css/login-react.input.css +58 -0
  279. package/public/assets/css/stickers-react.input.css +18 -0
  280. package/public/assets/css/terms-react.input.css +115 -0
  281. package/public/assets/css/user-react.input.css +57 -0
  282. package/public/assets/images/brand-icon-192.png +0 -0
  283. package/public/assets/images/brand-logo-128.webp +0 -0
  284. package/public/assets/images/hero-banner-1280.jpg +0 -0
  285. package/public/comandos/commands-catalog.json +4517 -0
  286. package/public/css/api-docs.css +161 -0
  287. package/public/css/stickers-admin.css +1288 -0
  288. package/public/css/styles.css +679 -0
  289. package/public/css/systemadm/admin.css +474 -0
  290. package/public/css/systemadm/base.css +73 -0
  291. package/public/css/systemadm/components.css +662 -0
  292. package/public/css/systemadm/layout.css +229 -0
  293. package/public/css/systemadm/tokens.css +56 -0
  294. package/public/favicon-16x16.png +0 -0
  295. package/public/favicon-32x32.png +0 -0
  296. package/public/favicon.ico +0 -0
  297. package/public/js/apps/apiDocsApp.js +235 -0
  298. package/public/js/apps/commandsReactApp.js +528 -0
  299. package/public/js/apps/createPackApp.js +1646 -0
  300. package/public/js/apps/homeReactApp.js +942 -0
  301. package/public/js/apps/loginReactApp.js +496 -0
  302. package/public/js/apps/stickersAdminApp.js +1753 -0
  303. package/public/js/apps/stickersApp.js +3797 -0
  304. package/public/js/apps/termsReactApp.js +528 -0
  305. package/public/js/apps/userApp.js +2540 -0
  306. package/public/js/apps/userProfile/actions.js +66 -0
  307. package/public/js/apps/userReactApp.js +547 -0
  308. package/public/js/catalog.js +950 -0
  309. package/public/pages/api-docs.html +40 -0
  310. package/public/pages/aup.html +158 -0
  311. package/public/pages/comandos.html +41 -0
  312. package/public/pages/dpa.html +227 -0
  313. package/public/pages/home.html +45 -0
  314. package/public/pages/licenca.html +182 -0
  315. package/public/pages/login.html +40 -0
  316. package/public/pages/notice-and-takedown.html +234 -0
  317. package/public/pages/politica-de-privacidade.html +251 -0
  318. package/public/pages/seo-bot-whatsapp-para-grupo.html +350 -0
  319. package/public/pages/seo-bot-whatsapp-sem-programar.html +350 -0
  320. package/public/pages/seo-como-automatizar-avisos-no-whatsapp.html +350 -0
  321. package/public/pages/seo-como-criar-comandos-whatsapp.html +350 -0
  322. package/public/pages/seo-como-evitar-spam-no-whatsapp.html +350 -0
  323. package/public/pages/seo-como-moderar-grupo-whatsapp.html +350 -0
  324. package/public/pages/seo-como-organizar-comunidade-whatsapp.html +350 -0
  325. package/public/pages/seo-melhor-bot-whatsapp-para-grupos.html +350 -0
  326. package/public/pages/stickers-admin.html +31 -0
  327. package/public/pages/stickers-create.html +41 -0
  328. package/public/pages/stickers.html +45 -0
  329. package/public/pages/suboperadores.html +237 -0
  330. package/public/pages/termos-de-uso-texto-integral.html +241 -0
  331. package/public/pages/termos-de-uso.html +41 -0
  332. package/public/pages/user-password-reset.html +32 -0
  333. package/public/pages/user-systemadm.html +508 -0
  334. package/public/pages/user.html +39 -0
  335. package/public/robots.txt +9 -0
  336. package/public/site.webmanifest +24 -0
  337. package/public/sitemap.xml +98 -0
  338. package/schemas/command-config.schema.json +582 -0
  339. package/scripts/baileys-compat-smoke.mjs +12 -0
  340. package/scripts/cache-bust.mjs +142 -0
  341. package/scripts/deploy.sh +916 -0
  342. package/scripts/email-broadcast-terms-update.mjs +170 -0
  343. package/scripts/enrich-command-discovery-fields.mjs +286 -0
  344. package/scripts/generate-command-config-schema.mjs +273 -0
  345. package/scripts/generate-commands-catalog.mjs +308 -0
  346. package/scripts/generate-module-agents.mjs +631 -0
  347. package/scripts/generate-seo-satellite-pages.mjs +400 -0
  348. package/scripts/github-deploy-notify.mjs +174 -0
  349. package/scripts/github-release-notify.mjs +219 -0
  350. package/scripts/release.sh +599 -0
  351. package/scripts/run-codeql-local.sh +116 -0
  352. package/scripts/run-prettier-all.mjs +25 -0
  353. package/scripts/security-smoketest.mjs +581 -0
  354. package/scripts/sticker-catalog-loadtest.mjs +210 -0
  355. package/scripts/sticker-worker-task.mjs +119 -0
  356. package/scripts/sync-readme-snapshot.mjs +133 -0
  357. package/scripts/validate-command-config-schema.mjs +130 -0
  358. package/scripts/validate-command-configs.mjs +15 -0
  359. package/scripts/wiki-sync.sh +191 -0
  360. package/server/auth/googleWebAuth/googleWebAuthRuntime.js +62 -0
  361. package/server/auth/googleWebAuth/googleWebAuthService.js +807 -0
  362. package/server/auth/jwt/webJwtService.js +147 -0
  363. package/server/auth/stickerCatalogAuthContext.js +165 -0
  364. package/server/auth/termsAcceptance/termsAcceptanceHandler.js +189 -0
  365. package/server/auth/userPassword/index.js +14 -0
  366. package/server/auth/userPassword/userPasswordAuthService.js +422 -0
  367. package/server/auth/userPassword/userPasswordCrypto.js +199 -0
  368. package/server/auth/userPassword/userPasswordCrypto.test.js +76 -0
  369. package/server/auth/userPassword/userPasswordRecoveryService.js +728 -0
  370. package/server/auth/validation/authSchemas.js +236 -0
  371. package/server/auth/webAccount/webAccountHandlers.js +1434 -0
  372. package/server/controllers/admin/adminBanService.js +138 -0
  373. package/server/controllers/admin/adminPanelHandlers.js +2083 -0
  374. package/server/controllers/admin/stickerCatalogAdminContext.js +17 -0
  375. package/server/controllers/admin/systemAdminController.js +201 -0
  376. package/server/controllers/email/emailAutomationController.js +239 -0
  377. package/server/controllers/metricsController.js +21 -0
  378. package/server/controllers/seo/stickerCatalogSeoContext.js +514 -0
  379. package/server/controllers/sticker/nonCatalogHandlers.js +303 -0
  380. package/server/controllers/sticker/stickerCatalogController.js +4700 -0
  381. package/server/controllers/system/contactController.js +115 -0
  382. package/server/controllers/system/githubController.js +137 -0
  383. package/server/controllers/system/stickerCatalogSystemContext.js +758 -0
  384. package/server/controllers/system/storageController.js +154 -0
  385. package/server/controllers/system/systemController.js +135 -0
  386. package/server/controllers/system/systemMetricsController.js +156 -0
  387. package/server/controllers/system/visitController.js +90 -0
  388. package/server/controllers/userController.js +145 -0
  389. package/server/email/emailAutomationRuntime.js +225 -0
  390. package/server/email/emailAutomationService.js +125 -0
  391. package/server/email/emailOutboxRepository.js +282 -0
  392. package/server/email/emailTemplateService.js +480 -0
  393. package/server/email/emailTransportService.js +156 -0
  394. package/server/http/clientIp.js +95 -0
  395. package/server/http/httpRequestUtils.js +262 -0
  396. package/server/http/httpRequestUtils.test.js +80 -0
  397. package/server/http/httpServer.js +180 -0
  398. package/server/http/requestContext.js +20 -0
  399. package/server/http/siteRoutingUtils.js +87 -0
  400. package/server/index.js +1 -0
  401. package/server/middleware/cachePolicy.js +26 -0
  402. package/server/middleware/cachePolicyHelpers.js +1 -0
  403. package/server/middleware/endpointRateLimit.js +181 -0
  404. package/server/middleware/rateLimit.js +70 -0
  405. package/server/middleware/requireAdminAuth.js +48 -0
  406. package/server/middleware/securityHeaders.js +97 -0
  407. package/server/routes/admin/systemAdminRouter.js +64 -0
  408. package/server/routes/email/emailAutomationRouter.js +46 -0
  409. package/server/routes/health/healthRouter.js +41 -0
  410. package/server/routes/indexRouter.js +234 -0
  411. package/server/routes/metrics/metricsRouter.js +58 -0
  412. package/server/routes/static/staticPageRouter.js +134 -0
  413. package/server/routes/sticker/catalogHandlers/catalogAdminHttp.js +105 -0
  414. package/server/routes/sticker/catalogHandlers/catalogAuthHttp.js +77 -0
  415. package/server/routes/sticker/catalogHandlers/catalogPublicHttp.js +120 -0
  416. package/server/routes/sticker/catalogHandlers/catalogUploadHttp.js +83 -0
  417. package/server/routes/sticker/catalogRouter.js +77 -0
  418. package/server/routes/sticker/stickerApiRouter.js +84 -0
  419. package/server/routes/sticker/stickerDataRouter.js +145 -0
  420. package/server/routes/sticker/stickerSiteRouter.js +43 -0
  421. package/server/routes/user/userApiPaths.js +66 -0
  422. package/server/routes/user/userRouter.js +65 -0
  423. package/server/utils/safePath.js +26 -0
  424. package/utils/logger/loggerModule.js +35 -0
  425. package/vite.config.mjs +38 -0
@@ -0,0 +1,95 @@
1
+ import { isIP } from 'node:net';
2
+
3
+ const parseEnvBool = (value, fallback = false) => {
4
+ if (value === undefined || value === null || value === '') return fallback;
5
+ const normalized = String(value).trim().toLowerCase();
6
+ if (['1', 'true', 'yes', 'y', 'on'].includes(normalized)) return true;
7
+ if (['0', 'false', 'no', 'n', 'off'].includes(normalized)) return false;
8
+ return fallback;
9
+ };
10
+
11
+ const TRUST_PROXY_HEADERS = parseEnvBool(process.env.APP_TRUST_PROXY, parseEnvBool(process.env.RATE_LIMIT_TRUST_PROXY, false));
12
+ const LOOPBACK_IPS = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
13
+
14
+ const normalizeIpCandidate = (value) => {
15
+ let raw = String(value || '').trim();
16
+ if (!raw) return '';
17
+
18
+ if (raw.startsWith('for=')) raw = raw.slice(4).trim();
19
+ if (raw.startsWith('"') && raw.endsWith('"') && raw.length > 1) raw = raw.slice(1, -1).trim();
20
+ if (raw === 'unknown') return '';
21
+
22
+ if (raw.startsWith('[')) {
23
+ const closeBracketIndex = raw.indexOf(']');
24
+ if (closeBracketIndex > 1) {
25
+ raw = raw.slice(1, closeBracketIndex).trim();
26
+ }
27
+ }
28
+
29
+ const ipv4WithPortMatch = raw.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/);
30
+ if (ipv4WithPortMatch?.[1]) raw = ipv4WithPortMatch[1];
31
+
32
+ const zoneIndex = raw.indexOf('%');
33
+ if (zoneIndex > 0) raw = raw.slice(0, zoneIndex);
34
+
35
+ if (raw.startsWith('::ffff:') && isIP(raw.slice(7)) === 4) raw = raw.slice(7);
36
+
37
+ return isIP(raw) ? raw : '';
38
+ };
39
+
40
+ const pickFirstValidIpFromCommaList = (value) => {
41
+ const raw = Array.isArray(value) ? value.join(',') : String(value || '');
42
+ if (!raw.trim()) return '';
43
+
44
+ for (const part of raw.split(',')) {
45
+ const ip = normalizeIpCandidate(part);
46
+ if (ip) return ip;
47
+ }
48
+
49
+ return '';
50
+ };
51
+
52
+ const pickFirstValidIpFromForwardedHeader = (value) => {
53
+ const raw = Array.isArray(value) ? value.join(',') : String(value || '');
54
+ if (!raw.trim()) return '';
55
+
56
+ const entries = raw.split(',');
57
+ for (const entry of entries) {
58
+ const directives = entry.split(';');
59
+ for (const directive of directives) {
60
+ const trimmed = String(directive || '').trim();
61
+ if (!trimmed || !trimmed.toLowerCase().startsWith('for=')) continue;
62
+ const ip = normalizeIpCandidate(trimmed);
63
+ if (ip) return ip;
64
+ }
65
+ }
66
+
67
+ return '';
68
+ };
69
+
70
+ const shouldTrustForwardedHeaders = (socketIp = '', explicitTrustProxy = undefined) => {
71
+ if (typeof explicitTrustProxy === 'boolean') return explicitTrustProxy;
72
+ if (TRUST_PROXY_HEADERS) return true;
73
+ return LOOPBACK_IPS.has(socketIp);
74
+ };
75
+
76
+ export const resolveClientIp = (req, { fallback = 'unknown', trustProxy = undefined } = {}) => {
77
+ const socketIp = normalizeIpCandidate(req?.socket?.remoteAddress);
78
+
79
+ if (shouldTrustForwardedHeaders(socketIp, trustProxy)) {
80
+ const cfConnectingIp = normalizeIpCandidate(req?.headers?.['cf-connecting-ip']);
81
+ if (cfConnectingIp) return cfConnectingIp;
82
+
83
+ const xRealIp = normalizeIpCandidate(req?.headers?.['x-real-ip']);
84
+ if (xRealIp) return xRealIp;
85
+
86
+ const forwardedFor = pickFirstValidIpFromCommaList(req?.headers?.['x-forwarded-for']);
87
+ if (forwardedFor) return forwardedFor;
88
+
89
+ const forwarded = pickFirstValidIpFromForwardedHeader(req?.headers?.forwarded);
90
+ if (forwarded) return forwarded;
91
+ }
92
+
93
+ if (socketIp) return socketIp;
94
+ return fallback;
95
+ };
@@ -0,0 +1,262 @@
1
+ import { resolveClientIp } from './clientIp.js';
2
+ import { resolveCookieDomainForRequest } from './siteRoutingUtils.js';
3
+
4
+ const parseEnvBool = (value, fallback = false) => {
5
+ if (value === undefined || value === null || value === '') return fallback;
6
+ const normalized = String(value).trim().toLowerCase();
7
+ if (['1', 'true', 'yes', 'y', 'on'].includes(normalized)) return true;
8
+ if (['0', 'false', 'no', 'n', 'off'].includes(normalized)) return false;
9
+ return fallback;
10
+ };
11
+
12
+ const LOOPBACK_IPS = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
13
+
14
+ const shouldTrustForwardedProtoHeader = (req) => {
15
+ const trustProxyHeaders = parseEnvBool(process.env.APP_TRUST_PROXY, parseEnvBool(process.env.RATE_LIMIT_TRUST_PROXY, false));
16
+ if (trustProxyHeaders) return true;
17
+
18
+ const socketIp = resolveClientIp(req, { fallback: '', trustProxy: false });
19
+ return LOOPBACK_IPS.has(socketIp);
20
+ };
21
+
22
+ export const sendJson = (req, res, statusCode, payload) => {
23
+ const body = JSON.stringify(payload)
24
+ .replace(/</g, '\\u003c')
25
+ .replace(/>/g, '\\u003e')
26
+ .replace(/&/g, '\\u0026')
27
+ .replace(/\u2028/g, '\\u2028')
28
+ .replace(/\u2029/g, '\\u2029');
29
+ res.statusCode = statusCode;
30
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
31
+ res.setHeader('Cache-Control', 'no-store');
32
+ res.setHeader('X-Robots-Tag', 'noindex, nofollow');
33
+ if (req.method === 'HEAD') {
34
+ res.end();
35
+ return;
36
+ }
37
+ res.end(body);
38
+ };
39
+
40
+ export const sendText = (req, res, statusCode, body, contentType) => {
41
+ res.statusCode = statusCode;
42
+ res.setHeader('Content-Type', contentType);
43
+ if (req.method === 'HEAD') {
44
+ res.end();
45
+ return;
46
+ }
47
+ res.end(body);
48
+ };
49
+
50
+ /**
51
+ * Envia buffer binário (asset estático) com headers básicos de cache.
52
+ * @param {import('node:http').IncomingMessage} req
53
+ * @param {import('node:http').ServerResponse} res
54
+ * @param {Buffer} buffer
55
+ * @param {string} [mimetype]
56
+ * @param {string} [cacheControl]
57
+ * @returns {void}
58
+ */
59
+ export const sendAsset = (req, res, buffer, mimetype = 'application/octet-stream', cacheControl = 'public, max-age=86400') => {
60
+ res.statusCode = 200;
61
+ res.setHeader('Content-Type', mimetype);
62
+ res.setHeader('Content-Length', String(Buffer.byteLength(buffer)));
63
+ res.setHeader('Cache-Control', cacheControl);
64
+ if (req.method === 'HEAD') {
65
+ res.end();
66
+ return;
67
+ }
68
+ res.end(buffer);
69
+ };
70
+
71
+ export const parseCookies = (req) => {
72
+ const raw = String(req?.headers?.cookie || '');
73
+ if (!raw) return {};
74
+ return raw.split(';').reduce((acc, chunk) => {
75
+ const [k, ...rest] = chunk.split('=');
76
+ const key = String(k || '').trim();
77
+ if (!key) return acc;
78
+ const value = rest.join('=').trim();
79
+ try {
80
+ acc[key] = decodeURIComponent(value);
81
+ } catch {
82
+ acc[key] = value;
83
+ }
84
+ return acc;
85
+ }, {});
86
+ };
87
+
88
+ export const getCookieValuesFromRequest = (req, cookieName) => {
89
+ const target = String(cookieName || '').trim();
90
+ if (!target) return [];
91
+ const raw = String(req?.headers?.cookie || '');
92
+ if (!raw) return [];
93
+
94
+ const values = [];
95
+ for (const chunk of raw.split(';')) {
96
+ const trimmed = String(chunk || '').trim();
97
+ if (!trimmed) continue;
98
+ const separatorIndex = trimmed.indexOf('=');
99
+ if (separatorIndex <= 0) continue;
100
+ const key = trimmed.slice(0, separatorIndex).trim();
101
+ if (key !== target) continue;
102
+ const encodedValue = trimmed.slice(separatorIndex + 1).trim();
103
+ if (!encodedValue) continue;
104
+ let decodedValue = encodedValue;
105
+ try {
106
+ decodedValue = decodeURIComponent(encodedValue);
107
+ } catch (error) {
108
+ if (error) decodedValue = encodedValue;
109
+ }
110
+ const normalizedValue = String(decodedValue || '').trim();
111
+ if (!normalizedValue) continue;
112
+ if (!values.includes(normalizedValue)) values.push(normalizedValue);
113
+ }
114
+ return values;
115
+ };
116
+
117
+ export const isRequestSecure = (req) => {
118
+ const socketEncrypted = Boolean(req?.socket?.encrypted);
119
+ const proto = String(req?.headers?.['x-forwarded-proto'] || '')
120
+ .split(',')[0]
121
+ .trim()
122
+ .toLowerCase();
123
+ if (proto && shouldTrustForwardedProtoHeader(req)) {
124
+ return proto === 'https';
125
+ }
126
+ return socketEncrypted;
127
+ };
128
+
129
+ export const resolveRequestRemoteIp = (req) => resolveClientIp(req, { fallback: null });
130
+
131
+ /**
132
+ * Converte um valor para string ISO ou null se inválido.
133
+ * @param {any} value
134
+ * @returns {string|null}
135
+ */
136
+ export const toIsoOrNull = (value) => (value ? new Date(value).toISOString() : null);
137
+
138
+ /**
139
+ * Formata duração em segundos para HH:MM:SS ou Dd HH:MM:SS.
140
+ * @param {number} totalSeconds
141
+ * @returns {string}
142
+ */
143
+ export const formatDuration = (totalSeconds) => {
144
+ const total = Math.max(0, Math.floor(Number(totalSeconds) || 0));
145
+ const days = Math.floor(total / 86400);
146
+ const hours = Math.floor((total % 86400) / 3600);
147
+ const minutes = Math.floor((total % 3600) / 60);
148
+ const seconds = total % 60;
149
+ const hhmmss = [hours, minutes, seconds].map((value) => String(value).padStart(2, '0')).join(':');
150
+ return days > 0 ? `${days}d ${hhmmss}` : hhmmss;
151
+ };
152
+
153
+ /**
154
+ * Normaliza caminho base garantindo barra inicial e removendo barra final.
155
+ * @param {string} value
156
+ * @param {string} fallback
157
+ * @returns {string}
158
+ */
159
+ export const normalizeBasePath = (value, fallback) => {
160
+ const raw = String(value || '').trim() || fallback;
161
+ const withLeadingSlash = raw.startsWith('/') ? raw : `/${raw}`;
162
+ const withoutTrailingSlash = withLeadingSlash.length > 1 && withLeadingSlash.endsWith('/') ? withLeadingSlash.slice(0, -1) : withLeadingSlash;
163
+ return withoutTrailingSlash || fallback;
164
+ };
165
+
166
+ /**
167
+ * Envolve uma promessa com um tempo limite.
168
+ * @param {Promise<any>} promise
169
+ * @param {number} timeoutMs
170
+ * @returns {Promise<any>}
171
+ */
172
+ export const withTimeout = (promise, timeoutMs) =>
173
+ Promise.race([
174
+ promise,
175
+ new Promise((_, reject) => {
176
+ setTimeout(() => reject(new Error(`timeout_${timeoutMs}ms`)), timeoutMs);
177
+ }),
178
+ ]);
179
+
180
+ export const normalizeCatalogVisibility = (value) => {
181
+ const normalized = String(value || '')
182
+ .trim()
183
+ .toLowerCase();
184
+ if (normalized === 'all') return 'all';
185
+ if (normalized === 'unlisted') return 'unlisted';
186
+ return 'public';
187
+ };
188
+
189
+ /**
190
+ * Normaliza o caminho de uma visita web.
191
+ * @param {string} raw
192
+ * @returns {string}
193
+ */
194
+ export const normalizeVisitPath = (raw) => {
195
+ const normalized = String(raw || '')
196
+ .trim()
197
+ .replace(/\s+/g, '')
198
+ .slice(0, 255);
199
+ if (!normalized) return '/';
200
+ return normalized.startsWith('/') ? normalized : `/${normalized}`;
201
+ };
202
+
203
+ export const appendSetCookie = (res, cookieValue) => {
204
+ const current = res.getHeader('Set-Cookie');
205
+ if (!current) {
206
+ res.setHeader('Set-Cookie', cookieValue);
207
+ return;
208
+ }
209
+ if (Array.isArray(current)) {
210
+ res.setHeader('Set-Cookie', [...current, cookieValue]);
211
+ return;
212
+ }
213
+ res.setHeader('Set-Cookie', [String(current), cookieValue]);
214
+ };
215
+
216
+ export const buildCookieString = (name, value, req, options = {}) => {
217
+ const parts = [`${name}=${encodeURIComponent(String(value ?? ''))}`];
218
+ parts.push(`Path=${options.path || '/'}`);
219
+ const cookieDomain = options.domain === false ? '' : String(options.domain || resolveCookieDomainForRequest(req)).trim();
220
+ if (cookieDomain) parts.push(`Domain=${cookieDomain}`);
221
+ if (options.httpOnly !== false) parts.push('HttpOnly');
222
+ parts.push(`SameSite=${options.sameSite || 'Lax'}`);
223
+ if (isRequestSecure(req)) parts.push('Secure');
224
+ if (Number.isFinite(options.maxAgeSeconds)) parts.push(`Max-Age=${Math.max(0, Math.floor(options.maxAgeSeconds))}`);
225
+ return parts.join('; ');
226
+ };
227
+
228
+ export const readJsonBody = async (req, { maxBytes = 64 * 1024 } = {}) =>
229
+ new Promise((resolve, reject) => {
230
+ const chunks = [];
231
+ let total = 0;
232
+
233
+ req.on('data', (chunk) => {
234
+ total += chunk.length;
235
+ if (total > maxBytes) {
236
+ const error = new Error('Payload excedeu limite permitido.');
237
+ error.statusCode = 413;
238
+ reject(error);
239
+ req.destroy();
240
+ return;
241
+ }
242
+ chunks.push(chunk);
243
+ });
244
+
245
+ req.on('end', () => {
246
+ const raw = Buffer.concat(chunks).toString('utf8').trim();
247
+ if (!raw) {
248
+ resolve({});
249
+ return;
250
+ }
251
+
252
+ try {
253
+ resolve(JSON.parse(raw));
254
+ } catch {
255
+ const error = new Error('JSON invalido.');
256
+ error.statusCode = 400;
257
+ reject(error);
258
+ }
259
+ });
260
+
261
+ req.on('error', (error) => reject(error));
262
+ });
@@ -0,0 +1,80 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { isRequestSecure } from './httpRequestUtils.js';
5
+
6
+ const withEnv = (overrides, fn) => {
7
+ const previous = new Map();
8
+ for (const [key, value] of Object.entries(overrides)) {
9
+ previous.set(key, Object.prototype.hasOwnProperty.call(process.env, key) ? process.env[key] : null);
10
+ if (value === undefined || value === null) {
11
+ delete process.env[key];
12
+ } else {
13
+ process.env[key] = String(value);
14
+ }
15
+ }
16
+
17
+ try {
18
+ return fn();
19
+ } finally {
20
+ for (const [key, value] of previous.entries()) {
21
+ if (value === null) {
22
+ delete process.env[key];
23
+ } else {
24
+ process.env[key] = value;
25
+ }
26
+ }
27
+ }
28
+ };
29
+
30
+ const buildReq = ({ forwardedProto = '', remoteAddress = '203.0.113.10', encrypted = false } = {}) => ({
31
+ headers: forwardedProto ? { 'x-forwarded-proto': forwardedProto } : {},
32
+ socket: {
33
+ remoteAddress,
34
+ encrypted,
35
+ },
36
+ });
37
+
38
+ test('isRequestSecure ignores x-forwarded-proto for untrusted remote proxy', () => {
39
+ withEnv({ APP_TRUST_PROXY: 'false', RATE_LIMIT_TRUST_PROXY: 'false' }, () => {
40
+ const req = buildReq({
41
+ forwardedProto: 'https',
42
+ remoteAddress: '203.0.113.42',
43
+ encrypted: false,
44
+ });
45
+ assert.equal(isRequestSecure(req), false);
46
+ });
47
+ });
48
+
49
+ test('isRequestSecure accepts x-forwarded-proto over trusted loopback proxy', () => {
50
+ withEnv({ APP_TRUST_PROXY: 'false', RATE_LIMIT_TRUST_PROXY: 'false' }, () => {
51
+ const req = buildReq({
52
+ forwardedProto: 'https',
53
+ remoteAddress: '127.0.0.1',
54
+ encrypted: false,
55
+ });
56
+ assert.equal(isRequestSecure(req), true);
57
+ });
58
+ });
59
+
60
+ test('isRequestSecure accepts x-forwarded-proto when trust proxy is enabled', () => {
61
+ withEnv({ APP_TRUST_PROXY: 'true', RATE_LIMIT_TRUST_PROXY: 'false' }, () => {
62
+ const req = buildReq({
63
+ forwardedProto: 'https',
64
+ remoteAddress: '198.51.100.5',
65
+ encrypted: false,
66
+ });
67
+ assert.equal(isRequestSecure(req), true);
68
+ });
69
+ });
70
+
71
+ test('isRequestSecure falls back to socket encryption without trusted forwarded proto', () => {
72
+ withEnv({ APP_TRUST_PROXY: 'false', RATE_LIMIT_TRUST_PROXY: 'false' }, () => {
73
+ const req = buildReq({
74
+ forwardedProto: 'http',
75
+ remoteAddress: '198.51.100.5',
76
+ encrypted: true,
77
+ });
78
+ assert.equal(isRequestSecure(req), true);
79
+ });
80
+ });
@@ -0,0 +1,180 @@
1
+ import http from 'node:http';
2
+
3
+ import logger from '#logger';
4
+ import { getMetricsServerConfig, isMetricsEnabled, recordHttpRequest, resolveRouteGroup } from '../../app/observability/metrics.js';
5
+ import { applyCachePolicy } from '../middleware/cachePolicy.js';
6
+ import { applySensitiveRouteRateLimit } from '../middleware/endpointRateLimit.js';
7
+ import { applySecurityHeaders } from '../middleware/securityHeaders.js';
8
+ import { getIndexRouteConfigs, routeRequest } from '../routes/indexRouter.js';
9
+ import { parseRequestUrl, normalizeRequestId } from './requestContext.js';
10
+
11
+ let server = null;
12
+ let serverStarted = false;
13
+
14
+ const sanitizePathForLogs = (pathname) => {
15
+ const rawPath = String(pathname || '').trim();
16
+ if (!rawPath) return null;
17
+
18
+ const marker = '/auth/password/recovery/session/';
19
+ const lower = rawPath.toLowerCase();
20
+ const markerIndex = lower.indexOf(marker);
21
+ if (markerIndex < 0) return rawPath;
22
+
23
+ const tokenStart = markerIndex + marker.length;
24
+ const suffix = rawPath.slice(tokenStart);
25
+ const nextSlashIndex = suffix.indexOf('/');
26
+ if (nextSlashIndex < 0) {
27
+ const rawSegment = String(suffix || '')
28
+ .trim()
29
+ .toLowerCase();
30
+ if (rawSegment === 'request' || rawSegment === 'verify') {
31
+ return rawPath;
32
+ }
33
+ return `${rawPath.slice(0, tokenStart)}[redacted]`;
34
+ }
35
+ return `${rawPath.slice(0, tokenStart)}[redacted]${suffix.slice(nextSlashIndex)}`;
36
+ };
37
+
38
+ export const startHttpServer = () => {
39
+ if (!isMetricsEnabled() || serverStarted) return;
40
+
41
+ const { host, port, path: metricsPath } = getMetricsServerConfig();
42
+
43
+ server = http.createServer(async (req, res) => {
44
+ const requestStartedAt = Date.now();
45
+ const requestId = normalizeRequestId(req.headers['x-request-id']);
46
+ res.setHeader('X-Request-Id', requestId);
47
+
48
+ const parsedUrl = parseRequestUrl(req, host, port);
49
+ const pathname = parsedUrl.pathname;
50
+
51
+ let routeConfigs = null;
52
+ try {
53
+ routeConfigs = await getIndexRouteConfigs();
54
+ } catch (error) {
55
+ logger.error('Erro ao carregar configuracao de rotas.', {
56
+ error: error?.message,
57
+ });
58
+ }
59
+
60
+ let routeGroup = resolveRouteGroup({
61
+ pathname,
62
+ metricsPath,
63
+ catalogConfig: routeConfigs?.stickerConfig || null,
64
+ userConfig: routeConfigs?.userConfig || null,
65
+ systemAdminConfig: routeConfigs?.systemAdminConfig || null,
66
+ });
67
+
68
+ res.once('finish', () => {
69
+ recordHttpRequest({
70
+ durationMs: Date.now() - requestStartedAt,
71
+ method: req.method,
72
+ statusCode: res.statusCode,
73
+ routeGroup,
74
+ });
75
+ });
76
+
77
+ try {
78
+ applySecurityHeaders(req, res);
79
+ applyCachePolicy(req, res, { pathname });
80
+ const allowedByRateLimit = await applySensitiveRouteRateLimit(req, res, { pathname });
81
+ if (!allowedByRateLimit) return;
82
+
83
+ await routeRequest(req, res, {
84
+ pathname,
85
+ url: parsedUrl,
86
+ metricsPath,
87
+ configs: routeConfigs,
88
+ });
89
+
90
+ routeGroup = resolveRouteGroup({
91
+ pathname,
92
+ metricsPath,
93
+ catalogConfig: routeConfigs?.stickerConfig || null,
94
+ userConfig: routeConfigs?.userConfig || null,
95
+ systemAdminConfig: routeConfigs?.systemAdminConfig || null,
96
+ });
97
+ } catch (error) {
98
+ logger.error('Falha ao processar request HTTP.', {
99
+ path: sanitizePathForLogs(pathname),
100
+ method: req.method,
101
+ error: error?.message,
102
+ });
103
+
104
+ if (!res.writableEnded) {
105
+ res.statusCode = 500;
106
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
107
+ res.end(JSON.stringify({ error: 'Internal Server Error' }));
108
+ }
109
+ }
110
+ });
111
+
112
+ server.listen(port, host, () => {
113
+ serverStarted = true;
114
+ logger.info('Servidor HTTP iniciado', {
115
+ host,
116
+ port,
117
+ metrics_path: metricsPath,
118
+ });
119
+
120
+ getIndexRouteConfigs()
121
+ .then(({ userConfig, systemAdminConfig, stickerConfig }) => {
122
+ if (userConfig?.webPath) {
123
+ logger.info('Rotas web de usuario habilitadas', {
124
+ web_path: userConfig.webPath,
125
+ api_base_path: userConfig.apiBasePath,
126
+ host,
127
+ port,
128
+ });
129
+ }
130
+
131
+ if (systemAdminConfig?.webPath) {
132
+ logger.info('Rotas system admin habilitadas', {
133
+ web_path: systemAdminConfig.webPath,
134
+ legacy_web_path: systemAdminConfig.legacyWebPath,
135
+ api_admin_base_path: systemAdminConfig.apiAdminBasePath,
136
+ host,
137
+ port,
138
+ });
139
+ }
140
+
141
+ if (stickerConfig?.enabled && stickerConfig?.webPath) {
142
+ logger.info('Catalogo web de sticker packs habilitado', {
143
+ web_path: stickerConfig.webPath,
144
+ api_base_path: stickerConfig.apiBasePath,
145
+ orphan_api_path: stickerConfig.orphanApiPath,
146
+ data_public_path: stickerConfig.dataPublicPath,
147
+ data_public_dir: stickerConfig.dataPublicDir,
148
+ host,
149
+ port,
150
+ });
151
+ }
152
+ })
153
+ .catch((error) => {
154
+ logger.warn('Nao foi possivel carregar configuracao das rotas na inicializacao.', {
155
+ error: error?.message,
156
+ });
157
+ });
158
+ });
159
+
160
+ server.on('error', (error) => {
161
+ logger.error('Falha ao iniciar servidor HTTP', { error: error?.message });
162
+ });
163
+ };
164
+
165
+ export const stopHttpServer = async () => {
166
+ if (!serverStarted || !server) return;
167
+
168
+ const current = server;
169
+ server = null;
170
+ serverStarted = false;
171
+ await new Promise((resolve, reject) => {
172
+ current.close((error) => {
173
+ if (error) {
174
+ reject(error);
175
+ return;
176
+ }
177
+ resolve();
178
+ });
179
+ });
180
+ };
@@ -0,0 +1,20 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { URL } from 'node:url';
3
+
4
+ export const normalizeRequestId = (value) => {
5
+ const token = String(value || '')
6
+ .trim()
7
+ .replace(/[^a-zA-Z0-9._:-]/g, '')
8
+ .slice(0, 120);
9
+ return token || randomUUID();
10
+ };
11
+
12
+ export const parseRequestUrl = (req, host, port) => {
13
+ const fallbackHost = `${host}:${port}`;
14
+ const requestHost = req.headers.host || fallbackHost;
15
+ try {
16
+ return new URL(req.url || '/', `http://${requestHost}`);
17
+ } catch {
18
+ return new URL(req.url || '/', 'http://localhost');
19
+ }
20
+ };