@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,225 @@
1
+ import logger from '#logger';
2
+ import { setQueueDepth } from '../../app/observability/metrics.js';
3
+ import { claimEmailOutboxTask, completeEmailOutboxTask, countEmailOutboxByStatus, failEmailOutboxTask } from './emailOutboxRepository.js';
4
+ import { isEmailTransportConfigured, sendEmailMessage } from './emailTransportService.js';
5
+
6
+ const parseEnvBool = (value, fallback) => {
7
+ if (value === undefined || value === null || value === '') return fallback;
8
+ const normalized = String(value).trim().toLowerCase();
9
+ if (['1', 'true', 'yes', 'y', 'on'].includes(normalized)) return true;
10
+ if (['0', 'false', 'no', 'n', 'off'].includes(normalized)) return false;
11
+ return fallback;
12
+ };
13
+
14
+ const clampInt = (value, fallback, min, max) => {
15
+ const numeric = Number(value);
16
+ if (!Number.isFinite(numeric)) return fallback;
17
+ return Math.max(min, Math.min(max, Math.floor(numeric)));
18
+ };
19
+
20
+ const clampNumber = (value, fallback, min, max) => {
21
+ const numeric = Number(value);
22
+ if (!Number.isFinite(numeric)) return fallback;
23
+ return Math.max(min, Math.min(max, numeric));
24
+ };
25
+
26
+ const EMAIL_AUTOMATION_ENABLED = parseEnvBool(process.env.EMAIL_AUTOMATION_ENABLED, true);
27
+ const EMAIL_AUTOMATION_WORKER_ENABLED = parseEnvBool(process.env.EMAIL_AUTOMATION_WORKER_ENABLED, true);
28
+ const EMAIL_AUTOMATION_POLL_INTERVAL_MS = clampInt(process.env.EMAIL_AUTOMATION_POLL_INTERVAL_MS, 12_000, 1_000, 300_000);
29
+ const EMAIL_AUTOMATION_IDLE_BACKOFF_MULTIPLIER = clampNumber(process.env.EMAIL_AUTOMATION_IDLE_BACKOFF_MULTIPLIER, 1.7, 1, 5);
30
+ const EMAIL_AUTOMATION_IDLE_MAX_POLL_INTERVAL_MS = clampInt(process.env.EMAIL_AUTOMATION_IDLE_MAX_POLL_INTERVAL_MS, Math.max(60_000, EMAIL_AUTOMATION_POLL_INTERVAL_MS * 8), 1_000, 900_000);
31
+ const EMAIL_AUTOMATION_IDLE_JITTER_PERCENT = clampInt(process.env.EMAIL_AUTOMATION_IDLE_JITTER_PERCENT, 12, 0, 60);
32
+ const EMAIL_AUTOMATION_MAX_PER_TICK = clampInt(process.env.EMAIL_AUTOMATION_MAX_PER_TICK, 3, 1, 20);
33
+ const EMAIL_AUTOMATION_RETRY_DELAY_SECONDS = clampInt(process.env.EMAIL_AUTOMATION_RETRY_DELAY_SECONDS, 120, 5, 86_400);
34
+
35
+ let started = false;
36
+ let stopping = false;
37
+ let inFlight = false;
38
+ let timerHandle = null;
39
+ let nextDelayMs = EMAIL_AUTOMATION_POLL_INTERVAL_MS;
40
+
41
+ const applyDelayJitter = (delayMs) => {
42
+ const baseDelay = Math.max(250, Math.floor(Number(delayMs) || 0));
43
+ if (EMAIL_AUTOMATION_IDLE_JITTER_PERCENT <= 0) return baseDelay;
44
+ const variation = (Math.random() * 2 - 1) * (EMAIL_AUTOMATION_IDLE_JITTER_PERCENT / 100);
45
+ return Math.max(250, Math.floor(baseDelay * (1 + variation)));
46
+ };
47
+
48
+ const refreshQueueDepthMetrics = async () => {
49
+ const [pending, processing, failed] = await Promise.all([countEmailOutboxByStatus('pending'), countEmailOutboxByStatus('processing'), countEmailOutboxByStatus('failed')]);
50
+ setQueueDepth('email_outbox_pending', pending);
51
+ setQueueDepth('email_outbox_processing', processing);
52
+ setQueueDepth('email_outbox_failed', failed);
53
+ };
54
+
55
+ const scheduleNextTick = (delayMs = EMAIL_AUTOMATION_POLL_INTERVAL_MS) => {
56
+ if (stopping || !started) return;
57
+ if (timerHandle) {
58
+ clearTimeout(timerHandle);
59
+ timerHandle = null;
60
+ }
61
+
62
+ timerHandle = setTimeout(() => {
63
+ timerHandle = null;
64
+ void runLoopOnce();
65
+ }, applyDelayJitter(delayMs));
66
+
67
+ if (typeof timerHandle?.unref === 'function') {
68
+ timerHandle.unref();
69
+ }
70
+ };
71
+
72
+ export const runEmailAutomationTick = async ({ maxPerTick = EMAIL_AUTOMATION_MAX_PER_TICK, retryDelaySeconds = EMAIL_AUTOMATION_RETRY_DELAY_SECONDS } = {}) => {
73
+ if (!EMAIL_AUTOMATION_ENABLED || !EMAIL_AUTOMATION_WORKER_ENABLED) {
74
+ return {
75
+ executed: false,
76
+ reason: 'disabled',
77
+ claimed: 0,
78
+ sent: 0,
79
+ failed: 0,
80
+ };
81
+ }
82
+
83
+ if (!isEmailTransportConfigured()) {
84
+ return {
85
+ executed: false,
86
+ reason: 'smtp_not_configured',
87
+ claimed: 0,
88
+ sent: 0,
89
+ failed: 0,
90
+ };
91
+ }
92
+
93
+ const safeMaxPerTick = clampInt(maxPerTick, EMAIL_AUTOMATION_MAX_PER_TICK, 1, 20);
94
+ const safeRetryDelay = clampInt(retryDelaySeconds, EMAIL_AUTOMATION_RETRY_DELAY_SECONDS, 5, 86_400);
95
+ const stats = {
96
+ executed: true,
97
+ reason: 'ok',
98
+ claimed: 0,
99
+ sent: 0,
100
+ failed: 0,
101
+ };
102
+
103
+ for (let index = 0; index < safeMaxPerTick; index += 1) {
104
+ const task = await claimEmailOutboxTask();
105
+ if (!task) break;
106
+
107
+ stats.claimed += 1;
108
+
109
+ try {
110
+ const delivery = await sendEmailMessage({
111
+ to: task.recipient_email,
112
+ subject: task.subject,
113
+ text: task.text_body,
114
+ html: task.html_body,
115
+ });
116
+
117
+ await completeEmailOutboxTask(task.id, {
118
+ providerMessageId: delivery?.messageId || '',
119
+ });
120
+
121
+ stats.sent += 1;
122
+ } catch (error) {
123
+ stats.failed += 1;
124
+ await failEmailOutboxTask(task.id, {
125
+ error: error?.message || 'email_delivery_failed',
126
+ retryDelaySeconds: safeRetryDelay,
127
+ });
128
+
129
+ logger.warn('Falha ao entregar e-mail da fila.', {
130
+ action: 'email_automation_delivery_failed',
131
+ task_id: task.id,
132
+ recipient_email: task.recipient_email,
133
+ attempts: task.attempts,
134
+ error: error?.message,
135
+ });
136
+ }
137
+ }
138
+
139
+ if (stats.claimed > 0) {
140
+ await refreshQueueDepthMetrics().catch(() => null);
141
+ }
142
+
143
+ return stats;
144
+ };
145
+
146
+ const runLoopOnce = async () => {
147
+ if (stopping || inFlight) return;
148
+ inFlight = true;
149
+ let tickStats = null;
150
+
151
+ try {
152
+ tickStats = await runEmailAutomationTick();
153
+ } catch (error) {
154
+ logger.error('Falha no runtime de automação de e-mail.', {
155
+ action: 'email_automation_runtime_tick_failed',
156
+ error: error?.message,
157
+ });
158
+ } finally {
159
+ inFlight = false;
160
+ }
161
+
162
+ if (stopping || !started) return;
163
+
164
+ const claimed = Number(tickStats?.claimed || 0);
165
+ if (claimed > 0) {
166
+ nextDelayMs = EMAIL_AUTOMATION_POLL_INTERVAL_MS;
167
+ } else {
168
+ nextDelayMs = Math.min(EMAIL_AUTOMATION_IDLE_MAX_POLL_INTERVAL_MS, Math.max(EMAIL_AUTOMATION_POLL_INTERVAL_MS, Math.floor(nextDelayMs * EMAIL_AUTOMATION_IDLE_BACKOFF_MULTIPLIER)));
169
+ }
170
+
171
+ scheduleNextTick(nextDelayMs);
172
+ };
173
+
174
+ export const startEmailAutomationRuntime = () => {
175
+ if (started) return;
176
+
177
+ if (!EMAIL_AUTOMATION_ENABLED || !EMAIL_AUTOMATION_WORKER_ENABLED) {
178
+ logger.info('Runtime de automação de e-mail desabilitado.', {
179
+ action: 'email_automation_runtime_disabled',
180
+ automation_enabled: EMAIL_AUTOMATION_ENABLED,
181
+ worker_enabled: EMAIL_AUTOMATION_WORKER_ENABLED,
182
+ });
183
+ return;
184
+ }
185
+
186
+ if (!isEmailTransportConfigured()) {
187
+ logger.warn('Runtime de automação de e-mail não iniciado: SMTP não configurado.', {
188
+ action: 'email_automation_runtime_smtp_not_configured',
189
+ });
190
+ return;
191
+ }
192
+
193
+ started = true;
194
+ stopping = false;
195
+ inFlight = false;
196
+ nextDelayMs = EMAIL_AUTOMATION_POLL_INTERVAL_MS;
197
+
198
+ logger.info('Runtime de automação de e-mail iniciado.', {
199
+ action: 'email_automation_runtime_started',
200
+ poll_interval_ms: EMAIL_AUTOMATION_POLL_INTERVAL_MS,
201
+ idle_backoff_multiplier: EMAIL_AUTOMATION_IDLE_BACKOFF_MULTIPLIER,
202
+ idle_max_poll_interval_ms: EMAIL_AUTOMATION_IDLE_MAX_POLL_INTERVAL_MS,
203
+ max_per_tick: EMAIL_AUTOMATION_MAX_PER_TICK,
204
+ retry_delay_seconds: EMAIL_AUTOMATION_RETRY_DELAY_SECONDS,
205
+ });
206
+
207
+ void runLoopOnce();
208
+ };
209
+
210
+ export const stopEmailAutomationRuntime = () => {
211
+ if (!started && !timerHandle) return;
212
+ stopping = true;
213
+ started = false;
214
+ if (timerHandle) {
215
+ clearTimeout(timerHandle);
216
+ timerHandle = null;
217
+ }
218
+
219
+ logger.info('Runtime de automação de e-mail encerrado.', {
220
+ action: 'email_automation_runtime_stopped',
221
+ });
222
+ };
223
+
224
+ export const isEmailAutomationRuntimeEnabled = () => EMAIL_AUTOMATION_ENABLED && EMAIL_AUTOMATION_WORKER_ENABLED;
225
+ export const isEmailAutomationRuntimeRunning = () => started && !stopping;
@@ -0,0 +1,125 @@
1
+ import { enqueueEmailOutbox, getEmailOutboxStatusSnapshot } from './emailOutboxRepository.js';
2
+ import { renderEmailTemplate } from './emailTemplateService.js';
3
+ import { getEmailTransportMetadata } from './emailTransportService.js';
4
+
5
+ const normalizeEmail = (value) =>
6
+ String(value || '')
7
+ .trim()
8
+ .toLowerCase()
9
+ .slice(0, 255);
10
+
11
+ const normalizeOptionalText = (value, maxLength = 500_000) => {
12
+ const normalized =
13
+ String(value || '')
14
+ .trim()
15
+ .slice(0, maxLength) || '';
16
+ return normalized || null;
17
+ };
18
+
19
+ const normalizeTemplateKey = (value) =>
20
+ String(value || '')
21
+ .trim()
22
+ .toLowerCase()
23
+ .replace(/[^a-z0-9_:-]/g, '')
24
+ .slice(0, 64);
25
+
26
+ const normalizePayloadObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});
27
+
28
+ const resolveEmailBodyFromPayload = ({ templateKey = '', templateData = {}, subject = '', text = '', html = '' } = {}) => {
29
+ const normalizedTemplateKey = normalizeTemplateKey(templateKey);
30
+ const normalizedTemplateData = normalizePayloadObject(templateData);
31
+
32
+ const renderedTemplate = normalizedTemplateKey ? renderEmailTemplate(normalizedTemplateKey, normalizedTemplateData) : null;
33
+
34
+ const normalizedSubject = normalizeOptionalText(subject, 180) || renderedTemplate?.subject || '';
35
+ const normalizedText = normalizeOptionalText(text, 120_000) || renderedTemplate?.text || null;
36
+ const normalizedHtml = normalizeOptionalText(html, 500_000) || renderedTemplate?.html || null;
37
+
38
+ if (!normalizedSubject) {
39
+ const error = new Error('Informe o assunto ou use um template válido.');
40
+ error.statusCode = 400;
41
+ throw error;
42
+ }
43
+
44
+ if (!normalizedText && !normalizedHtml) {
45
+ const error = new Error('Informe conteúdo de e-mail (text/html) ou use um template válido.');
46
+ error.statusCode = 400;
47
+ throw error;
48
+ }
49
+
50
+ return {
51
+ template_key: renderedTemplate?.template_key || normalizedTemplateKey || null,
52
+ template_payload: renderedTemplate ? normalizedTemplateData : {},
53
+ subject: normalizedSubject,
54
+ text_body: normalizedText,
55
+ html_body: normalizedHtml,
56
+ };
57
+ };
58
+
59
+ export const queueAutomatedEmail = async ({ to, name = '', templateKey = '', templateData = {}, subject = '', text = '', html = '', metadata = {}, priority = 50, scheduledAt = null, maxAttempts = 5, idempotencyKey = '' } = {}) => {
60
+ const normalizedEmail = normalizeEmail(to);
61
+ if (!normalizedEmail || !normalizedEmail.includes('@')) {
62
+ const error = new Error('Destinatário de e-mail inválido.');
63
+ error.statusCode = 400;
64
+ throw error;
65
+ }
66
+
67
+ const body = resolveEmailBodyFromPayload({
68
+ templateKey,
69
+ templateData,
70
+ subject,
71
+ text,
72
+ html,
73
+ });
74
+
75
+ const taskId = await enqueueEmailOutbox({
76
+ recipientEmail: normalizedEmail,
77
+ recipientName: normalizeOptionalText(name, 120),
78
+ subject: body.subject,
79
+ textBody: body.text_body,
80
+ htmlBody: body.html_body,
81
+ templateKey: body.template_key,
82
+ templatePayload: body.template_payload,
83
+ metadata: normalizePayloadObject(metadata),
84
+ priority,
85
+ scheduledAt,
86
+ maxAttempts,
87
+ idempotencyKey,
88
+ });
89
+
90
+ if (!taskId) {
91
+ const error = new Error('Não foi possível enfileirar o e-mail.');
92
+ error.statusCode = 500;
93
+ throw error;
94
+ }
95
+
96
+ return {
97
+ task_id: taskId,
98
+ recipient_email: normalizedEmail,
99
+ subject: body.subject,
100
+ template_key: body.template_key || null,
101
+ };
102
+ };
103
+
104
+ export const queueWelcomeEmail = async ({ to, name = '', loginUrl = '', redirectUrl = '', homeUrl = '', metadata = {}, idempotencyKey = '' } = {}) =>
105
+ queueAutomatedEmail({
106
+ to,
107
+ name,
108
+ templateKey: 'welcome',
109
+ templateData: {
110
+ name,
111
+ loginUrl,
112
+ redirectUrl,
113
+ homeUrl,
114
+ },
115
+ metadata,
116
+ idempotencyKey,
117
+ });
118
+
119
+ export const getEmailAutomationStatusSnapshot = async () => {
120
+ const queue = await getEmailOutboxStatusSnapshot();
121
+ return {
122
+ queue,
123
+ transport: getEmailTransportMetadata(),
124
+ };
125
+ };
@@ -0,0 +1,282 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import { executeQuery, TABLES } from '../../database/index.js';
4
+
5
+ const STATUS_VALUES = new Set(['pending', 'processing', 'sent', 'failed']);
6
+
7
+ const clampInt = (value, fallback, min, max) => {
8
+ const numeric = Number(value);
9
+ if (!Number.isFinite(numeric)) return fallback;
10
+ return Math.max(min, Math.min(max, Math.floor(numeric)));
11
+ };
12
+
13
+ const CLAIM_LOCK_TIMEOUT_SECONDS = clampInt(process.env.EMAIL_OUTBOX_LOCK_TIMEOUT_SECONDS, 15 * 60, 30, 24 * 60 * 60);
14
+
15
+ const normalizeStatus = (value) => {
16
+ const normalized = String(value || '')
17
+ .trim()
18
+ .toLowerCase();
19
+ return STATUS_VALUES.has(normalized) ? normalized : null;
20
+ };
21
+
22
+ const normalizeEmail = (value) =>
23
+ String(value || '')
24
+ .trim()
25
+ .toLowerCase()
26
+ .slice(0, 255);
27
+
28
+ const normalizeIdempotencyKey = (value) =>
29
+ String(value || '')
30
+ .trim()
31
+ .replace(/[^a-zA-Z0-9_:-]/g, '')
32
+ .slice(0, 180);
33
+
34
+ const normalizeTemplateKey = (value) =>
35
+ String(value || '')
36
+ .trim()
37
+ .toLowerCase()
38
+ .replace(/[^a-z0-9_:-]/g, '')
39
+ .slice(0, 64);
40
+
41
+ const normalizeSubject = (value) =>
42
+ String(value || '')
43
+ .trim()
44
+ .replace(/\s+/g, ' ')
45
+ .slice(0, 180);
46
+
47
+ const normalizeNullableText = (value, maxLength = 200_000) => {
48
+ const normalized =
49
+ String(value || '')
50
+ .trim()
51
+ .slice(0, maxLength) || '';
52
+ return normalized || null;
53
+ };
54
+
55
+ const parseJson = (value, fallback = null) => {
56
+ if (value === null || value === undefined) return fallback;
57
+ if (typeof value === 'object') return value;
58
+ if (Buffer.isBuffer(value)) {
59
+ try {
60
+ return JSON.parse(value.toString('utf8'));
61
+ } catch {
62
+ return fallback;
63
+ }
64
+ }
65
+ if (typeof value === 'string') {
66
+ try {
67
+ return JSON.parse(value);
68
+ } catch {
69
+ return fallback;
70
+ }
71
+ }
72
+ return fallback;
73
+ };
74
+
75
+ const normalizeRow = (row) => {
76
+ if (!row) return null;
77
+ return {
78
+ id: Number(row.id),
79
+ recipient_email: normalizeEmail(row.recipient_email),
80
+ recipient_name:
81
+ String(row.recipient_name || '')
82
+ .trim()
83
+ .slice(0, 120) || null,
84
+ subject: normalizeSubject(row.subject),
85
+ text_body: row.text_body || null,
86
+ html_body: row.html_body || null,
87
+ template_key: normalizeTemplateKey(row.template_key) || null,
88
+ template_payload: parseJson(row.template_payload, {}),
89
+ metadata: parseJson(row.metadata, {}),
90
+ status: normalizeStatus(row.status) || 'pending',
91
+ priority: Number(row.priority || 0),
92
+ idempotency_key: row.idempotency_key || null,
93
+ available_at: row.available_at || null,
94
+ attempts: Number(row.attempts || 0),
95
+ max_attempts: Number(row.max_attempts || 0),
96
+ worker_token: row.worker_token || null,
97
+ provider_message_id: row.provider_message_id || null,
98
+ last_error: row.last_error || null,
99
+ locked_at: row.locked_at || null,
100
+ sent_at: row.sent_at || null,
101
+ created_at: row.created_at || null,
102
+ updated_at: row.updated_at || null,
103
+ };
104
+ };
105
+
106
+ export async function enqueueEmailOutbox({ recipientEmail, recipientName = '', subject, textBody = null, htmlBody = null, templateKey = '', templatePayload = {}, metadata = {}, priority = 50, scheduledAt = null, maxAttempts = 5, idempotencyKey = '' } = {}, connection = null) {
107
+ const normalizedRecipientEmail = normalizeEmail(recipientEmail);
108
+ const normalizedSubject = normalizeSubject(subject);
109
+ const normalizedTextBody = normalizeNullableText(textBody, 120_000);
110
+ const normalizedHtmlBody = normalizeNullableText(htmlBody, 500_000);
111
+
112
+ if (!normalizedRecipientEmail || !normalizedRecipientEmail.includes('@')) return null;
113
+ if (!normalizedSubject) return null;
114
+ if (!normalizedTextBody && !normalizedHtmlBody) return null;
115
+
116
+ const normalizedRecipientName =
117
+ String(recipientName || '')
118
+ .trim()
119
+ .slice(0, 120) || null;
120
+ const normalizedTemplateKey = normalizeTemplateKey(templateKey) || null;
121
+ const normalizedTemplatePayload = templatePayload && typeof templatePayload === 'object' && !Array.isArray(templatePayload) ? templatePayload : {};
122
+ const normalizedMetadata = metadata && typeof metadata === 'object' && !Array.isArray(metadata) ? metadata : {};
123
+ const safePriority = clampInt(priority, 50, 1, 100);
124
+ const safeMaxAttempts = clampInt(maxAttempts, 5, 1, 20);
125
+ const safeScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
126
+ const scheduledValue = safeScheduledAt && Number.isFinite(safeScheduledAt.valueOf()) ? safeScheduledAt : null;
127
+ const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || null;
128
+
129
+ const result = await executeQuery(
130
+ `INSERT INTO ${TABLES.EMAIL_OUTBOX}
131
+ (recipient_email, recipient_name, subject, text_body, html_body, template_key, template_payload, metadata, status, priority, idempotency_key, available_at, attempts, max_attempts)
132
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, COALESCE(?, UTC_TIMESTAMP()), 0, ?)
133
+ ON DUPLICATE KEY UPDATE
134
+ id = LAST_INSERT_ID(id),
135
+ subject = IF(status IN ('pending', 'failed'), VALUES(subject), subject),
136
+ text_body = IF(status IN ('pending', 'failed'), VALUES(text_body), text_body),
137
+ html_body = IF(status IN ('pending', 'failed'), VALUES(html_body), html_body),
138
+ template_key = IF(status IN ('pending', 'failed'), VALUES(template_key), template_key),
139
+ template_payload = IF(status IN ('pending', 'failed'), VALUES(template_payload), template_payload),
140
+ metadata = IF(status IN ('pending', 'failed'), VALUES(metadata), metadata),
141
+ priority = GREATEST(priority, VALUES(priority)),
142
+ available_at = LEAST(available_at, VALUES(available_at)),
143
+ status = IF(status = 'failed' AND attempts < max_attempts, 'pending', status),
144
+ updated_at = UTC_TIMESTAMP()`,
145
+ [normalizedRecipientEmail, normalizedRecipientName, normalizedSubject, normalizedTextBody, normalizedHtmlBody, normalizedTemplateKey, JSON.stringify(normalizedTemplatePayload), JSON.stringify(normalizedMetadata), safePriority, normalizedIdempotencyKey, scheduledValue, safeMaxAttempts],
146
+ connection,
147
+ );
148
+
149
+ const insertedId = Number(result?.insertId || 0);
150
+ return Number.isFinite(insertedId) && insertedId > 0 ? insertedId : null;
151
+ }
152
+
153
+ export async function claimEmailOutboxTask({ allowRetryFailed = true } = {}, connection = null) {
154
+ const workerToken = randomUUID();
155
+ const statusClause = allowRetryFailed
156
+ ? `(status = 'pending'
157
+ OR (status = 'failed' AND attempts < max_attempts)
158
+ OR (status = 'processing' AND locked_at <= (UTC_TIMESTAMP() - INTERVAL ${CLAIM_LOCK_TIMEOUT_SECONDS} SECOND)))`
159
+ : `(status = 'pending'
160
+ OR (status = 'processing' AND locked_at <= (UTC_TIMESTAMP() - INTERVAL ${CLAIM_LOCK_TIMEOUT_SECONDS} SECOND)))`;
161
+
162
+ await executeQuery(
163
+ `UPDATE ${TABLES.EMAIL_OUTBOX}
164
+ SET status = 'processing',
165
+ worker_token = ?,
166
+ locked_at = UTC_TIMESTAMP(),
167
+ attempts = attempts + 1,
168
+ updated_at = UTC_TIMESTAMP()
169
+ WHERE id = (
170
+ SELECT id FROM (
171
+ SELECT id
172
+ FROM ${TABLES.EMAIL_OUTBOX}
173
+ WHERE ${statusClause}
174
+ AND available_at <= UTC_TIMESTAMP()
175
+ ORDER BY priority DESC, available_at ASC, id ASC
176
+ LIMIT 1
177
+ ) picked
178
+ )`,
179
+ [workerToken],
180
+ connection,
181
+ );
182
+
183
+ const rows = await executeQuery(
184
+ `SELECT *
185
+ FROM ${TABLES.EMAIL_OUTBOX}
186
+ WHERE worker_token = ?
187
+ AND status = 'processing'
188
+ ORDER BY id DESC
189
+ LIMIT 1`,
190
+ [workerToken],
191
+ connection,
192
+ );
193
+
194
+ return normalizeRow(rows?.[0] || null);
195
+ }
196
+
197
+ export async function completeEmailOutboxTask(taskId, { providerMessageId = '' } = {}, connection = null) {
198
+ if (!taskId) return false;
199
+ const normalizedProviderMessageId =
200
+ String(providerMessageId || '')
201
+ .trim()
202
+ .slice(0, 255) || null;
203
+
204
+ await executeQuery(
205
+ `UPDATE ${TABLES.EMAIL_OUTBOX}
206
+ SET status = 'sent',
207
+ provider_message_id = ?,
208
+ sent_at = UTC_TIMESTAMP(),
209
+ worker_token = NULL,
210
+ locked_at = NULL,
211
+ last_error = NULL,
212
+ updated_at = UTC_TIMESTAMP()
213
+ WHERE id = ?`,
214
+ [normalizedProviderMessageId, taskId],
215
+ connection,
216
+ );
217
+
218
+ return true;
219
+ }
220
+
221
+ export async function failEmailOutboxTask(taskId, { error = null, retryDelaySeconds = 0 } = {}, connection = null) {
222
+ if (!taskId) return false;
223
+
224
+ const safeDelay = clampInt(retryDelaySeconds, 0, 0, 86400 * 7);
225
+ const normalizedError =
226
+ String(error || '')
227
+ .trim()
228
+ .slice(0, 255) || null;
229
+
230
+ await executeQuery(
231
+ `UPDATE ${TABLES.EMAIL_OUTBOX}
232
+ SET status = IF(attempts >= max_attempts, 'failed', 'pending'),
233
+ worker_token = NULL,
234
+ locked_at = NULL,
235
+ last_error = ?,
236
+ available_at = IF(attempts >= max_attempts, available_at, UTC_TIMESTAMP() + INTERVAL ${safeDelay} SECOND),
237
+ updated_at = UTC_TIMESTAMP()
238
+ WHERE id = ?`,
239
+ [normalizedError, taskId],
240
+ connection,
241
+ );
242
+
243
+ return true;
244
+ }
245
+
246
+ export async function countEmailOutboxByStatus(status = 'pending', connection = null) {
247
+ const normalizedStatus = normalizeStatus(status);
248
+ if (!normalizedStatus) return 0;
249
+
250
+ const rows = await executeQuery(
251
+ `SELECT COUNT(*) AS total
252
+ FROM ${TABLES.EMAIL_OUTBOX}
253
+ WHERE status = ?`,
254
+ [normalizedStatus],
255
+ connection,
256
+ );
257
+
258
+ return Number(rows?.[0]?.total || 0);
259
+ }
260
+
261
+ export async function getEmailOutboxStatusSnapshot(connection = null) {
262
+ const rows = await executeQuery(
263
+ `SELECT
264
+ SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending,
265
+ SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) AS processing,
266
+ SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) AS sent,
267
+ SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed,
268
+ COUNT(*) AS total
269
+ FROM ${TABLES.EMAIL_OUTBOX}`,
270
+ [],
271
+ connection,
272
+ );
273
+
274
+ const row = rows?.[0] || {};
275
+ return {
276
+ pending: Number(row.pending || 0),
277
+ processing: Number(row.processing || 0),
278
+ sent: Number(row.sent || 0),
279
+ failed: Number(row.failed || 0),
280
+ total: Number(row.total || 0),
281
+ };
282
+ }