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
@@ -13,20 +13,18 @@ const {
13
13
  clearModerationFlag,
14
14
  listModerationFlags,
15
15
  getModerationFlag,
16
+ accountEpoch,
16
17
  commitModerationDecision,
17
18
  markModerationNotice,
18
19
  markModerationKicked,
19
- getPnForLid,
20
- getLidForPn,
21
- getLidsForPn,
22
20
  } = require("./storage.cjs");
23
- const normalizeJid = require("./normalizeJid.cjs");
24
- const { isLidJid } = normalizeJid;
21
+ const { roleIdentityAliases } = require("../db/store.cjs");
25
22
  const {
26
23
  getSenderCandidatesSync,
27
24
  hasBotPrivilegesSync,
28
25
  isAdminInGroupSync,
29
26
  isBotAdminInGroupSync,
27
+ isBotAdminUserSync,
30
28
  isOwnerJidSync,
31
29
  primePermissions,
32
30
  rosterJidForSync,
@@ -37,7 +35,7 @@ const { unwrapMessage } = require("./messageContent.cjs");
37
35
  const { mediaLabel } = require("./moderationSummary.cjs");
38
36
  const { resolveModerationPolicy, effectivePoints } = require("../services/moderationPolicy.cjs");
39
37
  const logger = require("./logger.cjs");
40
- const { tr } = require("./i18n.cjs");
38
+ const { t } = require("./i18n.cjs");
41
39
 
42
40
  const MAX_POINTS_PER_MESSAGE = 50;
43
41
  const RULE_FEATURE = {
@@ -62,28 +60,7 @@ function commandContextInfo(msg) {
62
60
  }
63
61
 
64
62
  function identityAliases(jid) {
65
- const ids = [];
66
- const add = (value) => {
67
- const norm = normalizeJid(value);
68
- if (norm && !ids.includes(norm)) ids.push(norm);
69
- };
70
- add(jid);
71
- const norm = ids[0];
72
- if (!norm) return ids;
73
- const phones = [];
74
- const addPhone = (value) => {
75
- const phone = normalizeJid(value);
76
- if (!phone || isLidJid(phone) || phones.includes(phone)) return;
77
- phones.push(phone);
78
- };
79
- if (isLidJid(norm)) addPhone(getPnForLid(norm));
80
- else addPhone(norm);
81
- for (const phone of phones) {
82
- add(phone);
83
- add(getLidForPn(phone));
84
- for (const lid of getLidsForPn(phone) || []) add(lid);
85
- }
86
- return ids;
63
+ return roleIdentityAliases(jid);
87
64
  }
88
65
 
89
66
  function targetFromCommand(msg) {
@@ -118,8 +95,8 @@ function isProtectedMember(sock, groupMetadata, candidates) {
118
95
  const botIds = [sock?.user?.id, sock?.user?.lid].filter(Boolean);
119
96
  return (candidates || []).some(
120
97
  (candidate) =>
121
- isOwnerJidSync(candidate) ||
122
- hasBotPrivilegesSync(candidate) ||
98
+ isOwnerJidSync(candidate, groupMetadata) ||
99
+ hasBotPrivilegesSync(candidate, groupMetadata) ||
123
100
  isAdminInGroupSync(groupMetadata, candidate) ||
124
101
  botIds.some((botId) => sameUserSync(candidate, botId)),
125
102
  );
@@ -151,56 +128,41 @@ function ruleNotice({
151
128
  const lines = [];
152
129
  if (rule === "warn") {
153
130
  lines.push(
154
- tr(
155
- `✅ ${mentionTag} has been warned.\n*Reason:* ${detail || ""}`,
156
- `✅ تم توجيه تحذير إلى ${mentionTag}.\n*السبب:* ${detail || ""}`,
157
- ),
131
+ t("bot.moderation.moderationAction.hasBeenWarnedReason", { mentionTag, detail: detail || "" }),
158
132
  );
159
133
  } else {
160
134
  lines.push(mentionTag);
161
135
  if (rule === "link") {
162
136
  lines.push(
163
- tr("Links are not allowed in this group.", "الروابط غير مسموحة في هذه المجموعة."),
137
+ t("bot.moderation.moderationAction.linksAreNotAllowedIn"),
164
138
  );
165
139
  } else if (rule === "spam") {
166
- lines.push(tr("Spam is not allowed in this group.", "الإزعاج غير مسموح في هذه المجموعة."));
140
+ lines.push(t("bot.moderation.moderationAction.spamIsNotAllowedIn"));
167
141
  } else if (rule === "media") {
168
142
  const label = mediaLabel(detail);
169
143
  lines.push(
170
- tr(
171
- `${label} are not allowed in this group.`,
172
- `يُمنع إرسال ${label} في هذه المجموعة.`,
173
- ),
144
+ t("bot.moderation.moderationAction.mediaNotAllowed", { label }),
174
145
  );
175
146
  } else if (rule === "forbidden") {
176
147
  lines.push(
177
- tr(
178
- "Forbidden words are not allowed in this group.",
179
- "الكلمات الممنوعة غير مسموحة في هذه المجموعة.",
180
- ),
148
+ t("bot.moderation.moderationAction.forbiddenWordsAreNotAllowed"),
181
149
  );
182
150
  }
183
151
  }
184
152
  if (count && limit) {
185
- lines.push(tr(`Warnings: ${count}/${limit}`, `الإنذارات: ${count}/${limit}`));
153
+ lines.push(t("bot.moderation.moderationAction.warnings", { count, limit }));
186
154
  }
187
155
  if (announceKick) {
188
- lines.push(tr("The member will be removed.", "سيتم حذف العضو."));
156
+ lines.push(t("bot.moderation.moderationAction.theMemberWillBeRemoved"));
189
157
  }
190
158
  if (announceNeedAdmin) {
191
159
  lines.push(
192
- tr(
193
- "I am not a group admin, so an admin must act.",
194
- "لست مشرفًا في المجموعة، لذلك يجب أن يتصرف أحد المشرفين.",
195
- ),
160
+ t("bot.moderation.moderationAction.iAmNotAGroup"),
196
161
  );
197
162
  }
198
163
  if (announceFlag) {
199
164
  lines.push(
200
- tr(
201
- "The member reached the warning limit. Admins have been notified.",
202
- "بلغ العضو حد الإنذارات. تم إشعار المشرفين.",
203
- ),
165
+ t("bot.moderation.moderationAction.theMemberReachedTheWarning"),
204
166
  );
205
167
  }
206
168
  if (adminTags) lines.push(adminTags);
@@ -228,28 +190,83 @@ function clearMemberModeration(groupId, userId) {
228
190
  clearModerationFlag(groupId, userId);
229
191
  }
230
192
 
193
+ function accountEpochMoved(epoch) {
194
+ if (epoch === accountEpoch()) return false;
195
+ logger.debug("[Moderation] skipped account write after account change");
196
+ return true;
197
+ }
198
+
231
199
  function dismissMemberFlag(groupId, userId) {
232
200
  clearModerationFlag(groupId, userId);
233
201
  }
234
202
 
203
+ /**
204
+ * The `userAdminRequired` rule of the gate that admitted this invocation, on a
205
+ * roster the caller picks.
206
+ *
207
+ * "direct" (default): the dispatcher's rule (resolveSender in
208
+ * middleware/permissions.middleware.js). A bot admin who is not an owner, or an
209
+ * admin of this group. `fromMe` makes the sender an owner there, which is why
210
+ * an owner needs the group role.
211
+ *
212
+ * "nested": the `!group <sub-command>` gate (commands/group.cjs): the same, or
213
+ * an owner (`fromMe` or the owner roster).
214
+ */
215
+ function requesterStillAdmin(meta, candidates, fromMe, rule = "direct") {
216
+ const isOwner = Boolean(fromMe) || candidates.some((candidate) => isOwnerJidSync(candidate, meta));
217
+ const isBotAdmin = !isOwner && candidates.some((candidate) => isBotAdminUserSync(candidate, meta));
218
+ const isGroupAdmin = candidates.some((candidate) => isAdminInGroupSync(meta, candidate));
219
+ return isBotAdmin || isGroupAdmin || (rule === "nested" && isOwner);
220
+ }
221
+
235
222
  /**
236
223
  * Remove a member on WhatsApp and drop their warnings + flag.
237
- * Used by !kick and the panel.
224
+ * Used by !kick, the panel and automatic enforcement.
225
+ *
226
+ * The roster is re-read fresh right before the checks and the remove call, never
227
+ * taken from the caller's earlier snapshot: a member promoted since then stays,
228
+ * and a requester demoted since then cannot kick. No fresh roster, no kick.
229
+ * `opts.requesterCandidates` (manual !kick only) re-checks the requester on that
230
+ * same roster; `opts.requesterFromMe` carries the command's `key.fromMe`.
231
+ * `opts.requesterRule` is the gate that admitted the command: "direct" (the
232
+ * dispatcher, the default) or "nested" (`!group kick`, which also admits an
233
+ * owner). Anything else is treated as "direct".
238
234
  */
239
235
  async function kickGroupMember(sock, opts) {
236
+ const epoch = Number.isInteger(opts.accountEpoch)
237
+ ? opts.accountEpoch
238
+ : Number.isInteger(opts.epoch)
239
+ ? opts.epoch
240
+ : accountEpoch();
240
241
  await primePermissions();
241
242
  const groupId = opts.groupId;
242
243
  if (!groupId?.endsWith("@g.us")) return { kicked: false, error: "not-group" };
243
- const meta = opts.groupMetadata || (await resolveGroupMetadata(sock, groupId));
244
244
  const candidates = (opts.targetCandidates || []).filter(Boolean);
245
245
  if (!candidates.length) return { kicked: false, error: "no-target" };
246
+ const meta = await resolveGroupMetadata(sock, groupId, { fresh: true });
247
+ if (!meta) return { kicked: false, error: "metadata-unavailable" };
248
+ if (opts.requesterCandidates) {
249
+ const requester = opts.requesterCandidates.filter(Boolean);
250
+ const rule = opts.requesterRule === "nested" ? "nested" : "direct";
251
+ // `!group` admits its own account (fromMe) with no identity to match.
252
+ const ownAccount = rule === "nested" && Boolean(opts.requesterFromMe);
253
+ if (
254
+ !ownAccount &&
255
+ (!requester.length || !requesterStillAdmin(meta, requester, opts.requesterFromMe, rule))
256
+ ) {
257
+ return { kicked: false, error: "requester-not-admin" };
258
+ }
259
+ }
246
260
  if (isProtectedMember(sock, meta, candidates)) return { kicked: false, error: "protected" };
247
261
  if (!isBotAdminInGroupSync(meta, sock)) return { kicked: false, error: "bot-not-admin" };
248
262
  const kickJid = rosterJidForSync(meta, candidates) || candidates[0];
263
+ if (accountEpoch() !== epoch) return { kicked: false, error: "stale" };
249
264
  const updated = await sock.groupParticipantsUpdate(groupId, [kickJid], "remove");
250
265
  if (!removalSucceeded(updated)) return { kicked: false, error: "rejected", kickJid };
266
+ if (accountEpochMoved(epoch)) return { kicked: true, kickJid };
251
267
  clearMemberModeration(groupId, candidates[0]);
252
- logger.info({ group: groupId, user: kickJid }, "moderation kicked member");
268
+ logger.info("moderation kicked member");
269
+ logger.debugOnly.info({ group: groupId, user: kickJid }, "moderation kicked member");
253
270
  return { kicked: true, kickJid };
254
271
  }
255
272
 
@@ -329,17 +346,26 @@ function decideOutcome({ policy, immediate, effective, flagWasOpen, repeatPoints
329
346
  }
330
347
 
331
348
  async function performKick(sock, ctx) {
349
+ const epoch = Number.isInteger(ctx.accountEpoch)
350
+ ? ctx.accountEpoch
351
+ : Number.isInteger(ctx.epoch)
352
+ ? ctx.epoch
353
+ : accountEpoch();
332
354
  try {
333
355
  const result = await kickGroupMember(sock, {
334
356
  groupId: ctx.groupId,
335
357
  groupMetadata: ctx.meta,
336
358
  targetCandidates: ctx.candidates,
359
+ epoch,
360
+ accountEpoch: epoch,
337
361
  });
362
+ if (accountEpochMoved(epoch)) return Boolean(result.kicked);
338
363
  if (result.kicked) {
339
364
  markModerationKicked(ctx.groupId, ctx.messageId);
340
365
  return true;
341
366
  }
342
- logger.warn(
367
+ logger.warn({ rule: ctx.rule, error: result.error }, "moderation kick skipped");
368
+ logger.debugOnly.warn(
343
369
  { group: ctx.groupId, user: ctx.mentionJid, rule: ctx.rule, error: result.error },
344
370
  "moderation kick skipped",
345
371
  );
@@ -351,22 +377,22 @@ async function performKick(sock, ctx) {
351
377
  });
352
378
  return false;
353
379
  } catch (err) {
354
- logger.error(
380
+ logger.error({ err, rule: ctx.rule }, "moderation kick failed");
381
+ logger.debugOnly.error(
355
382
  { err, group: ctx.groupId, user: ctx.mentionJid, rule: ctx.rule },
356
383
  "moderation kick failed",
357
384
  );
358
- flagMemberForReview(ctx.groupId, ctx.mentionJid, {
359
- warnCount: ctx.effective,
360
- lastRule: ctx.rule,
361
- reasons: ctx.reasons,
362
- repeatPoints: ctx.repeatPoints,
363
- });
385
+ if (!accountEpochMoved(epoch)) {
386
+ flagMemberForReview(ctx.groupId, ctx.mentionJid, {
387
+ warnCount: ctx.effective,
388
+ lastRule: ctx.rule,
389
+ reasons: ctx.reasons,
390
+ repeatPoints: ctx.repeatPoints,
391
+ });
392
+ }
364
393
  try {
365
394
  await sock.sendMessage(ctx.groupId, {
366
- text: tr(
367
- "I tried to remove the member, but I don't have enough permissions.",
368
- "حاولت حذف العضو ولكني لا أملك صلاحية كافية لذلك.",
369
- ),
395
+ text: t("bot.moderation.moderationAction.iTriedToRemoveThe"),
370
396
  });
371
397
  } catch (noticeErr) {
372
398
  logger.error({ err: noticeErr, group: ctx.groupId }, "moderation kick-failure notice failed");
@@ -380,6 +406,11 @@ async function performKick(sock, ctx) {
380
406
  * Returns { acted, duplicate, points, effective, decision, kicked, flagged }.
381
407
  */
382
408
  async function enforceHits(sock, opts) {
409
+ const epoch = Number.isInteger(opts.accountEpoch)
410
+ ? opts.accountEpoch
411
+ : Number.isInteger(opts.epoch)
412
+ ? opts.epoch
413
+ : accountEpoch();
383
414
  const msg = opts.msg;
384
415
  const groupId = opts.groupId || msg?.key?.remoteJid;
385
416
  if (!groupId?.endsWith("@g.us")) return idleResult();
@@ -410,6 +441,8 @@ async function enforceHits(sock, opts) {
410
441
  (hit) => hit.rule === "link" || hit.rule === "media" || hit.rule === "forbidden",
411
442
  );
412
443
 
444
+ if (accountEpochMoved(epoch)) return idleResult();
445
+
413
446
  const committed = commitModerationDecision(groupId, messageId, () => {
414
447
  const existingEvents = getUserWarnings(groupId, mentionJid);
415
448
  const flag = getModerationFlag(groupId, mentionJid);
@@ -499,6 +532,8 @@ async function enforceHits(sock, opts) {
499
532
  effective: flag?.warn_count || effectivePoints(events, policy, now),
500
533
  reasons: events.map((event) => event?.reason).filter(Boolean),
501
534
  repeatPoints: flag?.repeat_points || 0,
535
+ epoch,
536
+ accountEpoch: epoch,
502
537
  });
503
538
  }
504
539
  return {
@@ -558,16 +593,22 @@ async function enforceHits(sock, opts) {
558
593
  });
559
594
  try {
560
595
  await sock.sendMessage(groupId, { text, mentions: [committed.mentionJid, ...adminJids] });
561
- markModerationNotice(groupId, messageId, committed.mentionJid, {
562
- flagNotice: announceFlag,
563
- at: now,
564
- });
596
+ if (!accountEpochMoved(epoch)) {
597
+ markModerationNotice(groupId, messageId, committed.mentionJid, {
598
+ flagNotice: announceFlag,
599
+ at: now,
600
+ });
601
+ }
565
602
  } catch (err) {
566
603
  logger.error({ err, group: groupId, rule: committed.rule }, "moderation notice failed");
567
604
  }
568
605
  }
569
606
  if (converted) {
570
607
  logger.warn(
608
+ { rule: committed.rule },
609
+ "moderation kick skipped: bot is not a group admin; flagged instead",
610
+ );
611
+ logger.debugOnly.warn(
571
612
  { group: groupId, user: mentionJid, rule: committed.rule },
572
613
  "moderation kick skipped: bot is not a group admin; flagged instead",
573
614
  );
@@ -585,6 +626,8 @@ async function enforceHits(sock, opts) {
585
626
  effective: committed.effective,
586
627
  reasons: committed.reasons,
587
628
  repeatPoints: committed.repeatPoints,
629
+ epoch,
630
+ accountEpoch: epoch,
588
631
  });
589
632
  }
590
633
 
@@ -1,7 +1,7 @@
1
1
  // One builder for the "Active moderation" block. !rules, welcome, and the
2
2
  // panel preview all call this so the wording cannot drift.
3
3
 
4
- const { tr, withLang } = require("./i18n.cjs");
4
+ const { t, withLang } = require("./i18n.cjs");
5
5
  const { resolveModerationPolicy, policyFieldVisibility } = require("../services/moderationPolicy.cjs");
6
6
 
7
7
  const MEDIA_TYPES = ["image", "video", "sticker", "audio"];
@@ -10,13 +10,13 @@ const DELETE_WARN_KICK = ["DELETE", "WARN", "KICK"];
10
10
  function mediaLabel(type) {
11
11
  switch (type) {
12
12
  case "image":
13
- return tr("photos", "الصور");
13
+ return t("bot.moderation.moderationSummary.photos");
14
14
  case "video":
15
- return tr("videos", "الفيديو");
15
+ return t("bot.moderation.moderationSummary.videos");
16
16
  case "audio":
17
- return tr("voice notes", "الصوتيات");
17
+ return t("bot.moderation.moderationSummary.voiceNotes");
18
18
  case "sticker":
19
- return tr("stickers", "الملصقات");
19
+ return t("bot.moderation.moderationSummary.stickers");
20
20
  default:
21
21
  return type;
22
22
  }
@@ -27,15 +27,12 @@ function linkModeLine(antilink) {
27
27
  const allowed = Array.isArray(antilink?.allowed_domains) ? antilink.allowed_domains.length : 0;
28
28
  const blocked = Array.isArray(antilink?.blocked_domains) ? antilink.blocked_domains.length : 0;
29
29
  if (mode === "WHITELIST") {
30
- return tr(
31
- `allow listed domains only (${allowed})`,
32
- `السماح بالنطاقات المدرجة فقط (${allowed})`,
33
- );
30
+ return t("bot.moderation.moderationSummary.allowListedDomainsOnly", { allowed });
34
31
  }
35
32
  if (mode === "BLACKLIST") {
36
- return tr(`block listed domains (${blocked})`, `حظر النطاقات المدرجة (${blocked})`);
33
+ return t("bot.moderation.moderationSummary.blockListedDomains", { blocked });
37
34
  }
38
- return tr("block all links", "حظر كل الروابط");
35
+ return t("bot.moderation.moderationSummary.blockAllLinks");
39
36
  }
40
37
 
41
38
  function forbiddenInfo(settings) {
@@ -91,21 +88,21 @@ function policyFromFeatureAction(action) {
91
88
  }
92
89
 
93
90
  function deleteWarnKickLabel(action) {
94
- if (action === "DELETE") return tr("delete only", "حذف فقط");
95
- if (action === "KICK") return tr("delete and remove the member", "حذف وطرد العضو");
96
- return tr("delete and warn", "حذف وإنذار");
91
+ if (action === "DELETE") return t("bot.moderation.moderationSummary.deleteOnly");
92
+ if (action === "KICK") return t("bot.moderation.moderationSummary.deleteAndRemoveTheMember");
93
+ return t("bot.moderation.moderationSummary.deleteAndWarn");
97
94
  }
98
95
 
99
96
  function renderModerationSummary(settings = {}) {
100
- const lines = [tr("*Active moderation*", "*الإشراف المفعّل*")];
97
+ const lines = [t("bot.moderation.moderationSummary.activeModeration")];
101
98
 
102
99
  if (settings.antilink?.enabled) {
103
100
  const action = deleteWarnKickLabel(featureActionOf(settings, "antilink"));
104
101
  lines.push(
105
- tr(
106
- `• Anti-link: on — ${linkModeLine(settings.antilink)}. Action: ${action}.`,
107
- `• منع الروابط: مفعّل — ${linkModeLine(settings.antilink)}. الإجراء: ${action}.`,
108
- ),
102
+ t("bot.moderation.moderationSummary.antiLinkOnAction", {
103
+ linkMode: linkModeLine(settings.antilink),
104
+ action,
105
+ }),
109
106
  );
110
107
  }
111
108
 
@@ -115,13 +112,10 @@ function renderModerationSummary(settings = {}) {
115
112
  const action = featureActionOf(settings, "antispam");
116
113
  const actionText =
117
114
  action === "KICK"
118
- ? tr("remove the member", "طرد العضو")
119
- : tr("warn", "إنذار");
115
+ ? t("bot.moderation.moderationSummary.removeTheMember")
116
+ : t("bot.moderation.moderationSummary.warn");
120
117
  lines.push(
121
- tr(
122
- `• Anti-spam: on — ${count} messages / ${windowSec}s. Action: ${actionText}.`,
123
- `• مكافحة الإزعاج: مفعّلة — ${count} رسائل / ${windowSec}ث. الإجراء: ${actionText}.`,
124
- ),
118
+ t("bot.moderation.moderationSummary.antiSpamOnMessagesS", { count, windowSec, actionText }),
125
119
  );
126
120
  }
127
121
 
@@ -129,10 +123,10 @@ function renderModerationSummary(settings = {}) {
129
123
  MEDIA_TYPES.includes(type),
130
124
  );
131
125
  if (settings.media_control?.enabled && blocked.length) {
132
- const names = blocked.map(mediaLabel).join(tr(", ", "، "));
126
+ const names = blocked.map(mediaLabel).join(t("bot.moderation.moderationSummary.mediaListSeparator"));
133
127
  const action = deleteWarnKickLabel(featureActionOf(settings, "media"));
134
128
  lines.push(
135
- tr(`• Media: ${names}. Action: ${action}.`, `• الوسائط: ${names}. الإجراء: ${action}.`),
129
+ t("bot.moderation.moderationSummary.mediaAction", { names, action }),
136
130
  );
137
131
  }
138
132
 
@@ -140,61 +134,43 @@ function renderModerationSummary(settings = {}) {
140
134
  if (words.enabled) {
141
135
  const action = deleteWarnKickLabel(featureActionOf(settings, "forbidden"));
142
136
  lines.push(
143
- tr(
144
- `• Forbidden words: ${words.count}. Action: ${action}.`,
145
- `• الكلمات الممنوعة: ${words.count}. الإجراء: ${action}.`,
146
- ),
137
+ t("bot.moderation.moderationSummary.forbiddenWordsAction", { count: words.count, action }),
147
138
  );
148
139
  }
149
140
 
150
141
  const warn = warnConfigOf(settings);
151
142
  const atLimit =
152
143
  warn.action === "FLAG"
153
- ? tr("flag for admin review", "إبلاغ المشرفين للمراجعة")
154
- : tr("remove the member", "طرد العضو");
144
+ ? t("bot.moderation.moderationSummary.flagForAdminReview")
145
+ : t("bot.moderation.moderationSummary.removeTheMember");
155
146
  lines.push(
156
- tr(
157
- `• Warn limit: ${warn.max_warnings}. At the limit: ${atLimit}.`,
158
- `• حد الإنذارات: ${warn.max_warnings}. عند بلوغ الحد: ${atLimit}.`,
159
- ),
147
+ t("bot.moderation.moderationSummary.warnLimitAtTheLimit", { maxWarnings: warn.max_warnings, atLimit }),
160
148
  );
161
149
 
162
150
  const policy = resolveModerationPolicy(settings);
163
151
  const visibility = policyFieldVisibility(policy);
164
152
  if (policy.decay.mode === "expire") {
165
153
  lines.push(
166
- tr(
167
- `• Warnings drop after ${policy.decay.days} days.`,
168
- `• تسقط الإنذارات بعد ${policy.decay.days} يومًا.`,
169
- ),
154
+ t("bot.moderation.moderationSummary.warningsDropAfterDays", { days: policy.decay.days }),
170
155
  );
171
156
  } else if (policy.decay.mode === "step") {
172
157
  lines.push(
173
- tr(
174
- `• Warnings lose one point every ${policy.decay.days} days.`,
175
- `• تفقد الإنذارات نقطة كل ${policy.decay.days} يومًا.`,
176
- ),
158
+ t("bot.moderation.moderationSummary.warningsLoseOnePointEvery", { days: policy.decay.days }),
177
159
  );
178
160
  }
179
161
  if (visibility["flag.notify"]) {
180
162
  const notify =
181
163
  policy.flag.notify === "silent"
182
- ? tr("silent", "بصمت")
183
- : tr("in the group", "في المجموعة");
164
+ ? t("bot.moderation.moderationSummary.silent")
165
+ : t("bot.moderation.moderationSummary.inTheGroup");
184
166
  lines.push(
185
- tr(`• Flag notice: ${notify}.`, `• إشعار الإبلاغ: ${notify}.`),
167
+ t("bot.moderation.moderationSummary.flagNotice", { notify }),
186
168
  );
187
169
  }
188
170
  lines.push(
189
171
  policy.membership === "keep"
190
- ? tr(
191
- "• Leaving or being removed keeps warnings.",
192
- "• المغادرة أو الإزالة تبقي الإنذارات.",
193
- )
194
- : tr(
195
- "• Leaving or being removed clears warnings.",
196
- "• المغادرة أو الإزالة تمسح الإنذارات.",
197
- ),
172
+ ? t("bot.moderation.moderationSummary.leavingOrBeingRemovedKeeps")
173
+ : t("bot.moderation.moderationSummary.leavingOrBeingRemovedClears"),
198
174
  );
199
175
 
200
176
  return lines.join("\n");
@@ -10,7 +10,7 @@
10
10
  // and this only answers "may that sender use something gated at `level`".
11
11
  // The refusal is worded in the language of the message being answered.
12
12
 
13
- const { tr } = require("./i18n.cjs");
13
+ const { t } = require("./i18n.cjs");
14
14
 
15
15
  /**
16
16
  * @param {string} level - MEMBERS | ALL | OWNER_ONLY | ADMINS_ONLY | ADMINS_OWNER
@@ -28,49 +28,28 @@ function evaluatePermissionLevel(level, { isGroup, isOwner, isBotAdmin, isSender
28
28
  return verdict(true, "");
29
29
 
30
30
  case "OWNER_ONLY":
31
- return verdict(
32
- Boolean(isOwner),
33
- tr("🚫 Only the bot owner can use this command.", "🚫 هذا الأمر متاح للمالك فقط."),
34
- );
31
+ return verdict(Boolean(isOwner), t("bot.core.permissionLevel.ownerOnly"));
35
32
 
36
33
  case "ADMINS_ONLY":
37
34
  // Owners and bot-admins can run admin-only commands from anywhere —
38
35
  // useful for the operator pinging the bot privately to manage a group.
39
36
  return isGroup
40
- ? verdict(
41
- Boolean(isSenderAdmin || isOwner),
42
- tr("🚫 Only group admins can use this command.", "🚫 هذا الأمر متاح للمشرفين فقط."),
43
- )
44
- : verdict(
45
- Boolean(isOwner || isBotAdmin),
46
- tr(
47
- "⚠️ This command only works in groups (or for the owner in private).",
48
- "⚠️ هذا الأمر يعمل في المجموعات فقط (أو للمالك في الخاص).",
49
- ),
50
- );
37
+ ? verdict(Boolean(isSenderAdmin || isOwner), t("bot.core.permissionLevel.adminsOnly"))
38
+ : verdict(Boolean(isOwner || isBotAdmin), t("bot.core.permissionLevel.adminsOnlyWrongChat"));
51
39
 
52
40
  case "ADMINS_OWNER":
53
41
  return isGroup
54
- ? verdict(
55
- Boolean(isOwner || isSenderAdmin),
56
- tr(
57
- "🚫 Only group admins and the owner can use this command.",
58
- "🚫 هذا الأمر متاح للمشرفين والمالك فقط.",
59
- ),
60
- )
42
+ ? verdict(Boolean(isOwner || isSenderAdmin), t("bot.core.permissionLevel.adminsOwnerOnly"))
61
43
  : verdict(
62
44
  Boolean(isOwner || isBotAdmin),
63
- tr(
64
- "⚠️ This command only works in groups, or for the owner.",
65
- "⚠️ هذا الأمر يعمل في المجموعات أو للمالك فقط.",
66
- ),
45
+ t("bot.core.permissionLevel.adminsOwnerWrongChat"),
67
46
  );
68
47
 
69
48
  default:
70
49
  // Fail closed: a level nobody knows how to evaluate lets nobody through.
71
50
  return {
72
51
  hasPermission: false,
73
- reason: tr("🚫 Unknown permission level.", "🚫 مستوى الصلاحية غير معروف."),
52
+ reason: t("bot.core.permissionLevel.unknownLevel"),
74
53
  unknownLevel: true,
75
54
  };
76
55
  }