levix-bot 4.9.2 → 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 (242) 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 +46 -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 +1 -1
  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 +182 -10
  138. package/src/core/connection.js +37 -8
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +525 -82
  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/debugLog.cjs +16 -4
  147. package/src/diagnostics/device.cjs +4 -2
  148. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  149. package/src/domain/command.js +24 -22
  150. package/src/extensions/autoReply.cjs +521 -0
  151. package/src/extensions/context.cjs +73 -0
  152. package/src/extensions/contract.cjs +69 -0
  153. package/src/extensions/entitlement/client.cjs +381 -0
  154. package/src/extensions/entitlement/index.cjs +629 -0
  155. package/src/extensions/entitlement/installation.cjs +117 -0
  156. package/src/extensions/entitlement/keys.cjs +72 -0
  157. package/src/extensions/entitlement/state.cjs +201 -0
  158. package/src/extensions/entitlement/target.cjs +7 -0
  159. package/src/extensions/entitlement/token.cjs +225 -0
  160. package/src/extensions/host.cjs +519 -0
  161. package/src/extensions/templateKeys.cjs +81 -0
  162. package/src/handlers/command.handler.js +191 -64
  163. package/src/handlers/group.handler.js +78 -18
  164. package/src/handlers/message.handler.js +56 -25
  165. package/src/i18n/catalog.generated.cjs +3537 -0
  166. package/src/index.js +51 -12
  167. package/src/legal/bundled/ar.json +102 -0
  168. package/src/legal/bundled/en.json +102 -0
  169. package/src/legal/bundled/es-419.json +102 -0
  170. package/src/legal/bundled/pt-BR.json +102 -0
  171. package/src/legal/cli.cjs +200 -0
  172. package/src/legal/consent.cjs +187 -0
  173. package/src/legal/document.cjs +156 -0
  174. package/src/legal/keys.cjs +100 -0
  175. package/src/legal/release.cjs +226 -0
  176. package/src/legal/remote.cjs +419 -0
  177. package/src/legal/terms.cjs +142 -0
  178. package/src/messaging/escape.cjs +31 -0
  179. package/src/messaging/health.cjs +65 -0
  180. package/src/messaging/identity.cjs +42 -0
  181. package/src/messaging/message.cjs +136 -0
  182. package/src/messaging/parser.cjs +88 -0
  183. package/src/messaging/router.cjs +217 -0
  184. package/src/middleware/permissions.middleware.js +34 -2
  185. package/src/panel/account-profile.cjs +489 -0
  186. package/src/panel/fallback-page.cjs +177 -0
  187. package/src/panel/password-reset.cjs +13 -14
  188. package/src/panel/recovery-email.cjs +3 -1
  189. package/src/routes/backup.api.esm.js +175 -0
  190. package/src/routes/dashboard.api.esm.js +183 -7
  191. package/src/routes/plus.api.esm.js +172 -0
  192. package/src/routes/reactions.api.esm.js +60 -0
  193. package/src/services/aiAgent.cjs +56 -43
  194. package/src/services/aiDocs.cjs +187 -0
  195. package/src/services/aiImage.cjs +183 -0
  196. package/src/services/aiMedia.cjs +146 -0
  197. package/src/services/aiProviders.cjs +76 -80
  198. package/src/services/aiRouter.cjs +2 -2
  199. package/src/services/aiToolAuth.cjs +76 -4
  200. package/src/services/aiTools.cjs +431 -105
  201. package/src/services/autoDelete.cjs +9 -1
  202. package/src/services/levix-docs.generated.json +2623 -0
  203. package/src/services/memoryPolicy.cjs +56 -0
  204. package/src/services/updateCheck.cjs +362 -0
  205. package/src/stickers/errors.cjs +53 -97
  206. package/src/stickers/library.cjs +13 -6
  207. package/src/stickers/owner.cjs +1 -1
  208. package/src/utils/commandContext.cjs +13 -0
  209. package/src/utils/commandDocs.cjs +42 -20
  210. package/src/utils/geminiHttpOptions.cjs +56 -0
  211. package/src/utils/geminiMedia.cjs +28 -3
  212. package/src/utils/groupMetadataCache.cjs +386 -21
  213. package/src/utils/httpsFetch.cjs +113 -0
  214. package/src/utils/i18n.cjs +117 -7
  215. package/src/utils/linkPreview.cjs +90 -0
  216. package/src/utils/markdownParser.cjs +3 -3
  217. package/src/utils/memory.cjs +375 -28
  218. package/src/utils/messageContent.cjs +7 -1
  219. package/src/utils/moderationAction.cjs +116 -73
  220. package/src/utils/moderationSummary.cjs +32 -56
  221. package/src/utils/permissionLevel.cjs +7 -28
  222. package/src/utils/permissions.cjs +23 -14
  223. package/src/utils/permissions.esm.js +99 -166
  224. package/src/utils/recentMessageCache.esm.js +241 -37
  225. package/src/utils/recurrence.cjs +78 -66
  226. package/src/utils/sendBotMessage.cjs +14 -29
  227. package/src/utils/sendBotMessage.esm.js +28 -13
  228. package/src/utils/statusMessage.cjs +94 -33
  229. package/src/utils/stickerBot.cjs +18 -16
  230. package/src/utils/storage.cjs +2 -0
  231. package/src/utils/storage.esm.js +2 -0
  232. package/src/utils/thumbnail.cjs +5 -21
  233. package/public/dashboard/assets/index-4xhK_Tpl.js +0 -561
  234. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  235. package/public/dashboard.css +0 -3127
  236. package/public/dashboard.js +0 -1981
  237. package/public/gateway-i18n.js +0 -321
  238. package/public/gateway.js +0 -70
  239. package/views/dashboard.ejs +0 -775
  240. package/views/login.ejs +0 -408
  241. package/views/qr.ejs +0 -155
  242. package/views/setup.ejs +0 -118
@@ -0,0 +1,471 @@
1
+ // Bounded verified transport intake. Execution belongs to engine.js.
2
+ import { createHash } from "node:crypto";
3
+ import { createRequire } from "node:module";
4
+ import { deserialize, serialize } from "node:v8";
5
+ import { sameUser } from "../utils/permissions.esm.js";
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const store = require("../db/store.cjs");
9
+ const { canonicalJid } = require("../messaging/router.cjs");
10
+ const { isReactionEmoji } = require("./rules.cjs");
11
+ const { MAX_IDENTITY_ALIASES } = require("./limits.cjs");
12
+ const logger = require("../utils/logger.cjs");
13
+
14
+ export const REACTION_LIMITS = Object.freeze({
15
+ ttlMs: 30 * 60_000,
16
+ futureSkewMs: 30_000,
17
+ maxItems: 500,
18
+ maxBytes: 8 * 1024 * 1024,
19
+ maxEntryBytes: 64 * 1024,
20
+ maxBatch: 100,
21
+ });
22
+ const sockets = new WeakMap();
23
+ const idPattern = /^[A-Za-z0-9_-]{1,128}$/;
24
+ const jidPattern =
25
+ /^(?:\d{1,30}(?::\d{1,5})?@(s\.whatsapp\.net|lid|g\.us)|\d{1,30}-\d{1,30}@g\.us)$/;
26
+ const mediaFields = [
27
+ "url",
28
+ "directPath",
29
+ "mediaKey",
30
+ "fileEncSha256",
31
+ "fileSha256",
32
+ "fileLength",
33
+ "mimetype",
34
+ "seconds",
35
+ "ptt",
36
+ "width",
37
+ "height",
38
+ "caption",
39
+ "fileName",
40
+ ];
41
+ const contentKeys = [
42
+ "conversation",
43
+ "extendedTextMessage",
44
+ "audioMessage",
45
+ "imageMessage",
46
+ "videoMessage",
47
+ "documentMessage",
48
+ "stickerMessage",
49
+ ];
50
+ const hash = (parts) => createHash("sha256").update(JSON.stringify(parts)).digest("hex");
51
+ const numberOf = (value) => (value == null ? NaN : Number(String(value)));
52
+
53
+ // Validate BEFORE normalization; normalizeJid deliberately accepts legacy inputs.
54
+ function jid(value) {
55
+ if (typeof value !== "string" || !jidPattern.test(value)) return null;
56
+ if (value.endsWith("@g.us") && value.includes(":")) return null;
57
+ return canonicalJid(value);
58
+ }
59
+ function aliases(value) {
60
+ const ids = store.reactionIdentityAliases(value);
61
+ return ids.length <= MAX_IDENTITY_ALIASES && ids.every((id) => jid(id)) ? ids : [];
62
+ }
63
+ function sameIdentity(a, b) {
64
+ if (a === b) return true;
65
+ if (!a || !b || a.endsWith("@g.us") || b.endsWith("@g.us")) return false;
66
+ // sameUser's legacy numeric fallback alone is not proof of a LID/PN link.
67
+ return aliases(a).includes(b) && sameUser(a, b);
68
+ }
69
+ function user(value) {
70
+ const normalized = jid(value);
71
+ return normalized && !normalized.endsWith("@g.us") ? normalized : null;
72
+ }
73
+ function messageKey(key) {
74
+ const chat = jid(key?.remoteJid);
75
+ if (
76
+ !chat ||
77
+ key?.isViewOnce ||
78
+ typeof key?.id !== "string" ||
79
+ !idPattern.test(key.id) ||
80
+ key?.fromMe !== false
81
+ )
82
+ return null;
83
+ const author = chat.endsWith("@g.us") ? user(key.participant) : chat;
84
+ if (!author || (key.participant && !sameIdentity(author, user(key.participant)))) return null;
85
+ return {
86
+ remoteJid: chat,
87
+ id: key.id,
88
+ fromMe: false,
89
+ ...(chat.endsWith("@g.us") ? { participant: author } : {}),
90
+ };
91
+ }
92
+ const identityOf = (key) => [key.remoteJid, key.id, key.fromMe, key.participant || key.remoteJid];
93
+ const lookupKey = (key) => JSON.stringify(identityOf(key));
94
+ const invalidationKeys = (chat, id = "*") => aliases(chat).map((alias) => hash([alias, id]));
95
+
96
+ function safeContent(message) {
97
+ // Disappearing, view-once and edited content is deliberately unsupported.
98
+ let inner = message;
99
+ if (inner?.documentWithCaptionMessage?.message) inner = inner.documentWithCaptionMessage.message;
100
+ if (
101
+ !inner ||
102
+ Object.keys(inner).some(
103
+ (key) =>
104
+ !contentKeys.includes(key) &&
105
+ !["messageContextInfo", "senderKeyDistributionMessage"].includes(key),
106
+ )
107
+ )
108
+ return null;
109
+ const keys = contentKeys.filter((key) => inner[key] != null);
110
+ if (keys.length !== 1) return null;
111
+ const key = keys[0];
112
+ const source = inner[key];
113
+ if (
114
+ inner.messageContextInfo?.botMetadata ||
115
+ inner.messageContextInfo?.botMessageSecret ||
116
+ source?.contextInfo?.botMessageSharingInfo ||
117
+ source?.contextInfo?.botMessageInvokerJid
118
+ )
119
+ return null;
120
+ if (source?.viewOnce || source?.contextInfo?.expiration || inner.messageContextInfo?.expiration)
121
+ return null;
122
+ if (key === "conversation")
123
+ return typeof source === "string" && source.length <= 65536 ? { conversation: source } : null;
124
+ if (key === "extendedTextMessage") {
125
+ return typeof source?.text === "string" && source.text.length <= 65536
126
+ ? { extendedTextMessage: { text: source.text } }
127
+ : null;
128
+ }
129
+ if (!source || typeof source !== "object") return null;
130
+ const media = {};
131
+ for (const field of mediaFields) {
132
+ const value = source[field];
133
+ if (value == null) continue;
134
+ if (["mediaKey", "fileEncSha256", "fileSha256"].includes(field)) {
135
+ if (!(value instanceof Uint8Array) || value.byteLength > 64) return null;
136
+ media[field] = value;
137
+ } else if (field === "ptt") {
138
+ if (typeof value !== "boolean") return null;
139
+ media[field] = value;
140
+ } else if (["seconds", "width", "height", "fileLength"].includes(field)) {
141
+ const number = numberOf(value);
142
+ if (!Number.isSafeInteger(number) || number < 0) return null;
143
+ media[field] = number;
144
+ } else {
145
+ if (typeof value !== "string" || value.length > (field === "caption" ? 65536 : 4096))
146
+ return null;
147
+ media[field] = value;
148
+ }
149
+ }
150
+ return { [key]: media };
151
+ }
152
+
153
+ /** One bounded lookup per live socket. Timers/closures are disposed with it. */
154
+ export function createReactionIntake(
155
+ sock,
156
+ {
157
+ now = Date.now,
158
+ limits = REACTION_LIMITS,
159
+ onTransition = () => {},
160
+ onInvalidate = () => {},
161
+ onClose = () => {},
162
+ } = {},
163
+ ) {
164
+ const cache = new Map();
165
+ const verified = new WeakMap();
166
+ let bytes = 0;
167
+ let active = false;
168
+ let closed = false;
169
+ let connectionAt = Infinity;
170
+ function block() {
171
+ cache.clear();
172
+ bytes = 0;
173
+ onInvalidate();
174
+ store.invalidateReactionLookup(null, now() + limits.ttlMs + limits.futureSkewMs, now());
175
+ }
176
+ const self = () => [user(sock?.user?.id), user(sock?.user?.lid)].filter(Boolean);
177
+ const isSelf = (author) => self().some((id) => sameIdentity(id, author));
178
+ const enabled = (chat) => aliases(chat).some((id) => store.isReactionChatEnabled(id));
179
+ const fresh = (timestamp, time) =>
180
+ Number.isSafeInteger(timestamp) &&
181
+ timestamp > time - limits.ttlMs &&
182
+ timestamp <= time + limits.futureSkewMs;
183
+
184
+ function drop(key) {
185
+ const entry = cache.get(key);
186
+ if (entry) bytes -= entry.size;
187
+ cache.delete(key);
188
+ if (entry) onInvalidate(entry.chat, entry.id);
189
+ }
190
+ function sweep() {
191
+ const time = now();
192
+ const scopes = new Map();
193
+ for (const [key, entry] of cache) {
194
+ if (!scopes.has(entry.chat)) scopes.set(entry.chat, enabled(entry.chat));
195
+ if (entry.expiresAt <= time || !scopes.get(entry.chat)) drop(key);
196
+ }
197
+ }
198
+ function invalidated(chat, id) {
199
+ const ids = aliases(chat);
200
+ return (
201
+ !ids.length ||
202
+ store.isReactionLookupInvalidated(
203
+ [...invalidationKeys(chat), ...invalidationKeys(chat, id)],
204
+ now(),
205
+ )
206
+ );
207
+ }
208
+ function invalidate(chatValue, id) {
209
+ const chat = jid(chatValue);
210
+ if (!active || !chat) return;
211
+ onInvalidate(chat, id);
212
+ // A configured but disabled chat still needs negative lookup state: a
213
+ // delete during disablement must not revive when the rule is re-enabled.
214
+ const tracked = [...cache.values()].some((entry) => sameIdentity(entry.chat, chat));
215
+ if (!tracked && !aliases(chat).some((alias) => store.isReactionChatConfigured(alias))) return;
216
+ sweep();
217
+ for (const [key, entry] of cache) {
218
+ if (sameIdentity(entry.chat, chat) && (!id || entry.id === id)) drop(key);
219
+ }
220
+ const keys = invalidationKeys(chat, id);
221
+ const blocked = store.invalidateReactionLookup(
222
+ keys.length ? keys : null,
223
+ now() + limits.ttlMs + limits.futureSkewMs,
224
+ now(),
225
+ limits.maxItems,
226
+ );
227
+ if (blocked) {
228
+ cache.clear();
229
+ bytes = 0;
230
+ }
231
+ }
232
+ function findOriginal(key) {
233
+ const exact = cache.get(lookupKey(key));
234
+ if (exact) return exact;
235
+ return [...cache.values()].find(
236
+ (entry) =>
237
+ entry.id === key.id &&
238
+ sameIdentity(entry.chat, key.remoteJid) &&
239
+ sameIdentity(entry.author, key.participant || key.remoteJid),
240
+ );
241
+ }
242
+ function remember(msg) {
243
+ if (!active || !self().length) return false;
244
+ const key = messageKey(msg?.key);
245
+ const time = now();
246
+ if (!key || !enabled(key.remoteJid) || isSelf(key.participant || key.remoteJid)) return false;
247
+ sweep();
248
+ if (
249
+ invalidated(key.remoteJid, key.id) ||
250
+ !fresh(numberOf(msg.messageTimestamp) * 1000, time) ||
251
+ msg.messageStubType != null ||
252
+ numberOf(msg.ephemeralStartTimestamp) > 0 ||
253
+ numberOf(msg.ephemeralDuration) > 0
254
+ )
255
+ return false;
256
+ const content = safeContent(msg.message);
257
+ if (!content) return false;
258
+ const value = { key, message: content, messageTimestamp: numberOf(msg.messageTimestamp) };
259
+ const data = serialize(value);
260
+ if (data.byteLength > limits.maxEntryBytes || data.byteLength > limits.maxBytes) return false;
261
+ const index = lookupKey(key);
262
+ // Redelivery never extends retention or replaces a verified snapshot.
263
+ if (findOriginal(key)) return false;
264
+ const configurationRevision = store.getBotSetting("reaction:revision", "");
265
+ const size = data.byteLength + serialize(configurationRevision).byteLength;
266
+ if (size > limits.maxEntryBytes || size > limits.maxBytes) return false;
267
+ while (cache.size >= limits.maxItems || bytes + size > limits.maxBytes)
268
+ drop(cache.keys().next().value);
269
+ cache.set(index, {
270
+ chat: key.remoteJid,
271
+ id: key.id,
272
+ author: key.participant || key.remoteJid,
273
+ data,
274
+ receivedAt: time,
275
+ configurationRevision,
276
+ size,
277
+ expiresAt: Math.min(time, numberOf(msg.messageTimestamp) * 1000) + limits.ttlMs,
278
+ });
279
+ bytes += size;
280
+ return true;
281
+ }
282
+ function observeUpsert(payload) {
283
+ if (
284
+ !active ||
285
+ payload?.type !== "notify" ||
286
+ payload.requestId ||
287
+ !Array.isArray(payload.messages)
288
+ )
289
+ return;
290
+ if (payload.messages.length > limits.maxBatch) {
291
+ block();
292
+ return;
293
+ }
294
+ sweep();
295
+ const folded = [];
296
+ for (const msg of payload.messages.slice(0, limits.maxBatch)) {
297
+ const protocol = msg?.message?.protocolMessage;
298
+ if (protocol?.key?.id) {
299
+ const chat = jid(msg?.key?.remoteJid);
300
+ // Revoke and edit envelopes are invalidations, never new originals.
301
+ if (chat && (!protocol.key.remoteJid || jid(protocol.key.remoteJid) === chat))
302
+ invalidate(chat, protocol.key.id);
303
+ }
304
+ remember(msg);
305
+ if (Array.isArray(msg?.reactions)) {
306
+ if (folded.length + msg.reactions.length > limits.maxBatch) {
307
+ block();
308
+ return [];
309
+ }
310
+ for (const reaction of msg.reactions) folded.push({ key: msg.key, reaction });
311
+ }
312
+ }
313
+ // Baileys can fold dedicated reactions into an original's buffered upsert.
314
+ return observeReactions(folded);
315
+ }
316
+ function observeUpdates(updates) {
317
+ if (!Array.isArray(updates)) return;
318
+ if (updates.length > limits.maxBatch) {
319
+ block();
320
+ return;
321
+ }
322
+ for (const item of updates.slice(0, limits.maxBatch)) {
323
+ if (item?.key?.id && item.update && Object.hasOwn(item.update, "message"))
324
+ invalidate(item.key.remoteJid, item.key.id);
325
+ }
326
+ }
327
+ function observeDeletes(payload) {
328
+ if (payload?.all === true) invalidate(payload.jid);
329
+ else if (Array.isArray(payload?.keys)) {
330
+ if (payload.keys.length > limits.maxBatch) {
331
+ block();
332
+ return;
333
+ }
334
+ for (const key of payload.keys.slice(0, limits.maxBatch))
335
+ if (key?.id) invalidate(key.remoteJid, key.id);
336
+ }
337
+ }
338
+ function reaction(entry) {
339
+ if (!active || !self().length) return null;
340
+ const originalKey = messageKey(entry?.key);
341
+ const actorKey = messageKey(entry?.reaction?.key);
342
+ const emoji = entry?.reaction?.text ?? "";
343
+ const time = now();
344
+ const timestampMs = numberOf(entry?.reaction?.senderTimestampMs);
345
+ if (
346
+ !originalKey ||
347
+ !actorKey ||
348
+ !sameIdentity(originalKey.remoteJid, actorKey.remoteJid) ||
349
+ typeof emoji !== "string" ||
350
+ emoji.length > 32 ||
351
+ (emoji && !isReactionEmoji(emoji)) ||
352
+ !fresh(timestampMs, time) ||
353
+ !enabled(originalKey.remoteJid)
354
+ )
355
+ return null;
356
+ const actor = actorKey.participant || actorKey.remoteJid;
357
+ if (isSelf(actor) || isSelf(originalKey.participant || originalKey.remoteJid)) return null;
358
+ sweep();
359
+ if (invalidated(originalKey.remoteJid, originalKey.id)) return null;
360
+ const stored = findOriginal(originalKey);
361
+ if (!stored) return null;
362
+ const account = self()[0];
363
+ // Transport ids are account-wide. Conservatively refuse any reuse, even
364
+ // across PN/LID chat aliases learned after the original claim.
365
+ const eventKey = hash([account, actorKey.id]);
366
+ const slotKeys = [];
367
+ for (const chat of aliases(originalKey.remoteJid)) {
368
+ for (const author of aliases(originalKey.participant || originalKey.remoteJid)) {
369
+ for (const sender of aliases(actor))
370
+ slotKeys.push(hash([account, chat, originalKey.id, false, author, sender]));
371
+ }
372
+ }
373
+ if (!slotKeys.length) return null;
374
+ const transition = store.claimReactionEvent(
375
+ {
376
+ eventKey,
377
+ slotKeys,
378
+ timestampMs,
379
+ emoji,
380
+ expiresAt: timestampMs + limits.ttlMs + limits.futureSkewMs,
381
+ },
382
+ time,
383
+ true,
384
+ );
385
+ if (!transition) return null;
386
+ const value = {
387
+ eventKey,
388
+ ...transition,
389
+ emoji,
390
+ timestampMs,
391
+ actorKey,
392
+ original: deserialize(stored.data),
393
+ receivedAt: stored.receivedAt,
394
+ configurationRevision: stored.configurationRevision,
395
+ connectionAt,
396
+ };
397
+ verified.set(value, { stored, data: serialize(value) });
398
+ onTransition(value);
399
+ return value;
400
+ }
401
+ function observeReactions(entries) {
402
+ if (!Array.isArray(entries)) return [];
403
+ sweep();
404
+ return entries.slice(0, limits.maxBatch).map(reaction).filter(Boolean);
405
+ }
406
+ function close() {
407
+ closed = true;
408
+ active = false;
409
+ cache.clear();
410
+ bytes = 0;
411
+ onClose();
412
+ clearInterval(timer);
413
+ }
414
+ const timer = setInterval(() => {
415
+ try {
416
+ sweep();
417
+ } catch {
418
+ close();
419
+ logger.warn("[Reactions] lookup sweep failed; cached originals discarded");
420
+ }
421
+ }, 60_000);
422
+ timer.unref?.();
423
+ return {
424
+ open() {
425
+ if (!closed && !active) {
426
+ active = true;
427
+ connectionAt = now();
428
+ }
429
+ },
430
+ close,
431
+ observeUpsert,
432
+ observeUpdates,
433
+ observeDeletes,
434
+ observeReactions,
435
+ resetLookup() {
436
+ for (const key of cache.keys()) drop(key);
437
+ },
438
+ resolveTransition(value) {
439
+ const record = verified.get(value);
440
+ if (
441
+ !active ||
442
+ !record ||
443
+ record.stored.expiresAt <= now() ||
444
+ !enabled(record.stored.chat) ||
445
+ invalidated(record.stored.chat, record.stored.id) ||
446
+ findOriginal(deserialize(record.stored.data).key) !== record.stored
447
+ )
448
+ return null;
449
+ return deserialize(record.data);
450
+ },
451
+ // Resource counters only; no private cache contents in diagnostics.
452
+ stats() {
453
+ sweep();
454
+ return { items: cache.size, bytes };
455
+ },
456
+ };
457
+ }
458
+
459
+ export function attachReactionIntake(sock, options) {
460
+ disposeReactionIntake(sock);
461
+ const intake = createReactionIntake(sock, options);
462
+ sockets.set(sock, intake);
463
+ return intake;
464
+ }
465
+ export function disposeReactionIntake(sock) {
466
+ sockets.get(sock)?.close();
467
+ sockets.delete(sock);
468
+ }
469
+ export function invalidateReactionMessage(sock, key) {
470
+ sockets.get(sock)?.observeDeletes({ keys: [key] });
471
+ }
@@ -0,0 +1,114 @@
1
+ // Internal configuration contract. No executable expressions or command arguments.
2
+ const { canonicalJid } = require("../messaging/router.cjs");
3
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
4
+ const TYPES = ["text", "voice", "audio", "image", "video", "document", "sticker"];
5
+ function invalid() {
6
+ throw new Error("REACTION_RULE_INVALID");
7
+ }
8
+ function exactJid(value, userOnly = false) {
9
+ if (
10
+ typeof value !== "string" ||
11
+ !/^(?:\d{1,30}@(s\.whatsapp\.net|lid|g\.us)|\d{1,30}-\d{1,30}@g\.us)$/.test(value) ||
12
+ canonicalJid(value) !== value ||
13
+ (userOnly && value.endsWith("@g.us"))
14
+ )
15
+ invalid();
16
+ return value;
17
+ }
18
+ function isReactionEmoji(value) {
19
+ return (
20
+ typeof value === "string" &&
21
+ value.length > 0 &&
22
+ value.length <= 32 &&
23
+ /^(?:\p{Extended_Pictographic}|\p{Regional_Indicator}|\p{Emoji_Modifier}|\uFE0F|\u200D|\u20E3|[#*0-9])+$/u.test(
24
+ value,
25
+ ) &&
26
+ /\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20e3/u.test(value) &&
27
+ [...segmenter.segment(value)].length === 1
28
+ );
29
+ }
30
+ function definitionIssues(value) {
31
+ const issues = [];
32
+ const add = (field, code = "invalid") => issues.push({ field, code });
33
+ const object = (item, field, keys) => {
34
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
35
+ add(field);
36
+ return false;
37
+ }
38
+ for (const key of Object.keys(item))
39
+ if (!keys.includes(key)) add(`${field}.${key}`, "unknown_field");
40
+ return true;
41
+ };
42
+ const list = (item, field, allowed) => {
43
+ if (!Array.isArray(item)) return add(field);
44
+ if (!item.length || item.some((entry) => !allowed.includes(entry))) add(field);
45
+ if (item.length > allowed.length) add(field, "too_many");
46
+ if (new Set(item).size !== item.length) add(field, "duplicate");
47
+ };
48
+ if (
49
+ !object(value, "definition", [
50
+ "version",
51
+ "emoji",
52
+ "transitions",
53
+ "originalTypes",
54
+ "senders",
55
+ "action",
56
+ "destination",
57
+ ])
58
+ )
59
+ return issues;
60
+ if (value.version !== 1) add("definition.version");
61
+ if (!isReactionEmoji(value.emoji)) add("definition.emoji");
62
+ list(value.transitions, "definition.transitions", ["add", "change", "remove"]);
63
+ list(value.originalTypes, "definition.originalTypes", TYPES);
64
+ if (object(value.senders, "definition.senders", ["role", "ids"])) {
65
+ if (!["any", "owner", "bot_admin", "group_admin", "member"].includes(value.senders.role))
66
+ add("definition.senders.role");
67
+ const ids = value.senders.ids;
68
+ if (!Array.isArray(ids)) add("definition.senders.ids");
69
+ else {
70
+ if (ids.length > 100) add("definition.senders.ids", "too_many");
71
+ if (new Set(ids).size !== ids.length) add("definition.senders.ids", "duplicate");
72
+ for (const id of ids) {
73
+ try {
74
+ exactJid(id, true);
75
+ } catch {
76
+ add("definition.senders.ids");
77
+ break;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ if (!["stt", "ping"].includes(value.action)) add("definition.action");
83
+ if (
84
+ value.action === "stt" &&
85
+ (!Array.isArray(value.originalTypes) ||
86
+ value.originalTypes.length !== 1 ||
87
+ value.originalTypes[0] !== "voice")
88
+ )
89
+ add("definition.originalTypes", "voice_only");
90
+ if (
91
+ object(value.destination, "definition.destination", ["mode"]) &&
92
+ !["same_chat", "owner_private"].includes(value.destination.mode)
93
+ )
94
+ add("definition.destination.mode");
95
+ if (!issues.length) {
96
+ try {
97
+ structuredClone(value);
98
+ } catch {
99
+ add("definition");
100
+ }
101
+ }
102
+ return issues;
103
+ }
104
+ function validateDefinition(value) {
105
+ if (definitionIssues(value).length) invalid();
106
+ return structuredClone(value);
107
+ }
108
+ function originalType(original) {
109
+ const msg = original?.message || {};
110
+ if (msg.audioMessage) return msg.audioMessage.ptt === true ? "voice" : "audio";
111
+ if (msg.conversation != null || msg.extendedTextMessage) return "text";
112
+ return ["image", "video", "document", "sticker"].find((type) => msg[`${type}Message`]) || null;
113
+ }
114
+ module.exports = { definitionIssues, validateDefinition, exactJid, originalType, isReactionEmoji };
@@ -0,0 +1,76 @@
1
+ // Execution diagnostics stay in RAM and contain no event or provider data.
2
+ const store = require("../db/store.cjs");
3
+ const CODES = new Set([
4
+ "REACTION_CANCELLED",
5
+ "REACTION_TIMEOUT",
6
+ "REACTION_STALE",
7
+ "REACTION_INACCESSIBLE",
8
+ "REACTION_FORBIDDEN",
9
+ "REACTION_STT_DISABLED",
10
+ "REACTION_DELIVERY_REFUSED",
11
+ "REACTION_CAPACITY",
12
+ "REACTION_IDENTITY_INVALID",
13
+ "REACTION_VOICE_REQUIRED",
14
+ "STT_KEY_REQUIRED",
15
+ "STT_OUTPUT_INVALID",
16
+ "MEDIA_AUDIO_INVALID",
17
+ "MEDIA_TOO_LARGE",
18
+ "MEDIA_NOT_AVAILABLE",
19
+ "MEDIA_URL_INVALID",
20
+ "DELIVERED",
21
+ "NO_MATCH",
22
+ "BUSY",
23
+ "ACTION_FAILED",
24
+ "RATE_LIMIT",
25
+ "CAPACITY",
26
+ "EVENT_MISSING",
27
+ "DUPLICATE",
28
+ ]);
29
+ const entries = new Map();
30
+ let globalEntry = null;
31
+ let accountEpoch = 0;
32
+
33
+ function record(ruleId, code, at = Date.now(), expectedEpoch = accountEpoch) {
34
+ if (expectedEpoch !== accountEpoch) return;
35
+ if (ruleId !== null && (typeof ruleId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(ruleId)))
36
+ return;
37
+ const safeCode = CODES.has(code) ? code : "ACTION_FAILED";
38
+ const entry = (ruleId === null ? globalEntry : entries.get(ruleId)) || {
39
+ lastCode: null,
40
+ lastAt: null,
41
+ counts: {},
42
+ };
43
+ entry.lastCode = safeCode;
44
+ entry.lastAt = Number.isSafeInteger(at) && at >= 0 ? at : Date.now();
45
+ entry.counts[safeCode] = (entry.counts[safeCode] || 0) + 1;
46
+ if (ruleId === null) globalEntry = entry;
47
+ else {
48
+ if (!entries.has(ruleId) && entries.size >= 1000) entries.delete(entries.keys().next().value);
49
+ entries.set(ruleId, entry);
50
+ }
51
+ }
52
+
53
+ function get(ruleId) {
54
+ return structuredClone(entries.get(ruleId) || null);
55
+ }
56
+ function global() {
57
+ return structuredClone(globalEntry);
58
+ }
59
+ function clear(ruleId) {
60
+ entries.delete(ruleId);
61
+ }
62
+ function reset() {
63
+ accountEpoch++;
64
+ entries.clear();
65
+ globalEntry = null;
66
+ }
67
+ function epoch() {
68
+ return accountEpoch;
69
+ }
70
+
71
+ store.subscribeReactionChanges((change) => {
72
+ if (change.type === "rule") clear(change.id);
73
+ if (change.account === true) reset();
74
+ });
75
+
76
+ module.exports = { record, get, global, clear, reset, epoch };
@@ -0,0 +1,29 @@
1
+ const store = require("../db/store.cjs");
2
+ const { isLinkedCreds } = require("../utils/linkedCreds.cjs");
3
+ const { normalizedLid, normalizedPn } = require("../stickers/owner.cjs");
4
+
5
+ function readPairedAccount() {
6
+ let creds;
7
+ try { creds = JSON.parse(store.authRead("creds") || "null"); }
8
+ catch { return null; }
9
+ if (!isLinkedCreds(creds)) return null;
10
+ const candidateLid = normalizedLid(creds.me.lid);
11
+ const candidatePn = normalizedPn(creds.me.id);
12
+ const lid = /^\d{1,32}@lid$/.test(candidateLid || "") ? candidateLid : null;
13
+ const pn = /^\d{5,20}@s\.whatsapp\.net$/.test(candidatePn || "") ? candidatePn : null;
14
+ return lid || pn ? { lid, pn } : null;
15
+ }
16
+
17
+ function maskAccount(account) {
18
+ if (!account?.pn) return account ? "WhatsApp account" : null;
19
+ const digits = account.pn.split("@")[0];
20
+ return `+${digits.slice(0, 2)} ••• ••• ••${digits.slice(-2)}`;
21
+ }
22
+
23
+ function accountsMatch(backupAccount, pairedAccount) {
24
+ if (!backupAccount || !pairedAccount) return false;
25
+ if (backupAccount.lid && pairedAccount.lid) return backupAccount.lid === pairedAccount.lid;
26
+ return !backupAccount.lid && !!backupAccount.pn && backupAccount.pn === pairedAccount.pn;
27
+ }
28
+
29
+ module.exports = { readPairedAccount, maskAccount, accountsMatch };