levix-bot 4.9.1 → 5.0.0

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 (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -0,0 +1,13 @@
1
+ const { AsyncLocalStorage } = require("node:async_hooks");
2
+
3
+ const scope = new AsyncLocalStorage();
4
+
5
+ function withCommand(command, fn) {
6
+ return scope.run(command, fn);
7
+ }
8
+
9
+ function currentCommand() {
10
+ return scope.getStore() || null;
11
+ }
12
+
13
+ module.exports = { withCommand, currentCommand };
@@ -1,14 +1,8 @@
1
- // A command's documentation, in the language the reader wants.
2
- //
3
- // `description` and `usage` on a command are either a plain string — one
4
- // language, shown as-is in both menus — or `{ en, ar }`. localize() picks the
5
- // requested language and falls back to the other one, so a command that ships
6
- // only one language still appears in both.
7
- //
8
- // Which language: `!help ar` / `!help en` say so explicitly. Otherwise it is
9
- // the language every other reply uses — see utils/i18n.cjs.
1
+ // Command documentation is stored in the generated catalog. Module-owned
2
+ // documentation takes precedence for commands added outside the catalog.
3
+ const catalog = require("../i18n/catalog.generated.cjs");
10
4
 
11
- const LANGS = ["en", "ar"];
5
+ const LANGS = ["en", "ar", "pt-BR", "es-419"];
12
6
 
13
7
  // Words accepted after !help to pick a language.
14
8
  const LANG_WORDS = new Map([
@@ -25,9 +19,19 @@ const LANG_WORDS = new Map([
25
19
  ["عربي", "ar"],
26
20
  ["عربى", "ar"],
27
21
  ["العربية", "ar"],
22
+ ["pt", "pt-BR"],
23
+ ["pt-br", "pt-BR"],
24
+ ["português", "pt-BR"],
25
+ ["portugues", "pt-BR"],
26
+ ["portuguese", "pt-BR"],
27
+ ["es", "es-419"],
28
+ ["es-419", "es-419"],
29
+ ["español", "es-419"],
30
+ ["espanol", "es-419"],
31
+ ["spanish", "es-419"],
28
32
  ]);
29
33
 
30
- /** "ar" | "en" for a word like `ar`, `english`, `عربي`; null otherwise. */
34
+ /** Resolve a language word after !help, or return null. */
31
35
  function parseLang(word) {
32
36
  return (
33
37
  LANG_WORDS.get(
@@ -38,21 +42,39 @@ function parseLang(word) {
38
42
  );
39
43
  }
40
44
 
41
- /** Pick `lang` out of a string or an `{ en, ar }` object. */
45
+ /** Pick a locale, then English, then Arabic. */
42
46
  function localize(value, lang = "en") {
43
47
  if (value == null) return "";
44
48
  if (typeof value === "string") return value;
45
49
  if (typeof value !== "object") return String(value);
46
50
  if (value[lang]) return value[lang];
47
- for (const other of LANGS) {
48
- if (value[other]) return value[other];
49
- }
50
- return "";
51
+ return value.en || value.ar || "";
52
+ }
53
+
54
+ function allLanguages(value) {
55
+ return Object.fromEntries(LANGS.map((lang) => [lang, localize(value, lang)]));
51
56
  }
52
57
 
53
- /** Both languages, for the dashboard (which follows its own UI language). */
54
- function bothLanguages(value) {
55
- return { en: localize(value, "en"), ar: localize(value, "ar") };
58
+ function attachCommandDocs(command, category = null) {
59
+ if (!command?.name) return command;
60
+ const key = category === "group" ? `group.${command.name}` : command.name;
61
+ for (const field of ["description", "usage"]) {
62
+ if (Object.hasOwn(command, field)) continue;
63
+ const messageKey = `commands.${key}.${field}`;
64
+ const english = catalog.messages.en?.[messageKey];
65
+ if (english === undefined) continue;
66
+ command[field] = Object.fromEntries(
67
+ LANGS.map((lang) => [lang, catalog.messages[lang]?.[messageKey] ?? english]),
68
+ );
69
+ }
70
+ return command;
56
71
  }
57
72
 
58
- module.exports = { LANGS, parseLang, localize, bothLanguages };
73
+ module.exports = {
74
+ LANGS,
75
+ parseLang,
76
+ localize,
77
+ allLanguages,
78
+ bothLanguages: allLanguages,
79
+ attachCommandDocs,
80
+ };
@@ -0,0 +1,56 @@
1
+ const { fetch: undiciFetch, getGlobalDispatcher } = require("undici");
2
+ const { t } = require("./i18n.cjs");
3
+
4
+ // Custom Gemini gateways use a 20 MiB JSON body limit and a 15 MiB
5
+ // aggregate decoded-media limit. Google keeps the SDK's own transport.
6
+ const JSON_LIMIT = 20 * 1024 * 1024;
7
+
8
+ function tooLarge() {
9
+ const error = new Error(t("bot.ai.gemini.requestTooLarge"));
10
+ error.code = "GEMINI_REQUEST_TOO_LARGE";
11
+ return error;
12
+ }
13
+
14
+ function assertGeminiRequestBudget(body) {
15
+ // The SDK has already serialized the complete wire payload: count it as-is,
16
+ // including UTF-8, escaping, tools, system instruction and every history turn.
17
+ // This also enforces the gateway's aggregate 15 MiB decoded-media limit:
18
+ // valid Base64 needs 4 bytes per 3 decoded bytes (plus padding), so 15 MiB
19
+ // already fills all 20 MiB before the JSON envelope. Summing across parts or
20
+ // history cannot evade that bound. No parsing, decoding, copying or second
21
+ // serialization of large media strings is necessary. Invalid Base64 remains
22
+ // the endpoint's validation responsibility, as before.
23
+ if (Buffer.byteLength(body, "utf8") > JSON_LIMIT) throw tooLarge();
24
+ }
25
+
26
+ // A custom fetch disables the SDK's no-timeout dispatcher. Preserve that
27
+ // behavior while leaving its AbortSignal/request timeout in charge.
28
+ const dispatcher = {
29
+ dispatch(options, handler) {
30
+ return getGlobalDispatcher().dispatch(
31
+ { ...options, headersTimeout: 0, bodyTimeout: 0 },
32
+ handler,
33
+ );
34
+ },
35
+ };
36
+
37
+ async function budgetedFetch(url, init) {
38
+ const path = new URL(url).pathname;
39
+ if (init?.method === "POST" && /:(?:generateContent|streamGenerateContent)$/.test(path)) {
40
+ assertGeminiRequestBudget(init.body);
41
+ }
42
+ // Uploads, polling and downloads keep their existing behavior, including the
43
+ // missing Files API response that triggers geminiMediaPart's inline fallback.
44
+ // Node's built-in fetch uses a different dispatcher handler protocol.
45
+ // Keep fetch and dispatcher on the same installed Undici version.
46
+ return undiciFetch(url, { ...init, dispatcher });
47
+ }
48
+
49
+ function geminiHttpOptions(baseUrl) {
50
+ if (!baseUrl || new URL(baseUrl).hostname === "generativelanguage.googleapis.com") {
51
+ return { baseUrl };
52
+ }
53
+ return { baseUrl, fetch: budgetedFetch };
54
+ }
55
+
56
+ module.exports = { geminiHttpOptions, assertGeminiRequestBudget };
@@ -71,10 +71,35 @@ function baseMimeType(mime, kind = mediaKind(mime)) {
71
71
  * `downloadType` picks the decryption keys, so it has to follow the message
72
72
  * type (an image sent as a document is a "document"), not the MIME type.
73
73
  */
74
- async function downloadMedia(downloadContentFromMessage, mediaMessage, downloadType) {
75
- const stream = await downloadContentFromMessage(mediaMessage, downloadType);
74
+ async function downloadMedia(
75
+ downloadContentFromMessage,
76
+ mediaMessage,
77
+ downloadType,
78
+ { maxBytes = 64 * 1024 * 1024, signal } = {},
79
+ ) {
80
+ signal?.throwIfAborted();
81
+ if (Number(mediaMessage?.fileLength || 0) > maxBytes) throw new Error("MEDIA_TOO_LARGE");
82
+ const stream = await downloadContentFromMessage(mediaMessage, downloadType, {
83
+ options: { signal },
84
+ });
76
85
  const chunks = [];
77
- for await (const chunk of stream) chunks.push(chunk);
86
+ let size = 0;
87
+ const abort = () => stream.destroy?.(new Error("MEDIA_TIMEOUT"));
88
+ signal?.addEventListener("abort", abort, { once: true });
89
+ try {
90
+ signal?.throwIfAborted();
91
+ for await (const chunk of stream) {
92
+ signal?.throwIfAborted();
93
+ size += chunk.length;
94
+ if (size > maxBytes) throw new Error("MEDIA_TOO_LARGE");
95
+ chunks.push(chunk);
96
+ }
97
+ } catch (error) {
98
+ stream.destroy?.();
99
+ throw error;
100
+ } finally {
101
+ signal?.removeEventListener("abort", abort);
102
+ }
78
103
  const buffer = Buffer.concat(chunks);
79
104
  if (!buffer.length) throw new Error("Empty media buffer");
80
105
  return buffer;
@@ -8,13 +8,26 @@
8
8
  // Now the hot path reads the cache and only the first caller after a miss
9
9
  // pays for one query, which is then shared by everyone.
10
10
  //
11
- // The cache is populated from three places:
11
+ // The cache is populated from four places:
12
12
  // * `groupFetchAllParticipating()` on connection open (see
13
13
  // src/core/connection.js — itself TTL-gated to avoid full rosters on every
14
14
  // reconnect),
15
- // * pushed `groups.upsert` / `groups.update` events (src/core/events.js),
15
+ // * pushed `groups.upsert` and full `groups.update` events,
16
+ // * a shared refresh after `group-participants.update`,
16
17
  // * the write-back in resolveGroupMetadata() below.
17
18
  //
19
+ // A roster event marks the entry stale before any await. The send hook
20
+ // (groupMetadataForSend) refuses a stale roster. getCached still returns the
21
+ // last known entry so the Reply Router can check membership during a refresh.
22
+ // A failed refresh keeps that entry. It does not delete it.
23
+ //
24
+ // A bulk answer (cacheAllGroups) and a full roster whose request start is
25
+ // unknown (groups.upsert, groups.update with participants) must not overwrite
26
+ // a group that had a roster event after that answer was requested. Those
27
+ // paths use captureRosterCursor / storeBulkGroupMetadata and
28
+ // storeUnsolicitedFullRoster. storeFullGroupMetadata itself stays the
29
+ // "this roster is current" writer.
30
+ //
18
31
  // CommonJS on purpose: the consumers are the CJS command files and the ESM
19
32
  // handlers/ middleware, and this module must be loadable from both.
20
33
 
@@ -22,7 +35,7 @@ const NodeCache = require("node-cache");
22
35
 
23
36
  // Same values the old src/config/constants.js CACHE_CONFIG had (1h entries,
24
37
  // swept every 5m). constants.js is ESM and this module must be CJS, so the
25
- // literals live here now.
38
+ // literals live here now. The sweep timer is unref'd by node-cache.
26
39
  const CACHE_CONFIG = {
27
40
  stdTTL: 60 * 60, // 1 hour
28
41
  checkperiod: 60 * 5, // 5 minutes
@@ -30,45 +43,386 @@ const CACHE_CONFIG = {
30
43
 
31
44
  const cache = new NodeCache(CACHE_CONFIG);
32
45
 
46
+ // jid -> { gen, stale, inflight, again }. Only stale or in-flight groups stay
47
+ // here. A fresh idle entry does not, so the map tracks refreshes, not the cache.
48
+ const state = new Map();
49
+
50
+ // Follow one coalesced refetch, then stop. A burst schedules at most one more
51
+ // fetch; this cap only bounds a pathological chain of events across fetches.
52
+ const MAX_FETCH_CHAIN = 8;
53
+
54
+ // Unknown-start full rosters are stored only when this group had no roster
55
+ // event in this window. Baileys can deliver that payload long after its query:
56
+ // rc14 times the query out at 60s and the event buffer can hold the update
57
+ // about 30s more. Records stay at least this long, so the gate and the prune
58
+ // cannot drift. No timer: prune runs when an event is recorded, when a bulk
59
+ // cursor is captured, and on flush.
60
+ const ROSTER_EVENT_WINDOW_MS = 10 * 60 * 1000;
61
+
62
+ // Monotonic count of roster events. A bulk fetch captures the value before
63
+ // its request and stores a group only when that group is still at or below it.
64
+ let rosterEventSeq = 0;
65
+ // Bumped on flush so an in-flight bulk answer cannot refill a cleared cache.
66
+ let rosterEpoch = 0;
67
+ // jid -> { seq, at }. Survives a finished refresh so a late bulk answer still
68
+ // sees the event. Separate from `state`, which only tracks stale fetches.
69
+ const rosterEvents = new Map();
70
+ // Unlike refresh state and event retention, these versions survive cache expiry.
71
+ // A caller may use its message-time roster only until newer information exists.
72
+ const rosterVersions = new Map();
73
+
74
+ function bumpRosterVersion(jid) {
75
+ if (isGroupJid(jid)) rosterVersions.set(jid, (rosterVersions.get(jid) || 0) + 1);
76
+ }
77
+
78
+ /** Read-only marker for writes, deletions, roster events and cache flushes. */
79
+ function getRosterVersion(jid) {
80
+ return `${rosterEpoch}:${rosterVersions.get(jid) || 0}`;
81
+ }
82
+
33
83
  function isGroupJid(jid) {
34
84
  return String(jid || "").endsWith("@g.us");
35
85
  }
36
86
 
87
+ function ensureState(jid) {
88
+ let entry = state.get(jid);
89
+ if (!entry) {
90
+ entry = { gen: 0, stale: false, inflight: null, again: false };
91
+ state.set(jid, entry);
92
+ }
93
+ return entry;
94
+ }
95
+
96
+ function freshEntry(jid) {
97
+ const entry = cache.get(jid);
98
+ if (!entry || !Array.isArray(entry.participants)) return undefined;
99
+ if (state.get(jid)?.stale) return undefined;
100
+ return entry;
101
+ }
102
+
103
+ /** Last known metadata, fresh or stale. The Reply Router depends on this. */
37
104
  function getCached(jid) {
38
105
  return cache.get(jid);
39
106
  }
40
107
 
41
- function setCached(jid, metadata) {
42
- if (isGroupJid(jid) && metadata) cache.set(jid, metadata);
108
+ function remainingTtlSeconds(jid) {
109
+ const expiresAt = cache.getTtl(jid);
110
+ if (expiresAt == null) return null;
111
+ if (expiresAt === 0) return 0;
112
+ if (!Number.isFinite(expiresAt)) return null;
113
+ const seconds = (expiresAt - Date.now()) / 1000;
114
+ if (seconds <= 0) return null;
115
+ return seconds;
43
116
  }
44
117
 
45
- function flushAll() {
46
- cache.flushAll();
118
+ function dropIdleState(jid) {
119
+ const entry = state.get(jid);
120
+ if (!entry || entry.inflight) return;
121
+ state.delete(jid);
47
122
  }
48
123
 
49
- function keys() {
50
- return cache.keys();
124
+ // Unlink and backup activation call NodeCache.flushAll() directly
125
+ // (session.js, connection.js). Bump gen first so an in-flight answer cannot
126
+ // write the roster back after the cache was cleared.
127
+ function dropAllRosterState() {
128
+ rosterEpoch += 1;
129
+ rosterVersions.clear();
130
+ rosterEvents.clear();
131
+ for (const entry of state.values()) {
132
+ entry.gen += 1;
133
+ entry.again = false;
134
+ entry.stale = false;
135
+ entry.inflight = null;
136
+ }
137
+ state.clear();
138
+ }
139
+
140
+ function pruneRosterEvents(now = Date.now()) {
141
+ for (const [jid, record] of rosterEvents) {
142
+ if (!record || now - record.at > ROSTER_EVENT_WINDOW_MS) rosterEvents.delete(jid);
143
+ }
144
+ }
145
+
146
+ function noteRosterEvent(jid, now = Date.now()) {
147
+ bumpRosterVersion(jid);
148
+ rosterEventSeq += 1;
149
+ rosterEvents.set(jid, { seq: rosterEventSeq, at: now });
150
+ pruneRosterEvents(now);
151
+ }
152
+
153
+ function hadRosterEventSince(jid, seq) {
154
+ const record = rosterEvents.get(jid);
155
+ return Boolean(record && record.seq > seq);
156
+ }
157
+
158
+ function hadRosterEventWithin(jid, withinMs, now = Date.now()) {
159
+ const record = rosterEvents.get(jid);
160
+ return Boolean(record && now - record.at < withinMs);
51
161
  }
52
162
 
53
163
  /**
54
- * Group metadata, cache-first. A cache hit costs nothing; a miss makes ONE
55
- * live query and writes the answer back so concurrent and later readers share
56
- * it. A failing live query resolves null without caching anything, so the
57
- * next caller retries — correctness beats request avoidance.
164
+ * Sequence and flush epoch at the moment a bulk roster request starts.
165
+ * `now` is only for pruning; production passes the clock cacheAllGroups uses.
58
166
  */
59
- async function resolveGroupMetadata(sock, jid) {
60
- if (!isGroupJid(jid)) return null;
167
+ function captureRosterCursor(now = Date.now()) {
168
+ pruneRosterEvents(now);
169
+ return { seq: rosterEventSeq, epoch: rosterEpoch };
170
+ }
171
+
172
+ cache.on("set", (key) => bumpRosterVersion(key));
173
+ cache.on("del", (key) => {
174
+ bumpRosterVersion(key);
175
+ dropIdleState(key);
176
+ });
177
+ cache.on("expired", (key) => {
178
+ bumpRosterVersion(key);
179
+ dropIdleState(key);
180
+ });
181
+ cache.on("flush", () => dropAllRosterState());
182
+
183
+ /**
184
+ * Store a full roster. Bumps the generation and clears stale. An in-flight
185
+ * fetch that started earlier can no longer write over this answer.
186
+ */
187
+ function storeFullGroupMetadata(jid, metadata) {
188
+ if (!isGroupJid(jid) || !metadata || !Array.isArray(metadata.participants)) return null;
189
+ const entry = ensureState(jid);
190
+ entry.gen += 1;
191
+ entry.stale = false;
192
+ entry.again = false;
193
+ cache.set(jid, metadata);
194
+ if (!entry.inflight) state.delete(jid);
195
+ return metadata;
196
+ }
197
+
198
+ /**
199
+ * Merge a partial groups.update into an existing entry. Keeps the remaining
200
+ * TTL. Does not create an entry, does not bump the generation, and does not
201
+ * clear stale.
202
+ */
203
+ function mergePartialGroupMetadata(jid, patch) {
204
+ if (!isGroupJid(jid) || !patch || typeof patch !== "object") return null;
205
+ if (!cache.has(jid)) return null;
206
+ const current = cache.get(jid);
207
+ if (!current || typeof current !== "object") return null;
208
+ const ttl = remainingTtlSeconds(jid);
209
+ if (ttl == null) return null;
210
+ const next = { ...current, ...patch };
211
+ cache.set(jid, next, ttl);
212
+ return next;
213
+ }
214
+
215
+ function setCached(jid, metadata) {
216
+ if (!isGroupJid(jid) || !metadata) return;
217
+ if (Array.isArray(metadata.participants)) {
218
+ storeFullGroupMetadata(jid, metadata);
219
+ return;
220
+ }
221
+ cache.set(jid, metadata);
222
+ }
223
+
224
+ /**
225
+ * Store one group from a bulk fetch that captured `cursor` before the request.
226
+ * A later roster event, an open refresh, or a flush wins. The bulk answer is
227
+ * left unused for that group so it cannot mark an older roster fresh.
228
+ */
229
+ function storeBulkGroupMetadata(jid, metadata, cursor) {
230
+ if (!cursor || cursor.epoch !== rosterEpoch) return null;
231
+ const entry = state.get(jid);
232
+ if (entry?.stale || entry?.inflight) return null;
233
+ if (hadRosterEventSince(jid, cursor.seq)) return null;
234
+ return storeFullGroupMetadata(jid, metadata);
235
+ }
61
236
 
62
- const hit = cache.get(jid);
63
- if (hit) return hit;
237
+ /**
238
+ * Full roster whose request started at an unknown time (groups.upsert, or
239
+ * groups.update that carries participants). Store it only when this group had
240
+ * no roster event in the last 10 minutes. Otherwise leave any in-flight
241
+ * refresh alone, or start one, so a live groupMetadata answer decides.
242
+ */
243
+ function storeUnsolicitedFullRoster(sock, jid, metadata, now = Date.now()) {
244
+ if (!isGroupJid(jid) || !metadata || !Array.isArray(metadata.participants)) return null;
245
+ pruneRosterEvents(now);
246
+ const entry = state.get(jid);
247
+ const quiet =
248
+ !entry?.stale && !entry?.inflight && !hadRosterEventWithin(jid, ROSTER_EVENT_WINDOW_MS, now);
249
+ if (quiet) return storeFullGroupMetadata(jid, metadata);
250
+ if (!entry?.inflight && canFetch(sock)) beginRosterRefresh(sock, jid);
251
+ return null;
252
+ }
253
+
254
+ function fetchRoster(sock, jid, entry) {
255
+ const gen = entry.gen;
256
+ let finish;
257
+ const inflight = new Promise((resolve) => {
258
+ finish = resolve;
259
+ });
260
+ // Set before groupMetadata so a roster event inside that call coalesces.
261
+ entry.inflight = inflight;
64
262
 
263
+ let pending;
65
264
  try {
66
- const live = await sock.groupMetadata(jid);
67
- if (live) setCached(jid, live);
68
- return live;
69
- } catch {
265
+ pending = sock.groupMetadata(jid);
266
+ } catch (error) {
267
+ pending = Promise.reject(error);
268
+ }
269
+
270
+ Promise.resolve(pending)
271
+ .then(
272
+ (live) => {
273
+ const current = entry.gen === gen;
274
+ if (current && live && Array.isArray(live.participants)) {
275
+ cache.set(jid, live);
276
+ entry.stale = false;
277
+ }
278
+ return { current, failed: false, live };
279
+ },
280
+ () => ({ current: entry.gen === gen, failed: true, live: undefined }),
281
+ )
282
+ .then((result) => {
283
+ try {
284
+ if (entry.inflight !== inflight) return;
285
+ if (entry.again) {
286
+ entry.again = false;
287
+ fetchRoster(sock, jid, entry);
288
+ return;
289
+ }
290
+ entry.inflight = null;
291
+ // A failed refresh keeps the last entry and stays stale. Drop state only
292
+ // when nothing is left to hide, or the entry is fresh and idle.
293
+ if (!cache.has(jid) || !entry.stale) state.delete(jid);
294
+ } finally {
295
+ finish(result);
296
+ }
297
+ });
298
+
299
+ return inflight;
300
+ }
301
+
302
+ function canFetch(sock) {
303
+ return Boolean(sock && typeof sock.groupMetadata === "function");
304
+ }
305
+
306
+ /**
307
+ * Mark the roster stale and start or coalesce one shared groupMetadata fetch.
308
+ * Does not record a roster event. markRosterChanged does that first.
309
+ * A second call while a fetch is open bumps gen so the older answer is dropped
310
+ * and one follow-up runs. storeUnsolicitedFullRoster does not call this while
311
+ * a fetch is already open, so a late full roster cannot discard that refresh.
312
+ */
313
+ function beginRosterRefresh(sock, jid) {
314
+ if (!isGroupJid(jid)) return null;
315
+ const entry = ensureState(jid);
316
+ entry.gen += 1;
317
+ entry.stale = true;
318
+ if (entry.inflight) {
319
+ entry.again = true;
320
+ return entry.inflight;
321
+ }
322
+ if (!canFetch(sock)) {
323
+ if (!cache.has(jid)) state.delete(jid);
70
324
  return null;
71
325
  }
326
+ return fetchRoster(sock, jid, entry);
327
+ }
328
+
329
+ /**
330
+ * Roster event. Records the event and sets stale synchronously, before any
331
+ * await, then starts or coalesces one shared groupMetadata fetch.
332
+ */
333
+ function markRosterChanged(sock, jid) {
334
+ if (!isGroupJid(jid)) return null;
335
+ noteRosterEvent(jid);
336
+ return beginRosterRefresh(sock, jid);
337
+ }
338
+
339
+ async function drainFetches(sock, jid) {
340
+ const entry = state.get(jid) || ensureState(jid);
341
+ if (!entry.inflight) fetchRoster(sock, jid, entry);
342
+ let last;
343
+ for (let i = 0; i < MAX_FETCH_CHAIN; i += 1) {
344
+ const current = state.get(jid);
345
+ if (!current?.inflight) break;
346
+ last = await current.inflight;
347
+ }
348
+ return last;
349
+ }
350
+
351
+ function acceptedLive(jid, result) {
352
+ return Boolean(
353
+ result && result.current && !result.failed && result.live && !state.get(jid)?.stale,
354
+ );
355
+ }
356
+
357
+ /** Live-only authorization read. Joins an open fetch; never falls back to cache. */
358
+ async function readLiveGroupMetadata(sock, jid) {
359
+ if (!isGroupJid(jid) || !canFetch(sock)) return null;
360
+ const last = await drainFetches(sock, jid);
361
+ if (acceptedLive(jid, last) && Array.isArray(last.live.participants)) return last.live;
362
+ return null;
363
+ }
364
+
365
+ /**
366
+ * Baileys send-path hook. A fresh roster, or the shared fetch's answer.
367
+ * Never a stale roster. Undefined on failure so Baileys queries itself.
368
+ */
369
+ async function groupMetadataForSend(sock, jid) {
370
+ if (!isGroupJid(jid)) return undefined;
371
+ const ready = freshEntry(jid);
372
+ if (ready) return ready;
373
+ if (!canFetch(sock)) return undefined;
374
+ const last = await drainFetches(sock, jid);
375
+ const after = freshEntry(jid);
376
+ if (after) return after;
377
+ if (acceptedLive(jid, last) && Array.isArray(last.live.participants)) return last.live;
378
+ return undefined;
379
+ }
380
+
381
+ /**
382
+ * Group metadata, cache-first. A fresh hit costs nothing. A miss or a stale
383
+ * entry joins the shared fetch. A failing fetch returns the last known entry
384
+ * (stale) or null when there is none.
385
+ *
386
+ * `{ fresh: true }` is the authorization read. It returns a fresh cache hit
387
+ * or a live answer, and null when the only roster left is a stale one.
388
+ * Display, moderation protection and the Reply Router omit the option.
389
+ */
390
+ async function resolveGroupMetadata(sock, jid, options) {
391
+ if (!isGroupJid(jid)) return null;
392
+ const fresh = Boolean(options && options.fresh);
393
+ const ready = freshEntry(jid);
394
+ if (ready) return ready;
395
+ let last;
396
+ if (canFetch(sock)) {
397
+ try {
398
+ last = await drainFetches(sock, jid);
399
+ } catch {
400
+ last = undefined;
401
+ }
402
+ }
403
+ const after = freshEntry(jid);
404
+ if (after) return after;
405
+ // A live answer with no participants array is not stored. Callers that
406
+ // already accept that shape (the low-data retry) still receive it.
407
+ if (acceptedLive(jid, last)) return last.live;
408
+ if (fresh) return null;
409
+ return cache.get(jid) || null;
410
+ }
411
+
412
+ function flushAll() {
413
+ cache.flushAll();
414
+ }
415
+
416
+ function keys() {
417
+ return cache.keys();
418
+ }
419
+
420
+ function isRosterStale(jid) {
421
+ return Boolean(state.get(jid)?.stale);
422
+ }
423
+
424
+ function rosterStateSize() {
425
+ return state.size;
72
426
  }
73
427
 
74
428
  module.exports = {
@@ -76,8 +430,19 @@ module.exports = {
76
430
  CACHE_CONFIG,
77
431
  isGroupJid,
78
432
  getCached,
433
+ getRosterVersion,
79
434
  setCached,
80
435
  flushAll,
81
436
  keys,
82
437
  resolveGroupMetadata,
438
+ readLiveGroupMetadata,
439
+ groupMetadataForSend,
440
+ storeFullGroupMetadata,
441
+ mergePartialGroupMetadata,
442
+ captureRosterCursor,
443
+ storeBulkGroupMetadata,
444
+ storeUnsolicitedFullRoster,
445
+ markRosterChanged,
446
+ isRosterStale,
447
+ rosterStateSize,
83
448
  };