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
@@ -16,21 +16,60 @@ try {
16
16
  };
17
17
  }
18
18
 
19
+ const MISSING = Symbol("missing");
20
+
21
+ function serialize(value) {
22
+ return JSON.stringify(value, BufferJSON.replacer);
23
+ }
24
+
25
+ function deserialize(text) {
26
+ return JSON.parse(text, BufferJSON.reviver);
27
+ }
28
+
29
+ // `value == null` is a delete. Anything else is BufferJSON text. Stringify
30
+ // every entry before the first mutation so a later encode failure leaves
31
+ // the batch untouched.
32
+ function encodeEntry(entry) {
33
+ if (entry == null || typeof entry.key !== "string") {
34
+ throw new TypeError("auth entry needs a string key");
35
+ }
36
+ if (entry.value == null) return { key: entry.key, delete: true };
37
+ return { key: entry.key, text: serialize(entry.value) };
38
+ }
39
+
19
40
  function memoryFactory() {
20
41
  const map = new Map();
21
42
 
22
43
  return {
23
44
  async writeData(key, value) {
24
- map.set(key, JSON.stringify(value, BufferJSON.replacer));
45
+ map.set(key, serialize(value));
25
46
  },
26
47
  async readData(key) {
27
- const v = map.get(key);
28
- if (!v) return null;
29
- return JSON.parse(v, BufferJSON.reviver);
48
+ if (!map.has(key)) return null;
49
+ const text = map.get(key);
50
+ if (text == null) return null;
51
+ return deserialize(text);
30
52
  },
31
53
  async removeData(key) {
32
54
  map.delete(key);
33
55
  },
56
+ async apply(entries) {
57
+ const ops = entries.map((entry) => encodeEntry(entry));
58
+ const prior = new Map();
59
+ try {
60
+ for (const op of ops) {
61
+ if (!prior.has(op.key)) prior.set(op.key, map.has(op.key) ? map.get(op.key) : MISSING);
62
+ if (op.delete) map.delete(op.key);
63
+ else map.set(op.key, op.text);
64
+ }
65
+ } catch (error) {
66
+ for (const [key, value] of prior) {
67
+ if (value === MISSING) map.delete(key);
68
+ else map.set(key, value);
69
+ }
70
+ throw error;
71
+ }
72
+ },
34
73
  async clearAll() {
35
74
  map.clear();
36
75
  },
@@ -46,16 +85,24 @@ function memoryFactory() {
46
85
  function sqliteFactory() {
47
86
  return {
48
87
  async writeData(key, value) {
49
- store.authWrite(key, JSON.stringify(value, BufferJSON.replacer));
88
+ store.authWrite(key, serialize(value));
50
89
  },
51
90
  async readData(key) {
52
91
  const text = store.authRead(key);
53
- if (text === null || text === undefined) return null;
54
- return JSON.parse(text, BufferJSON.reviver);
92
+ if (text == null) return null;
93
+ return deserialize(text);
55
94
  },
56
95
  async removeData(key) {
57
96
  store.authRemove(key);
58
97
  },
98
+ async apply(entries) {
99
+ store.authApply(
100
+ entries.map((entry) => {
101
+ const op = encodeEntry(entry);
102
+ return op.delete ? { key: op.key, value: null } : { key: op.key, value: op.text };
103
+ }),
104
+ );
105
+ },
59
106
  async clearAll() {
60
107
  store.authClearAll();
61
108
  },
@@ -6,12 +6,53 @@ const require = createRequire(import.meta.url);
6
6
  const { createAuthStorage } = require("./auth-storage.cjs");
7
7
  const logger = require("../utils/logger.cjs");
8
8
 
9
+ export const AUTH_STORE_FENCED = "AUTH_STORE_FENCED";
10
+
11
+ function fencedError() {
12
+ const err = new Error("Auth store is fenced");
13
+ err.code = AUTH_STORE_FENCED;
14
+ return err;
15
+ }
16
+
17
+ // Baileys' typed shape is `{ [type]: { [id]: value } }`. The untyped shape is
18
+ // a flat id → value map left over from older sessions; the key names stay.
19
+ function collectKeyEntries(data) {
20
+ const entries = [];
21
+ const topKeys = Object.keys(data);
22
+ const looksLikeTyped = topKeys.some((key) => typeof data[key] === "object" && data[key] !== null);
23
+
24
+ if (looksLikeTyped) {
25
+ for (const type of topKeys) {
26
+ const typed = data[type];
27
+ if (typeof typed !== "object" || typed === null) continue;
28
+ for (const id of Object.keys(typed)) {
29
+ entries.push({ key: `${type}-${id}`, value: typed[id] });
30
+ }
31
+ }
32
+ return entries;
33
+ }
34
+
35
+ for (const id of topKeys) {
36
+ let keyName = id;
37
+ const base64Id = id.length > 20 && /^[A-Za-z0-9+/=]+$/.test(id);
38
+ if (id.includes("@")) keyName = `session-${id}`;
39
+ else if (/^\d+$/.test(id)) keyName = `pre-key-${id}`;
40
+ else if (base64Id) keyName = `app-state-sync-key-${id}`;
41
+ entries.push({ key: keyName, value: data[id] });
42
+ }
43
+ return entries;
44
+ }
45
+
9
46
  export async function useDatabaseAuthState(storageType = null) {
10
47
  // SQLite unless the caller explicitly asks for the throwaway memory store.
11
48
  const resolvedType = storageType || "sqlite";
12
49
  const storage = createAuthStorage(resolvedType);
13
50
  logger.info(`[Auth] Using ${resolvedType} storage backend`);
14
51
 
52
+ // Creds only. The first load runs while the socket is built, and saveCreds
53
+ // is the `creds.update` listener (src/core/events.js). A rejection there is
54
+ // an unhandled exception, so these three helpers still swallow. keys.get
55
+ // and keys.set do not use them.
15
56
  const writeData = async (key, data) => {
16
57
  try {
17
58
  await storage.writeData(key, data);
@@ -47,61 +88,47 @@ export async function useDatabaseAuthState(storageType = null) {
47
88
  logger.info("[Auth] Loaded existing credentials from database");
48
89
  }
49
90
 
91
+ let fenced = false;
92
+ let fencedSaveLogged = false;
93
+ const fence = () => {
94
+ fenced = true;
95
+ };
96
+
50
97
  const keys = {
51
98
  get: async (type, ids) => {
99
+ if (fenced) throw fencedError();
52
100
  const out = {};
53
101
  await Promise.all(
54
102
  ids.map(async (id) => {
55
- const key = `${type}-${id}`;
56
- const val = await readData(key);
103
+ if (fenced) throw fencedError();
104
+ const val = await storage.readData(`${type}-${id}`);
105
+ if (fenced) throw fencedError();
57
106
  if (val !== null && val !== undefined) out[id] = val;
58
107
  }),
59
108
  );
109
+ if (fenced) throw fencedError();
60
110
  return out;
61
111
  },
62
112
 
63
113
  set: async (data) => {
64
- try {
65
- const topKeys = Object.keys(data);
66
- const looksLikeTyped = topKeys.some((k) => typeof data[k] === "object" && data[k] !== null);
67
-
68
- if (looksLikeTyped) {
69
- for (const type of topKeys) {
70
- const typed = data[type];
71
- if (typeof typed !== "object" || typed === null) continue;
72
- for (const id of Object.keys(typed)) {
73
- const key = `${type}-${id}`;
74
- await writeData(key, typed[id]);
75
- }
76
- }
77
- return;
78
- }
79
-
80
- for (const id of topKeys) {
81
- const val = data[id];
82
- let keyName = id;
83
-
84
- if (id.includes("@")) {
85
- keyName = `session-${id}`;
86
- } else if (/^\d+$/.test(id)) {
87
- keyName = `pre-key-${id}`;
88
- } else if (id.length > 20 && /^[A-Za-z0-9+/=]+$/.test(id)) {
89
- keyName = `app-state-sync-key-${id}`;
90
- } else {
91
- keyName = id;
92
- }
93
-
94
- await writeData(keyName, val);
95
- }
96
- } catch (err) {
97
- logger.error({ err }, "[Auth] keys.set failed");
98
- }
114
+ if (fenced) throw fencedError();
115
+ const entries = collectKeyEntries(data);
116
+ if (entries.length === 0) return;
117
+ if (fenced) throw fencedError();
118
+ await storage.apply(entries);
99
119
  },
100
120
  };
101
121
 
102
122
  const state = { creds, keys };
103
123
 
104
124
  const saveCreds = async () => {
125
+ if (fenced) {
126
+ if (!fencedSaveLogged) {
127
+ fencedSaveLogged = true;
128
+ logger.debug("[Auth] Ignoring saveCreds on fenced auth state");
129
+ }
130
+ return;
131
+ }
105
132
  try {
106
133
  await writeData("creds", state.creds);
107
134
  } catch (err) {
@@ -109,20 +136,24 @@ export async function useDatabaseAuthState(storageType = null) {
109
136
  }
110
137
  };
111
138
 
139
+ // Unlike saveCreds, a failed wipe must reject. The fence stays set so a
140
+ // later keys.set cannot write the credentials the delete did not remove.
112
141
  const clearAll = async () => {
142
+ fenced = true;
113
143
  try {
114
144
  if (storage.clearAll) {
115
145
  await storage.clearAll();
116
146
  } else {
117
- await removeData("creds");
147
+ await storage.removeData("creds");
118
148
  }
119
149
  logger.info("[Auth] Cleared all authentication data");
120
150
  } catch (err) {
121
151
  logger.error({ err }, "[Auth] Failed to clear all data");
152
+ throw err;
122
153
  }
123
154
  };
124
155
 
125
- return { state, saveCreds, clearAll };
156
+ return { state, saveCreds, clearAll, fence };
126
157
  }
127
158
 
128
159
  export default useDatabaseAuthState;
@@ -0,0 +1,412 @@
1
+ // Free Core reaction actions. One winner, no waiting queue, no automatic retry.
2
+ import { createHash } from "node:crypto";
3
+ import { createRequire } from "node:module";
4
+ import { attachReactionIntake, REACTION_LIMITS } from "./reactions.js";
5
+ import {
6
+ resolveVerifiedSender,
7
+ verifiedIdentityAliases,
8
+ verifiedParticipant,
9
+ } from "../middleware/permissions.middleware.js";
10
+
11
+ const require = createRequire(import.meta.url);
12
+ const store = require("../db/store.cjs");
13
+ const runtime = require("../config/runtime-config.cjs");
14
+ const settings = require("../config/settings.cjs");
15
+ const status = require("./status.cjs");
16
+ const { evaluatePermissionLevel } = require("../utils/permissionLevel.cjs");
17
+ const { planDelivery, canonicalJid } = require("../messaging/router.cjs");
18
+ const { linkedIdentity } = require("../messaging/identity.cjs");
19
+ const { validateDefinition, originalType } = require("./rules.cjs");
20
+ const { assertWhatsAppAudio, assertAudio, MAX_MEDIA_BYTES } = require("../services/aiMedia.cjs");
21
+ const { sendBotMessage } = require("../utils/sendBotMessage.cjs");
22
+ const { readLiveGroupMetadata } = require("../utils/groupMetadataCache.cjs");
23
+ const { withLang, langForCommand, t } = require("../utils/i18n.cjs");
24
+ const logger = require("../utils/logger.cjs");
25
+ const { candidateLimit } = require("./limits.cjs");
26
+ const hash = (...values) => createHash("sha256").update(JSON.stringify(values)).digest("hex");
27
+ const fail = (code) => {
28
+ throw new Error(code);
29
+ };
30
+ const same = (a, b) => a === b || verifiedIdentityAliases(a).includes(canonicalJid(b));
31
+ const actorOf = (key) => key.participant || key.remoteJid;
32
+ // Across socket generations too: an ignored cancellation must not free a slot.
33
+ const inFlight = new Set();
34
+ const OUTCOMES = new Set([
35
+ "REACTION_CANCELLED",
36
+ "REACTION_TIMEOUT",
37
+ "REACTION_STALE",
38
+ "REACTION_INACCESSIBLE",
39
+ "REACTION_FORBIDDEN",
40
+ "REACTION_STT_DISABLED",
41
+ "REACTION_DELIVERY_REFUSED",
42
+ "REACTION_CAPACITY",
43
+ "REACTION_IDENTITY_INVALID",
44
+ "REACTION_VOICE_REQUIRED",
45
+ "STT_KEY_REQUIRED",
46
+ "STT_OUTPUT_INVALID",
47
+ "MEDIA_AUDIO_INVALID",
48
+ "MEDIA_TOO_LARGE",
49
+ "MEDIA_NOT_AVAILABLE",
50
+ "MEDIA_URL_INVALID",
51
+ ]);
52
+
53
+ export const REACTION_ACTION_LIMITS = Object.freeze({
54
+ perReactor: 3,
55
+ perChat: 10,
56
+ perRule: 5,
57
+ globalJobs: 2,
58
+ windowMs: 60_000,
59
+ // Per-event work bound (store query LIMIT candidateLimit + 1); not a rule-count cap.
60
+ candidateLimit,
61
+ });
62
+
63
+ // Read-only checks shared with management; authorization still belongs to the job.
64
+ export function reactionActionReadiness(action, { checkKey = true } = {}) {
65
+ const statuses = [];
66
+ if (runtime.isDisabled(action)) statuses.push("ACTION_DISABLED");
67
+ if (action === "stt") {
68
+ if (!settings.get("ai_stt_enabled")) statuses.push("STT_DISABLED");
69
+ if (checkKey) {
70
+ const stt = require("../commands/stt.cjs");
71
+ if (!settings.get(`${stt.resolveSttProvider()}_api_key`)) statuses.push("STT_KEY_MISSING");
72
+ }
73
+ }
74
+ return statuses;
75
+ }
76
+
77
+ function senderMatches(definition, sender) {
78
+ const { role, ids } = definition.senders;
79
+ if (ids.length && !ids.some((id) => same(sender.senderId, id))) return false;
80
+ return (
81
+ role === "any" ||
82
+ (role === "owner" && sender.isOwner) ||
83
+ (role === "bot_admin" && (sender.isOwner || sender.isBotAdmin)) ||
84
+ (role === "group_admin" && sender.isGroupAdmin) ||
85
+ (role === "member" && !sender.isOwner && !sender.isBotAdmin && !sender.isGroupAdmin)
86
+ );
87
+ }
88
+
89
+ export function createReactionAutomation(sock, { now = Date.now } = {}) {
90
+ const active = new Set();
91
+ let closed = false;
92
+ let lastCode = null;
93
+ let completed = 0;
94
+ const outcome = (code, job = null) => {
95
+ lastCode = code;
96
+ completed++;
97
+ const ruleId =
98
+ job?.rule && store.getReactionRule(job.rule.id)?.revision === job.rule.revision
99
+ ? job.rule.id
100
+ : null;
101
+ // Account clearing disables rows without rotating their revisions.
102
+ status.record(ruleId, code, now(), job?.statusEpoch ?? status.epoch());
103
+ logger.debug({ code }, "[Reactions] action outcome");
104
+ };
105
+ const cancel = (predicate = () => true) => {
106
+ for (const job of active)
107
+ if (predicate(job)) job.controller.abort(new Error("REACTION_CANCELLED"));
108
+ };
109
+ const intake = attachReactionIntake(sock, {
110
+ now,
111
+ onTransition: submit,
112
+ onInvalidate: (chat, id) =>
113
+ cancel(
114
+ (job) =>
115
+ !chat ||
116
+ (same(job.event.original.key.remoteJid, chat) &&
117
+ (!id || job.event.original.key.id === id)),
118
+ ),
119
+ onClose: () => close(),
120
+ });
121
+ const unsubscribe = store.subscribeReactionChanges((change) => {
122
+ cancel();
123
+ if (change.type === "rule" || change.key === "reaction:enabled") intake.resetLookup();
124
+ });
125
+ function close() {
126
+ if (closed) return;
127
+ closed = true;
128
+ cancel();
129
+ unsubscribe();
130
+ intake.close();
131
+ }
132
+ function available(job) {
133
+ job.controller.signal.throwIfAborted();
134
+ if (
135
+ closed ||
136
+ store.getBotSetting("reaction:enabled", false) !== true ||
137
+ job.event.configurationRevision !== store.getBotSetting("reaction:revision", "") ||
138
+ !intake.resolveTransition(job.token)
139
+ )
140
+ fail("REACTION_CANCELLED");
141
+ const time = now();
142
+ if (
143
+ job.event.timestampMs <= time - REACTION_LIMITS.ttlMs ||
144
+ job.event.original.messageTimestamp * 1000 <= time - REACTION_LIMITS.ttlMs
145
+ )
146
+ fail("REACTION_STALE");
147
+ if (job.rule) {
148
+ const current = store.getReactionRule(job.rule.id);
149
+ if (
150
+ !current?.enabled ||
151
+ current.revision !== job.rule.revision ||
152
+ current.definition !== job.rule.definition ||
153
+ current.chat_jid !== job.rule.chat_jid ||
154
+ current.enabled_at !== job.rule.enabled_at
155
+ )
156
+ fail("REACTION_CANCELLED");
157
+ }
158
+ }
159
+ async function refresh(job) {
160
+ available(job);
161
+ const chat = job.event.original.key.remoteJid;
162
+ if (chat.endsWith("@g.us")) {
163
+ const metadata = await readLiveGroupMetadata(sock, chat);
164
+ available(job);
165
+ if (
166
+ canonicalJid(metadata?.id) !== chat ||
167
+ !Array.isArray(metadata.participants) ||
168
+ metadata.participants.length > 5000
169
+ )
170
+ fail("REACTION_INACCESSIBLE");
171
+ job.metadata = metadata;
172
+ }
173
+ }
174
+ function sender(job) {
175
+ available(job);
176
+ const event = job.event;
177
+ const subject = resolveVerifiedSender({ key: event.actorKey }, job.metadata, sock);
178
+ if (subject.isGroup) {
179
+ if (
180
+ !verifiedParticipant(job.metadata, subject.senderId) ||
181
+ !verifiedParticipant(job.metadata, actorOf(event.original.key)) ||
182
+ ![sock?.user?.id, sock?.user?.lid].some((id) => verifiedParticipant(job.metadata, id))
183
+ )
184
+ fail("REACTION_INACCESSIBLE");
185
+ const blacklist = store.getGroupSettings(event.original.key.remoteJid).blacklist || [];
186
+ if (
187
+ !Array.isArray(blacklist) ||
188
+ (blacklist.some((id) => same(subject.senderId, id)) && !subject.isGroupAdmin)
189
+ )
190
+ fail("REACTION_FORBIDDEN");
191
+ }
192
+ return subject;
193
+ }
194
+ function authorize(job) {
195
+ const subject = sender(job);
196
+ const readiness = reactionActionReadiness(job.definition.action, { checkKey: false });
197
+ if (
198
+ !senderMatches(job.definition, subject) ||
199
+ readiness.includes("ACTION_DISABLED") ||
200
+ !evaluatePermissionLevel(runtime.getPermission(job.definition.action), subject).hasPermission
201
+ )
202
+ fail("REACTION_FORBIDDEN");
203
+ if (readiness.includes("STT_DISABLED")) fail("REACTION_STT_DISABLED");
204
+ return subject;
205
+ }
206
+ function delivery(job) {
207
+ authorize(job);
208
+ const source = job.event.original.key.remoteJid;
209
+ const mode = job.definition.destination.mode;
210
+ const result = planDelivery({
211
+ sourceJid: source,
212
+ requestedJid: source,
213
+ senderJid: actorOf(job.event.actorKey),
214
+ commandName: job.definition.action,
215
+ routeMode: mode,
216
+ sensitivity: "source",
217
+ identity: mode === "same_chat" ? { selfJids: [] } : linkedIdentity(),
218
+ });
219
+ if (!result.allow || !result.destination) fail("REACTION_DELIVERY_REFUSED");
220
+ return result;
221
+ }
222
+ async function send(job, content) {
223
+ await refresh(job);
224
+ const planned = delivery(job);
225
+ const guard = {
226
+ refresh: () => refresh(job),
227
+ assert: () => {
228
+ const final = delivery(job);
229
+ if (final.destination !== planned.destination || final.quote !== planned.quote)
230
+ fail("REACTION_DELIVERY_REFUSED");
231
+ },
232
+ };
233
+ const result = await sendBotMessage(sock, planned.destination, content, {
234
+ signal: job.controller.signal,
235
+ deliveryGuard: guard,
236
+ replyTo: planned.quote ? job.event.original : null,
237
+ quote: planned.quote,
238
+ });
239
+ if (!result?.key || result.refused) fail("REACTION_DELIVERY_REFUSED");
240
+ }
241
+ function candidatesFor(event) {
242
+ const candidates = [];
243
+ const rows = store.reactionRulesForChats(
244
+ store.reactionIdentityAliases(event.original.key.remoteJid),
245
+ {
246
+ emoji: event.type === "remove" ? event.previousEmoji : event.emoji,
247
+ type: event.type,
248
+ originalType: originalType(event.original),
249
+ },
250
+ );
251
+ if (rows.length > REACTION_ACTION_LIMITS.candidateLimit) fail("REACTION_CAPACITY");
252
+ for (const row of rows) {
253
+ let definition;
254
+ try {
255
+ definition = validateDefinition(JSON.parse(row.definition));
256
+ } catch {
257
+ continue;
258
+ }
259
+ if (
260
+ event.configurationRevision !== store.getBotSetting("reaction:revision", "") ||
261
+ !Number.isSafeInteger(row.enabled_at) ||
262
+ event.receivedAt <= row.enabled_at ||
263
+ event.original.messageTimestamp * 1000 <= Math.max(row.enabled_at, event.connectionAt) ||
264
+ event.original.messageTimestamp * 1000 > event.receivedAt ||
265
+ event.timestampMs <= row.enabled_at ||
266
+ !definition.transitions.includes(event.type) ||
267
+ definition.emoji !== (event.type === "remove" ? event.previousEmoji : event.emoji) ||
268
+ !definition.originalTypes.includes(originalType(event.original))
269
+ )
270
+ continue;
271
+ candidates.push({ row, definition });
272
+ }
273
+ return candidates;
274
+ }
275
+ async function execute(job) {
276
+ await refresh(job);
277
+ const subject = sender(job);
278
+ const event = job.event;
279
+ for (const candidate of job.candidates) {
280
+ if (!senderMatches(candidate.definition, subject)) continue;
281
+ job.rule = candidate.row;
282
+ job.definition = candidate.definition;
283
+ break;
284
+ }
285
+ if (!job.rule) return "NO_MATCH";
286
+ authorize(job);
287
+ delivery(job);
288
+ const budgets = [{ key: hash("rule", job.rule.id), limit: REACTION_ACTION_LIMITS.perRule }];
289
+ const claimed = store.claimReactionExecution(
290
+ {
291
+ eventKey: event.eventKey,
292
+ ruleKey: hash(event.eventKey, job.rule.id, job.rule.revision),
293
+ actionKey: hash(event.eventKey, job.definition.action, job.definition.destination),
294
+ expiresAt: event.timestampMs + REACTION_LIMITS.ttlMs + REACTION_LIMITS.futureSkewMs,
295
+ budgets,
296
+ },
297
+ now(),
298
+ );
299
+ if (claimed !== "CLAIMED") return claimed;
300
+ // No await separates the live authorization check and action invocation.
301
+ authorize(job);
302
+ const command =
303
+ job.definition.action === "ping"
304
+ ? require("../commands/ping.cjs")
305
+ : require("../commands/stt.cjs");
306
+ return withLang(langForCommand(command), async () => {
307
+ if (job.definition.action === "ping") {
308
+ await require("../commands/ping.cjs").execute(
309
+ { sendMessage: (_jid, content) => send(job, content) },
310
+ event.original,
311
+ );
312
+ } else {
313
+ const audio = event.original.message.audioMessage;
314
+ assertWhatsAppAudio(audio);
315
+ if (audio.ptt !== true) fail("REACTION_VOICE_REQUIRED");
316
+ const stt = require("../commands/stt.cjs");
317
+ if (reactionActionReadiness("stt").includes("STT_KEY_MISSING")) fail("STT_KEY_REQUIRED");
318
+ const bytes = await require("../utils/geminiMedia.cjs").downloadMedia(
319
+ require("@whiskeysockets/baileys").downloadContentFromMessage,
320
+ audio,
321
+ "audio",
322
+ { maxBytes: MAX_MEDIA_BYTES, signal: job.controller.signal },
323
+ );
324
+ await refresh(job);
325
+ authorize(job);
326
+ assertAudio(bytes, audio.mimetype, true);
327
+ const text = await stt.transcribe(bytes, audio.mimetype, { signal: job.controller.signal });
328
+ authorize(job);
329
+ if (typeof text !== "string" || !text.trim() || text.length > 12000)
330
+ fail("STT_OUTPUT_INVALID");
331
+ await send(job, { text: t("bot.ai.stt.transcript", { transcription: text }) });
332
+ }
333
+ return "DELIVERED";
334
+ });
335
+ }
336
+ function submit(token) {
337
+ const event = intake.resolveTransition(token);
338
+ if (!event || closed || store.getBotSetting("reaction:enabled", false) !== true) return;
339
+ let candidates;
340
+ try {
341
+ candidates = candidatesFor(event);
342
+ } catch {
343
+ outcome("REACTION_CAPACITY");
344
+ return;
345
+ }
346
+ if (!candidates.length) {
347
+ outcome("NO_MATCH");
348
+ return;
349
+ }
350
+ if (
351
+ inFlight.size >= REACTION_ACTION_LIMITS.globalJobs ||
352
+ [...inFlight].some((job) => same(actorOf(job.event.actorKey), actorOf(event.actorKey)))
353
+ ) {
354
+ outcome("BUSY");
355
+ return;
356
+ }
357
+ const actor = verifiedIdentityAliases(actorOf(event.actorKey));
358
+ const budgets = [
359
+ ...actor.map((id) => ({ key: hash("actor", id), limit: REACTION_ACTION_LIMITS.perReactor })),
360
+ ...store
361
+ .reactionIdentityAliases(event.original.key.remoteJid)
362
+ .map((id) => ({ key: hash("chat", id), limit: REACTION_ACTION_LIMITS.perChat })),
363
+ ];
364
+ const admission = store.admitReactionAttempt(budgets, now());
365
+ if (admission !== "ADMITTED") {
366
+ outcome(admission);
367
+ return;
368
+ }
369
+ const job = {
370
+ token,
371
+ event,
372
+ candidates,
373
+ controller: new AbortController(),
374
+ rule: null,
375
+ statusEpoch: status.epoch(),
376
+ };
377
+ active.add(job);
378
+ inFlight.add(job);
379
+ const timeout = Math.max(
380
+ 1,
381
+ Math.min(120_000, Number(settings.get("ai_tool_timeout_ms")) || 30_000),
382
+ );
383
+ const timer = setTimeout(() => job.controller.abort(new Error("REACTION_TIMEOUT")), timeout);
384
+ job.work = execute(job)
385
+ .then(
386
+ (code) => outcome(code, job),
387
+ (error) => {
388
+ const message = String(job.controller.signal.reason?.message || error?.message || "");
389
+ const code = OUTCOMES.has(message) ? message : "ACTION_FAILED";
390
+ outcome(code, job);
391
+ },
392
+ )
393
+ .finally(() => {
394
+ clearTimeout(timer);
395
+ active.delete(job);
396
+ inFlight.delete(job);
397
+ });
398
+ }
399
+ return {
400
+ intake,
401
+ close,
402
+ cancelChat(chat) {
403
+ cancel((job) => same(job.event.original.key.remoteJid, chat));
404
+ },
405
+ stats() {
406
+ return { active: active.size, completed, lastCode };
407
+ },
408
+ settled() {
409
+ return Promise.all([...active].map((job) => job.work));
410
+ },
411
+ };
412
+ }
@@ -0,0 +1,6 @@
1
+ // Shared reaction bounds. Leaf module: the store and the engine both read it,
2
+ // and neither may import the other.
3
+ const candidateLimit = 100;
4
+ const MAX_IDENTITY_ALIASES = 4;
5
+
6
+ module.exports = { candidateLimit, MAX_IDENTITY_ALIASES };