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
package/src/db/store.cjs CHANGED
@@ -19,17 +19,31 @@ const crypto = require("node:crypto");
19
19
  const logger = require("../utils/logger.cjs");
20
20
  const normalizeJid = require("../utils/normalizeJid.cjs");
21
21
  const { db, q, parseJson, sweepExpired, checkpoint, DB_PATH } = require("./db.cjs");
22
+ const { candidateLimit, MAX_IDENTITY_ALIASES } = require("../automation/limits.cjs");
22
23
 
23
24
  const DAY_MS = 24 * 60 * 60 * 1000;
24
25
  const DEFAULT_FORWARD_TTL_DAYS = 30;
26
+ const reactionListeners = new Set();
27
+ function notifyReactionChange(change) {
28
+ for (const listener of reactionListeners) {
29
+ try {
30
+ listener(change);
31
+ } catch {
32
+ logger.warn("[Reactions] policy listener failed");
33
+ }
34
+ }
35
+ }
36
+ function subscribeReactionChanges(listener) {
37
+ reactionListeners.add(listener);
38
+ return () => reactionListeners.delete(listener);
39
+ }
25
40
 
26
41
  // ===================================================================
27
42
  // --- Lifecycle ---
28
43
  // ===================================================================
29
44
  //
30
- // The database is opened the moment db.cjs is required, so there is nothing
31
- // to await. These exist because the rest of the codebase calls them; they now
32
- // do the housekeeping the boot sequence needs: sweep, and report.
45
+ // Database access is lazy; startup prepares it before calling initStore().
46
+ // Direct store use outside startup opens it on the first query.
33
47
 
34
48
  let sweepTimer = null;
35
49
 
@@ -137,10 +151,74 @@ function saveBotSetting(key, value) {
137
151
  `INSERT INTO bot_settings (key, value) VALUES (?, ?)
138
152
  ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
139
153
  ).run(key, JSON.stringify(value ?? null));
154
+ if (["reaction:enabled", "command_permissions", "disabled_commands"].includes(key))
155
+ notifyReactionChange({ type: "policy", key });
140
156
  }
141
157
 
142
158
  function deleteBotSetting(key) {
143
159
  q("DELETE FROM bot_settings WHERE key = ?").run(key);
160
+ notifyReactionChange({ type: "policy" });
161
+ }
162
+
163
+ const EXT_VALUE_MAX_BYTES = 64 * 1024;
164
+ const EXT_MAX_NAMES = 200;
165
+ const EXT_NAME_RE = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
166
+
167
+ function extStoragePrefix(id, kind) {
168
+ return `ext:${id}:${kind}:`;
169
+ }
170
+
171
+ function listBotSettingsByPrefix(prefix) {
172
+ const rows = q("SELECT key, value FROM bot_settings WHERE key >= ? AND key < ?").all(
173
+ prefix,
174
+ `${prefix}\uFFFF`,
175
+ );
176
+ return rows.filter((row) => row.key.startsWith(prefix));
177
+ }
178
+
179
+ function getExtStorage(id, kind, name) {
180
+ if (typeof name !== "string" || !EXT_NAME_RE.test(name)) return undefined;
181
+ const row = q("SELECT value FROM bot_settings WHERE key = ?").get(
182
+ extStoragePrefix(id, kind) + name,
183
+ );
184
+ if (!row) return undefined;
185
+ return parseJson(row.value, null);
186
+ }
187
+
188
+ function setExtStorage(id, kind, name, value) {
189
+ if (typeof name !== "string" || !EXT_NAME_RE.test(name)) {
190
+ throw new Error("invalid extension storage name");
191
+ }
192
+ const encoded = JSON.stringify(value ?? null);
193
+ if (Buffer.byteLength(encoded, "utf8") > EXT_VALUE_MAX_BYTES) {
194
+ throw new Error("extension storage value too large");
195
+ }
196
+ const prefix = extStoragePrefix(id, kind);
197
+ const key = prefix + name;
198
+ const existing = q("SELECT 1 AS found FROM bot_settings WHERE key = ?").get(key);
199
+ if (!existing) {
200
+ if (listBotSettingsByPrefix(prefix).length >= EXT_MAX_NAMES) {
201
+ throw new Error("extension storage name limit");
202
+ }
203
+ }
204
+ saveBotSetting(key, value);
205
+ }
206
+
207
+ function deleteExtStorage(id, kind, name) {
208
+ if (typeof name !== "string" || !EXT_NAME_RE.test(name)) return;
209
+ q("DELETE FROM bot_settings WHERE key = ?").run(extStoragePrefix(id, kind) + name);
210
+ }
211
+
212
+ function listExtStorage(id, kind) {
213
+ const prefix = extStoragePrefix(id, kind);
214
+ return listBotSettingsByPrefix(prefix).map((row) => row.key.slice(prefix.length));
215
+ }
216
+
217
+ function wipeExtStorage(id, kind) {
218
+ const prefix = extStoragePrefix(id, kind);
219
+ for (const row of listBotSettingsByPrefix(prefix)) {
220
+ q("DELETE FROM bot_settings WHERE key = ?").run(row.key);
221
+ }
144
222
  }
145
223
 
146
224
  // ===================================================================
@@ -157,6 +235,7 @@ function saveGroupSettings(groupId, settings) {
157
235
  `INSERT INTO group_settings (group_id, settings) VALUES (?, ?)
158
236
  ON CONFLICT(group_id) DO UPDATE SET settings = excluded.settings`,
159
237
  ).run(groupId, JSON.stringify(settings || {}));
238
+ notifyReactionChange({ type: "chat", chat: groupId });
160
239
  }
161
240
 
162
241
  function getAllGroupSettings() {
@@ -220,8 +299,22 @@ function clearLidMappings() {
220
299
  q("DELETE FROM lid_mapping").run();
221
300
  }
222
301
 
302
+ // Account lifetime (Phase 07.5). Work that started for one linked account
303
+ // captures accountEpoch() and must not write account-scoped state once it has
304
+ // moved. Unlink, logout and backup activation advance it synchronously, before
305
+ // their first await, so a late completion from the previous account is dropped.
306
+ let accountEpochValue = 0;
307
+ function accountEpoch() {
308
+ return accountEpochValue;
309
+ }
310
+ function advanceAccountEpoch() {
311
+ accountEpochValue += 1;
312
+ return accountEpochValue;
313
+ }
314
+
223
315
  /** Drop WhatsApp-derived directory data after unlink / logged-out. */
224
316
  function clearWhatsAppDirectory() {
317
+ clearReactionAccountState();
225
318
  clearGroupDirectory();
226
319
  clearGroupSettings();
227
320
  clearUserMetadata();
@@ -229,6 +322,271 @@ function clearWhatsAppDirectory() {
229
322
  clearAllModerationFlags();
230
323
  }
231
324
 
325
+ // Reaction intake claims contain hashes/times/emoji only, never message bodies.
326
+ const REACTION_LEDGER_CAP = 10_000;
327
+
328
+ function isReactionChatEnabled(chatJid) {
329
+ return Boolean(
330
+ q("SELECT 1 FROM reaction_rules WHERE chat_jid = ? AND enabled = 1 LIMIT 1").get(chatJid),
331
+ );
332
+ }
333
+ function isReactionChatConfigured(chatJid) {
334
+ return Boolean(q("SELECT 1 FROM reaction_rules WHERE chat_jid = ? LIMIT 1").get(chatJid));
335
+ }
336
+
337
+ // Bound trusted alias expansion. Excess/ambiguous aliases fail closed at intake.
338
+ function reactionIdentityAliases(jid) {
339
+ if (jid.endsWith("@g.us")) return [jid];
340
+ const pn = jid.endsWith("@lid") ? getPnForLid(jid) : jid;
341
+ if (!pn) return [jid];
342
+ const rows = q(`SELECT lid FROM lid_mapping WHERE pn = ? LIMIT ${MAX_IDENTITY_ALIASES}`).all(pn);
343
+ return [...new Set([jid, pn, ...rows.map((row) => normalizeJid(row.lid))])];
344
+ }
345
+
346
+ // Hash-only negative lookup state survives restart. Saturation replaces markers
347
+ // with one conservative global block, never with a revived original.
348
+ function invalidateReactionLookup(keys, expiresAt, now, cap = 500) {
349
+ return withImmediateTransaction(() => {
350
+ q("DELETE FROM reaction_invalidations WHERE expires_at <= ?").run(now);
351
+ const global = q(
352
+ "SELECT expires_at FROM reaction_invalidations WHERE invalidation_key='*'",
353
+ ).get();
354
+ const existing = q(
355
+ "SELECT COUNT(*) AS n, MAX(expires_at) AS expiry FROM reaction_invalidations",
356
+ ).get();
357
+ if (!keys || global || existing.n + keys.length > cap) {
358
+ q("DELETE FROM reaction_invalidations").run();
359
+ q("INSERT INTO reaction_invalidations VALUES ('*', ?)").run(
360
+ Math.max(expiresAt, existing.expiry || 0),
361
+ );
362
+ return true;
363
+ } else {
364
+ for (const key of keys)
365
+ q(`INSERT INTO reaction_invalidations VALUES (?, ?)
366
+ ON CONFLICT(invalidation_key) DO UPDATE SET expires_at=MAX(expires_at, excluded.expires_at)`).run(
367
+ key,
368
+ expiresAt,
369
+ );
370
+ }
371
+ return false;
372
+ });
373
+ }
374
+ function isReactionLookupInvalidated(keys, now) {
375
+ return Boolean(
376
+ q(`SELECT 1 FROM reaction_invalidations WHERE expires_at > ?
377
+ AND invalidation_key IN (${sqlIn(["*", ...keys])}) LIMIT 1`).get(now, "*", ...keys),
378
+ );
379
+ }
380
+
381
+ // Cross-tab guard for the global switch. Never in backups or settings export. A
382
+ // missing row on an existing install reads as "0" until the first write.
383
+ const REACTION_AUTOMATION_REVISION_KEY = "reaction:automation-revision";
384
+
385
+ function clearReactionAccountState() {
386
+ withImmediateTransaction(() => {
387
+ q("UPDATE reaction_rules SET enabled = 0").run();
388
+ q("DELETE FROM reaction_events").run();
389
+ q("DELETE FROM reaction_state").run();
390
+ q("DELETE FROM reaction_invalidations").run();
391
+ q("DELETE FROM reaction_executions").run();
392
+ q("DELETE FROM reaction_budgets").run();
393
+ saveBotSetting("reaction:enabled", false);
394
+ saveBotSetting(REACTION_AUTOMATION_REVISION_KEY, crypto.randomUUID());
395
+ });
396
+ notifyReactionChange({ type: "policy", account: true });
397
+ }
398
+
399
+ /** Claim before handoff. Saturation never deletes a live replay key. */
400
+ function claimReactionEvent(
401
+ { eventKey, slotKeys, timestampMs, emoji, expiresAt },
402
+ now,
403
+ details = false,
404
+ ) {
405
+ return withImmediateTransaction(() => {
406
+ q("DELETE FROM reaction_events WHERE expires_at <= ?").run(now);
407
+ q("DELETE FROM reaction_state WHERE expires_at <= ?").run(now);
408
+ if (q("SELECT 1 FROM reaction_events WHERE event_key = ?").get(eventKey)) return null;
409
+ const previous = q(`SELECT slot_key, timestamp_ms, emoji FROM reaction_state
410
+ WHERE slot_key IN (${sqlIn(slotKeys)}) ORDER BY timestamp_ms DESC LIMIT 1`).get(...slotKeys);
411
+ if (previous && timestampMs <= previous.timestamp_ms) return null;
412
+ if (q("SELECT COUNT(*) AS n FROM reaction_events").get().n >= REACTION_LEDGER_CAP) return null;
413
+ if (!previous && q("SELECT COUNT(*) AS n FROM reaction_state").get().n >= REACTION_LEDGER_CAP)
414
+ return null;
415
+ q("INSERT INTO reaction_events (event_key, expires_at) VALUES (?, ?)").run(eventKey, expiresAt);
416
+ q(`INSERT INTO reaction_state (slot_key, timestamp_ms, emoji, expires_at) VALUES (?, ?, ?, ?)
417
+ ON CONFLICT(slot_key) DO UPDATE SET timestamp_ms=excluded.timestamp_ms,
418
+ emoji=excluded.emoji, expires_at=excluded.expires_at`).run(
419
+ previous?.slot_key || slotKeys[0],
420
+ timestampMs,
421
+ emoji,
422
+ expiresAt,
423
+ );
424
+ if (previous?.emoji === emoji) return null;
425
+ const type = !emoji ? "remove" : previous?.emoji ? "change" : "add";
426
+ return details ? { type, previousEmoji: previous?.emoji || "" } : type;
427
+ });
428
+ }
429
+
430
+ // Internal rule writes only; Phase 07c must put authenticated management over
431
+ // these methods. Every edit disables execution and rotates the revision.
432
+ function saveReactionRule(input) {
433
+ const { validateDefinition, exactJid } = require("../automation/rules.cjs");
434
+ if (
435
+ !input ||
436
+ Object.keys(input).some((key) => !["id", "chatJid", "priority", "definition"].includes(key))
437
+ )
438
+ throw new Error("REACTION_RULE_INVALID");
439
+ const id = input.id || crypto.randomUUID();
440
+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(id))
441
+ throw new Error("REACTION_RULE_INVALID");
442
+ const chat = exactJid(input.chatJid);
443
+ const priority = input.priority ?? 0;
444
+ if (!Number.isInteger(priority) || priority < 0 || priority > 1000)
445
+ throw new Error("REACTION_RULE_INVALID");
446
+ const definition = validateDefinition(input.definition);
447
+ q(`INSERT INTO reaction_rules(id,chat_jid,definition,revision,priority) VALUES(?,?,?,?,?)
448
+ ON CONFLICT(id) DO UPDATE SET chat_jid=excluded.chat_jid,definition=excluded.definition,
449
+ revision=excluded.revision,priority=excluded.priority,enabled=0,enabled_at=NULL`).run(
450
+ id,
451
+ chat,
452
+ JSON.stringify(definition),
453
+ crypto.randomUUID(),
454
+ priority,
455
+ );
456
+ saveBotSetting("reaction:revision", crypto.randomUUID());
457
+ notifyReactionChange({ type: "rule", id });
458
+ return getReactionRule(id);
459
+ }
460
+ function getReactionRule(id) {
461
+ return q("SELECT * FROM reaction_rules WHERE id=?").get(id) || null;
462
+ }
463
+ function listReactionRules() {
464
+ return q("SELECT * FROM reaction_rules ORDER BY chat_jid, priority, id COLLATE BINARY").all();
465
+ }
466
+ function setReactionRuleEnabled(id, enabled, now = Date.now()) {
467
+ if (typeof enabled !== "boolean" || !Number.isSafeInteger(now) || now < 0)
468
+ throw new Error("REACTION_RULE_INVALID");
469
+ const rule = getReactionRule(id);
470
+ if (!rule) throw new Error("REACTION_RULE_MISSING");
471
+ if (enabled) require("../automation/rules.cjs").validateDefinition(JSON.parse(rule.definition));
472
+ q("UPDATE reaction_rules SET enabled=?,enabled_at=?,revision=? WHERE id=?").run(
473
+ enabled ? 1 : 0,
474
+ enabled ? now : null,
475
+ crypto.randomUUID(),
476
+ id,
477
+ );
478
+ saveBotSetting("reaction:revision", crypto.randomUUID());
479
+ notifyReactionChange({ type: "rule", id });
480
+ return getReactionRule(id);
481
+ }
482
+ function deleteReactionRule(id) {
483
+ q("DELETE FROM reaction_rules WHERE id=?").run(id);
484
+ saveBotSetting("reaction:revision", crypto.randomUUID());
485
+ notifyReactionChange({ type: "rule", id });
486
+ }
487
+ function getReactionAutomation() {
488
+ const revision = getBotSetting(REACTION_AUTOMATION_REVISION_KEY, "0");
489
+ return {
490
+ enabled: getBotSetting("reaction:enabled", false) === true,
491
+ revision: typeof revision === "string" && revision ? revision : "0",
492
+ };
493
+ }
494
+ /**
495
+ * Set the global switch and rotate its revision in one transaction. With
496
+ * `expectedRevision` the compare and the write share that transaction; a stale
497
+ * value throws REACTION_AUTOMATION_CHANGED and writes nothing. Without it the
498
+ * write is unconditional (internal callers).
499
+ */
500
+ function setReactionAutomationEnabled(enabled, expectedRevision) {
501
+ if (typeof enabled !== "boolean") throw new Error("REACTION_SWITCH_INVALID");
502
+ return withImmediateTransaction(() => {
503
+ if (expectedRevision !== undefined && getReactionAutomation().revision !== expectedRevision)
504
+ throw new Error("REACTION_AUTOMATION_CHANGED");
505
+ saveBotSetting("reaction:enabled", enabled);
506
+ saveBotSetting(REACTION_AUTOMATION_REVISION_KEY, crypto.randomUUID());
507
+ return getReactionAutomation();
508
+ });
509
+ }
510
+ function reactionRulesForChats(chats, { emoji, type, originalType }) {
511
+ if (!chats.length || chats.length > MAX_IDENTITY_ALIASES) return [];
512
+ return q(`WITH rules AS (
513
+ SELECT *, CASE WHEN json_valid(definition) THEN definition ELSE '{}' END AS config
514
+ FROM reaction_rules WHERE enabled=1 AND chat_jid IN (${sqlIn(chats)})
515
+ ) SELECT id,chat_jid,enabled,definition,revision,enabled_at,priority FROM rules
516
+ WHERE json_extract(config,'$.emoji')=?
517
+ AND EXISTS (SELECT 1 FROM json_each(config,'$.transitions') WHERE value=?)
518
+ AND EXISTS (SELECT 1 FROM json_each(config,'$.originalTypes') WHERE value=?)
519
+ ORDER BY priority ASC,id COLLATE BINARY ASC LIMIT ?`).all(
520
+ ...chats,
521
+ emoji,
522
+ type,
523
+ originalType,
524
+ candidateLimit + 1,
525
+ );
526
+ }
527
+ // Strict role lookup deliberately never converts LID digits into phone digits.
528
+ function verifiedUserRoles(ids) {
529
+ if (!ids.length || ids.length > MAX_IDENTITY_ALIASES)
530
+ return { isOwner: false, isBotAdmin: false };
531
+ // Legacy contact merging can populate user_lid/phone_number by matching
532
+ // numeric digits alone. Only the role row's primary JID and authoritative
533
+ // lid_mapping expansion above may establish automation privileges.
534
+ const rows = q(
535
+ `SELECT is_owner,is_admin FROM user_metadata WHERE user_jid IN (${sqlIn(ids)})`,
536
+ ).all(...ids);
537
+ return {
538
+ isOwner: rows.some((row) => row.is_owner === 1),
539
+ isBotAdmin: rows.some((row) => row.is_admin === 1),
540
+ };
541
+ }
542
+ // Nonmatching reactions never perform remote authorization. Matching attempts
543
+ // spend reactor/chat budgets before metadata reads; rule budgets precede actions.
544
+ function spendReactionBudgets(budgets, now) {
545
+ q("DELETE FROM reaction_budgets WHERE expires_at<=?").run(now);
546
+ let added = 0;
547
+ for (const budget of budgets) {
548
+ const row = q("SELECT attempts FROM reaction_budgets WHERE budget_key=?").get(budget.key);
549
+ if (row && row.attempts >= budget.limit) return "RATE_LIMIT";
550
+ if (!row) added++;
551
+ }
552
+ if (q("SELECT COUNT(*) AS n FROM reaction_budgets").get().n + added > REACTION_LEDGER_CAP)
553
+ return "CAPACITY";
554
+ for (const budget of budgets)
555
+ q(`INSERT INTO reaction_budgets VALUES(?,1,?)
556
+ ON CONFLICT(budget_key) DO UPDATE SET attempts=attempts+1`).run(budget.key, now + 60_000);
557
+ return "ADMITTED";
558
+ }
559
+ function admitReactionAttempt(budgets, now) {
560
+ return withImmediateTransaction(() => spendReactionBudgets(budgets, now));
561
+ }
562
+ function claimReactionExecution({ eventKey, ruleKey, actionKey, expiresAt, budgets }, now) {
563
+ return withImmediateTransaction(() => {
564
+ q("DELETE FROM reaction_executions WHERE expires_at<=?").run(now);
565
+ q("DELETE FROM reaction_budgets WHERE expires_at<=?").run(now);
566
+ if (!q("SELECT 1 FROM reaction_events WHERE event_key=? AND expires_at>?").get(eventKey, now))
567
+ return "EVENT_MISSING";
568
+ if (
569
+ q("SELECT 1 FROM reaction_executions WHERE event_key=? OR rule_key=? OR action_key=?").get(
570
+ eventKey,
571
+ ruleKey,
572
+ actionKey,
573
+ )
574
+ )
575
+ return "DUPLICATE";
576
+ if (q("SELECT COUNT(*) AS n FROM reaction_executions").get().n >= REACTION_LEDGER_CAP)
577
+ return "CAPACITY";
578
+ const admitted = spendReactionBudgets(budgets, now);
579
+ if (admitted !== "ADMITTED") return admitted;
580
+ q("INSERT INTO reaction_executions VALUES(?,?,?,?)").run(
581
+ eventKey,
582
+ ruleKey,
583
+ actionKey,
584
+ expiresAt,
585
+ );
586
+ return "CLAIMED";
587
+ });
588
+ }
589
+
232
590
  // ===================================================================
233
591
  // --- Warnings ---
234
592
  // ===================================================================
@@ -613,7 +971,8 @@ function storeLidPnMapping(lid, pn, deviceIndex = 0) {
613
971
  device_index = excluded.device_index,
614
972
  updated_at = excluded.updated_at`,
615
973
  ).run(lid, pn, deviceIndex, Date.now());
616
- logger.debug(`[LID] Stored mapping: ${lid} <-> ${pn}`);
974
+ // The pair is an identifier: sanitized debug log only, never combined.log.
975
+ logger.debugOnly.debug({ lid, pn }, "[LID] Stored mapping");
617
976
  }
618
977
 
619
978
  function storeLidPnMappings(mappings) {
@@ -735,44 +1094,104 @@ function lidLocalPart(value) {
735
1094
  return String(value).split("@")[0].split(":")[0];
736
1095
  }
737
1096
 
738
- /**
739
- * Find the existing user_metadata row for a person named by any mix of JID,
740
- * LID and phone, including the lid_mapping table, so a LID and a phone JID
741
- * of the same person land on one record.
742
- */
1097
+ // Contact writes may reuse a proven primary alias, never a numeric contact match.
743
1098
  function resolveExistingUser(userData) {
744
- const candidates = [];
745
- const add = (value) => {
746
- if (value && !candidates.includes(value)) candidates.push(value);
747
- };
748
- add(userData?.jid);
749
- add(userData?.lid);
750
- add(userData?.phone);
751
- if (userData?.jid) {
752
- add(getPnForLid(userData.jid));
753
- add(getLidForPn(userData.jid));
754
- if (!isLidJid(userData.jid)) add(asPnJid(userData.jid));
1099
+ return resolveRoleUser(userData?.jid);
1100
+ }
1101
+
1102
+ // Bare phones and PN JIDs share a namespace. LID digits never enter it.
1103
+ function roleJid(identifier) {
1104
+ if (typeof identifier !== "string") return null;
1105
+ const raw = identifier.trim();
1106
+ if (!raw) return null;
1107
+ if (!raw.includes("@")) {
1108
+ if (!/^\+?[\d ()-]+$/.test(raw)) return null;
1109
+ const phone = raw.replace(/\D/g, "");
1110
+ return phone ? `${phone}@s.whatsapp.net` : null;
755
1111
  }
756
- if (userData?.lid) {
757
- add(getPnForLid(userData.lid));
758
- add(asLidJid(userData.lid));
1112
+ return normalizeJid(raw);
1113
+ }
1114
+
1115
+ // Mapping writers retain historical rows. Only the newest pair for a PN is
1116
+ // current. Tied conflicting pairs fail closed. Device suffixes are the only
1117
+ // aliases accepted when reading either indexed column.
1118
+ function roleMappingRows(column, jid) {
1119
+ const local = jid.split("@")[0];
1120
+ return q(`SELECT lid, pn, updated_at FROM lid_mapping
1121
+ WHERE ${column} IN (?, ?) OR (${column} >= ? AND ${column} < ?)
1122
+ ORDER BY updated_at DESC`)
1123
+ .all(jid, column === "pn" ? local : jid, `${local}:`, `${local};`)
1124
+ .filter((row) => roleJid(row[column]) === jid);
1125
+ }
1126
+
1127
+ function currentRoleMapping(pn) {
1128
+ const rows = roleMappingRows("pn", pn);
1129
+ const newest = rows[0];
1130
+ if (!newest) return null;
1131
+ const lid = roleJid(newest.lid);
1132
+ if (!lid?.endsWith("@lid")) return null;
1133
+ if (rows.some((row) => row.updated_at === newest.updated_at && roleJid(row.lid) !== lid)) {
1134
+ return null;
759
1135
  }
760
- if (userData?.phone) {
761
- const pnJid = asPnJid(userData.phone);
762
- add(pnJid);
763
- if (pnJid) add(getLidForPn(pnJid));
1136
+ // The normalized LID may itself have device-suffixed historical rows.
1137
+ // Accept the pair only when its latest reverse link agrees as well.
1138
+ const reverse = roleMappingRows("lid", lid);
1139
+ const latest = reverse[0];
1140
+ if (
1141
+ !latest ||
1142
+ roleJid(latest.pn) !== pn ||
1143
+ reverse.some((row) => row.updated_at === latest.updated_at && roleJid(row.pn) !== pn)
1144
+ )
1145
+ return null;
1146
+ return newest;
1147
+ }
1148
+
1149
+ // Shared by role reads/writes and the permission helpers. Secondary contact
1150
+ // columns are deliberately excluded: old digit merges could have populated them.
1151
+ function roleIdentityAliases(identifier) {
1152
+ const jid = roleJid(identifier);
1153
+ if (!jid) return [];
1154
+ if (!jid.endsWith("@lid") && !jid.endsWith("@s.whatsapp.net")) return [jid];
1155
+ if (jid.endsWith("@s.whatsapp.net")) {
1156
+ const pair = currentRoleMapping(jid);
1157
+ const lid = pair && roleJid(pair.lid);
1158
+ return lid?.endsWith("@lid") ? [jid, lid] : [jid];
764
1159
  }
765
- for (const identifier of candidates) {
766
- const found = getUserMetadata(identifier);
767
- if (found) return found;
1160
+ const pair = roleMappingRows("lid", jid)[0];
1161
+ const pn = pair && roleJid(pair.pn);
1162
+ if (!pn?.endsWith("@s.whatsapp.net")) return [jid];
1163
+ const current = currentRoleMapping(pn);
1164
+ return current && roleJid(current.lid) === jid ? [jid, pn] : [jid];
1165
+ }
1166
+
1167
+ function roleUserRows(identifier) {
1168
+ const rows = [];
1169
+ for (const jid of roleIdentityAliases(identifier)) {
1170
+ const exact = userRow(jid);
1171
+ if (exact) rows.push(exact);
1172
+ if (jid.endsWith("@s.whatsapp.net")) {
1173
+ const bare = userRow(jid.split("@")[0]);
1174
+ if (bare) rows.push(bare);
1175
+ }
1176
+ if (!jid.includes("@")) continue;
1177
+ const local = jid.split("@")[0];
1178
+ for (const row of q(`SELECT * FROM user_metadata
1179
+ WHERE user_jid >= ? AND user_jid < ?`).all(`${local}:`, `${local};`)) {
1180
+ if (roleJid(row.user_jid) === jid) rows.push(row);
1181
+ }
768
1182
  }
769
- return null;
1183
+ return rows;
770
1184
  }
771
1185
 
772
1186
  function userRow(jid) {
773
1187
  return q("SELECT * FROM user_metadata WHERE user_jid = ?").get(jid);
774
1188
  }
775
1189
 
1190
+ // Privilege writes must not follow the legacy contact digit-merging path.
1191
+ function resolveRoleUser(identifier) {
1192
+ return rowToUser(roleUserRows(identifier)[0]);
1193
+ }
1194
+
776
1195
  /**
777
1196
  * Save or update user metadata.
778
1197
  *
@@ -787,10 +1206,10 @@ function userRow(jid) {
787
1206
  function saveUserMetadata(userData) {
788
1207
  if (!userData?.jid) return;
789
1208
  const now = Date.now();
790
- const resolved = resolveExistingUser(userData);
791
- const jid =
792
- resolved?.jid ||
793
- (isLidJid(userData.jid) ? userData.jid : asPnJid(userData.jid) || userData.jid);
1209
+ const writesRole = userData.isOwner !== undefined || userData.isAdmin !== undefined;
1210
+ const resolved = writesRole ? null : resolveExistingUser(userData);
1211
+ const jid = resolved?.jid || roleJid(userData.jid);
1212
+ if (!jid) return;
794
1213
  const existing = userRow(jid) || (resolved ? userRow(resolved.jid) : null);
795
1214
 
796
1215
  let phone = userData.phone || existing?.phone_number || null;
@@ -840,6 +1259,22 @@ function saveUserMetadata(userData) {
840
1259
  row.display_name,
841
1260
  row.saved_name,
842
1261
  );
1262
+ if (writesRole) {
1263
+ // Separate PN/LID rows can predate a learned mapping. A revocation must
1264
+ // cover every proven primary alias, or the other row would retain access.
1265
+ const ids = roleUserRows(userData.jid).map((entry) => entry.user_jid);
1266
+ for (const [field, column] of [
1267
+ ["isOwner", "is_owner"],
1268
+ ["isAdmin", "is_admin"],
1269
+ ]) {
1270
+ // A grant belongs to the requested primary identity. Copying it to a
1271
+ // mapped LID would leave an independent grant when that mapping changes.
1272
+ if (userData[field] !== undefined && !bool(userData[field]) && ids.length) {
1273
+ q(`UPDATE user_metadata SET ${column}=0 WHERE user_jid IN (${sqlIn(ids)})`).run(...ids);
1274
+ }
1275
+ }
1276
+ notifyReactionChange({ type: "policy" });
1277
+ }
843
1278
  }
844
1279
 
845
1280
  /**
@@ -939,7 +1374,7 @@ function getUserMetadata(identifier) {
939
1374
  }
940
1375
 
941
1376
  function isUserOwner(identifier) {
942
- return getUserMetadata(identifier)?.isOwner === true;
1377
+ return roleUserRows(identifier).some((row) => row.is_owner === 1);
943
1378
  }
944
1379
 
945
1380
  /**
@@ -947,7 +1382,7 @@ function isUserOwner(identifier) {
947
1382
  * an admin of a WhatsApp group).
948
1383
  */
949
1384
  function isUserBotAdmin(identifier) {
950
- return getUserMetadata(identifier)?.isAdmin === true;
1385
+ return roleUserRows(identifier).some((row) => row.is_admin === 1);
951
1386
  }
952
1387
 
953
1388
  function getAllOwners() {
@@ -978,28 +1413,19 @@ function setUserRole(identifier, role, enabled = true) {
978
1413
  if (!identifier) return null;
979
1414
 
980
1415
  const wanted = String(role).toLowerCase() === "owner" ? "isOwner" : "isAdmin";
981
- const existing = getUserMetadata(identifier);
982
-
983
- // Keep LIDs as LIDs; anything else becomes a PN JID so the roster stays
984
- // comparable with what the permission checks resolve senders to.
985
- let jid = existing?.jid;
986
- if (!jid) {
987
- if (String(identifier).includes("@")) jid = identifier;
988
- else {
989
- const phone = digitsOf(identifier);
990
- jid = phone ? `${phone}@s.whatsapp.net` : identifier;
991
- }
992
- }
1416
+ const jid = roleJid(identifier);
1417
+ if (!jid) return null;
1418
+ const existing = rowToUser(userRow(jid));
993
1419
 
994
1420
  saveUserMetadata({
995
1421
  jid,
996
- lid: existing?.lid || (String(identifier).endsWith("@lid") ? identifier : null),
997
- phone: existing?.phone || digitsOf(identifier),
1422
+ lid: existing?.lid || (jid.endsWith("@lid") ? jid : null),
1423
+ phone: existing?.phone || (jid.endsWith("@s.whatsapp.net") ? digitsOf(jid) : null),
998
1424
  displayName: existing?.displayName || null,
999
1425
  [wanted]: !!enabled,
1000
1426
  });
1001
1427
 
1002
- return getUserMetadata(jid);
1428
+ return rowToUser(userRow(jid));
1003
1429
  }
1004
1430
 
1005
1431
  function updateUserLastSeen(jid) {
@@ -1290,8 +1716,45 @@ function authRemove(key) {
1290
1716
  q("DELETE FROM baileys_auth WHERE key = ?").run(key);
1291
1717
  }
1292
1718
 
1719
+ // One transaction. SQLITE_FULL / SQLITE_BUSY throw and the delete rolls back,
1720
+ // so the rows stay. The session writes `auth:unlink-pending` before calling
1721
+ // this; that row is outside this transaction and survives the rollback.
1293
1722
  function authClearAll() {
1294
- q("DELETE FROM baileys_auth").run();
1723
+ return withImmediateTransaction(() => {
1724
+ q("DELETE FROM baileys_auth").run();
1725
+ });
1726
+ }
1727
+
1728
+ // Set before the credential wipe. `auth:*` is already excluded from backups
1729
+ // (src/db/copy.cjs isSecretBotKey) and from settings export.
1730
+ const UNLINK_PENDING_KEY = "auth:unlink-pending";
1731
+
1732
+ function isUnlinkPending() {
1733
+ return !!q("SELECT 1 AS x FROM bot_settings WHERE key = ?").get(UNLINK_PENDING_KEY);
1734
+ }
1735
+
1736
+ function markUnlinkPending() {
1737
+ saveBotSetting(UNLINK_PENDING_KEY, Date.now());
1738
+ }
1739
+
1740
+ function clearUnlinkPending() {
1741
+ q("DELETE FROM bot_settings WHERE key = ?").run(UNLINK_PENDING_KEY);
1742
+ }
1743
+
1744
+ // One keys.set is one IMMEDIATE transaction. `value == null` deletes the row
1745
+ // (Baileys passes null to remove a key). A throw rolls the whole batch back
1746
+ // and is rethrown unchanged; nothing here logs the key or the payload.
1747
+ function authApply(entries) {
1748
+ if (!Array.isArray(entries)) throw new TypeError("authApply expects an array");
1749
+ return withImmediateTransaction(() => {
1750
+ for (const entry of entries) {
1751
+ if (!entry || typeof entry.key !== "string") {
1752
+ throw new TypeError("authApply entry needs a string key");
1753
+ }
1754
+ if (entry.value == null) authRemove(entry.key);
1755
+ else authWrite(entry.key, entry.value);
1756
+ }
1757
+ });
1295
1758
  }
1296
1759
 
1297
1760
  function hasCredentials() {
@@ -1339,11 +1802,14 @@ function describePeer(jid) {
1339
1802
  savedName: null,
1340
1803
  pushName: null,
1341
1804
  memberCount: null,
1805
+ nameSource: "none",
1342
1806
  };
1343
1807
  }
1344
1808
  if (id.endsWith("@g.us")) {
1345
1809
  const dir = getGroupDirectory(id);
1346
- const label = personName(dir?.subject) || "Group";
1810
+ const subject = personName(dir?.subject);
1811
+ // "Group" stays for older clients. nameSource says it was not a real subject.
1812
+ const label = subject || "Group";
1347
1813
  return {
1348
1814
  jid: id,
1349
1815
  kind: "group",
@@ -1352,6 +1818,7 @@ function describePeer(jid) {
1352
1818
  savedName: null,
1353
1819
  pushName: null,
1354
1820
  memberCount: dir?.participant_count ?? null,
1821
+ nameSource: subject ? "subject" : "none",
1355
1822
  };
1356
1823
  }
1357
1824
  const phone = resolveUserPhone(id);
@@ -1359,6 +1826,11 @@ function describePeer(jid) {
1359
1826
  const savedName = personName(meta?.savedName);
1360
1827
  const pushName = personName(meta?.displayName);
1361
1828
  const phoneLabel = phone ? `+${phone}` : null;
1829
+ let nameSource = "none";
1830
+ if (savedName) nameSource = "saved";
1831
+ else if (pushName) nameSource = "push";
1832
+ else if (phoneLabel) nameSource = "phone";
1833
+ // "Contact" stays for older clients. nameSource says it was not a real name.
1362
1834
  const label = savedName || pushName || phoneLabel || "Contact";
1363
1835
  return {
1364
1836
  jid: id,
@@ -1368,6 +1840,7 @@ function describePeer(jid) {
1368
1840
  savedName,
1369
1841
  pushName,
1370
1842
  memberCount: null,
1843
+ nameSource,
1371
1844
  };
1372
1845
  }
1373
1846
 
@@ -2073,6 +2546,26 @@ function clearAutoDeleteOnUnlink() {
2073
2546
  }
2074
2547
 
2075
2548
  module.exports = {
2549
+ isReactionChatEnabled,
2550
+ isReactionChatConfigured,
2551
+ reactionIdentityAliases,
2552
+ invalidateReactionLookup,
2553
+ isReactionLookupInvalidated,
2554
+ clearReactionAccountState,
2555
+ getReactionAutomation,
2556
+ claimReactionEvent,
2557
+ subscribeReactionChanges,
2558
+ saveReactionRule,
2559
+ listReactionRules,
2560
+ getReactionRule,
2561
+ setReactionRuleEnabled,
2562
+ deleteReactionRule,
2563
+ setReactionAutomationEnabled,
2564
+ reactionRulesForChats,
2565
+ verifiedUserRoles,
2566
+ claimReactionExecution,
2567
+ admitReactionAttempt,
2568
+ REACTION_LEDGER_CAP,
2076
2569
  // Lifecycle
2077
2570
  initStore,
2078
2571
  flushStore,
@@ -2082,6 +2575,12 @@ module.exports = {
2082
2575
  getBotSetting,
2083
2576
  saveBotSetting,
2084
2577
  deleteBotSetting,
2578
+ listBotSettingsByPrefix,
2579
+ getExtStorage,
2580
+ setExtStorage,
2581
+ deleteExtStorage,
2582
+ listExtStorage,
2583
+ wipeExtStorage,
2085
2584
  // Group settings
2086
2585
  getGroupSettings,
2087
2586
  saveGroupSettings,
@@ -2094,6 +2593,8 @@ module.exports = {
2094
2593
  clearGroupSettings,
2095
2594
  clearUserMetadata,
2096
2595
  clearLidMappings,
2596
+ accountEpoch,
2597
+ advanceAccountEpoch,
2097
2598
  clearWhatsAppDirectory,
2098
2599
  // Warnings
2099
2600
  getUserWarnings,
@@ -2135,6 +2636,7 @@ module.exports = {
2135
2636
  getPnForLid,
2136
2637
  getAllLidMappings,
2137
2638
  // User metadata & roles
2639
+ roleIdentityAliases,
2138
2640
  saveUserMetadata,
2139
2641
  rememberSavedName,
2140
2642
  applyContactRecord,
@@ -2179,6 +2681,11 @@ module.exports = {
2179
2681
  authWrite,
2180
2682
  authRemove,
2181
2683
  authClearAll,
2684
+ authApply,
2685
+ UNLINK_PENDING_KEY,
2686
+ isUnlinkPending,
2687
+ markUnlinkPending,
2688
+ clearUnlinkPending,
2182
2689
  hasCredentials,
2183
2690
  isPairedSession,
2184
2691
  resolveUserPhone,