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
@@ -30,7 +30,8 @@
30
30
  // disconnected closed and not retrying. Startable again by hand.
31
31
  // retry_exhausted the retry schedule ran out. Levix keeps running.
32
32
  // logged_out WhatsApp dropped the pairing; credentials were cleared.
33
- // error starting the socket threw.
33
+ // error starting the socket threw, or an unlink could not clear
34
+ // credentials or account data (reason `unlink_incomplete`).
34
35
  //
35
36
  // THE RECONNECT POLICY
36
37
  // --------------------
@@ -50,18 +51,20 @@ import { DisconnectReason } from "@whiskeysockets/baileys";
50
51
  import { createRequire } from "module";
51
52
  import { RETRY_SCHEDULE_MS } from "../config/constants.js";
52
53
  import { bootstrapAdmins, bootstrapOwners } from "../utils/permissions.esm.js";
54
+ import { clearRecentMessages } from "../utils/recentMessageCache.esm.js";
53
55
  import {
54
- clearAuthState,
55
56
  clearAutoDeleteOnUnlink,
56
57
  clearWhatsAppDirectory,
57
58
  deleteAllChatHistories,
58
59
  deleteQrCode,
60
+ advanceAccountEpoch,
59
61
  isPairedSession,
60
62
  pauseAllSchedules,
61
63
  saveQrCode,
62
64
  } from "../utils/storage.esm.js";
63
- import { classifyDisconnect, handleConnectionOpen } from "./connection.js";
65
+ import { classifyDisconnect, describeCloseError, handleConnectionOpen } from "./connection.js";
64
66
  import { setupEventListeners } from "./events.js";
67
+ import { disposeReactionIntake } from "../automation/reactions.js";
65
68
  import {
66
69
  createProxyAgents,
67
70
  describeProxyFailure,
@@ -73,41 +76,55 @@ import { createWhatsAppSocket, groupMetadataCache } from "./socket.js";
73
76
 
74
77
  const require = createRequire(import.meta.url);
75
78
  const logger = require("../utils/logger.cjs");
79
+ const store = require("../db/store.cjs");
80
+ const consent = require("../legal/consent.cjs");
81
+
82
+ const UNLINK_INCOMPLETE_DETAIL =
83
+ "Unlink did not finish: the stored WhatsApp credentials could not be deleted. " +
84
+ "Press Unlink again to retry.";
85
+
86
+ /**
87
+ * How often a session waiting for the Terms re-reads the acceptance record.
88
+ * `levix terms` writes it from another process, and this is how a running
89
+ * Levix notices without a restart.
90
+ */
91
+ const CONSENT_POLL_MS = 5000;
76
92
 
77
93
  function clearAccountScopedState() {
94
+ // In-flight one-off deliveries compare this generation and leave a paused
95
+ // job paused instead of writing sent or failed after the account is gone.
96
+ require("../../scheduler.cjs").bumpScheduleGeneration();
78
97
  clearWhatsAppDirectory();
79
98
  deleteAllChatHistories();
80
99
  pauseAllSchedules();
81
100
  bootstrapOwners([]);
82
101
  bootstrapAdmins([]);
83
102
 
84
- try {
85
- require("../utils/memory.cjs").clearAllMemoryFiles();
86
- } catch (error) {
87
- logger.warn({ err: error }, "[Session] failed to clear AI memory after unlink");
88
- }
103
+ // Persistent account data is required cleanup. Any failure keeps unlink
104
+ // pending so the next attempt repeats the whole cleanup before pairing.
105
+ require("../utils/memory.cjs").clearAllMemoryFiles();
89
106
  try {
90
107
  require("../commands/gemini.cjs").clearAllContextBuffers();
91
108
  } catch (error) {
92
109
  logger.warn({ err: error }, "[Session] failed to clear AI context buffers after unlink");
93
110
  }
94
- try {
95
- // Same boundary as the memory wipe above: the next phone that pairs must
96
- // not inherit this account's stickers, packs, or files.
97
- require("../stickers/library.cjs").clearAll();
98
- } catch (error) {
99
- logger.warn({ err: error }, "[Session] failed to clear the sticker library after unlink");
100
- }
111
+ // Same boundary as the memory wipe above: the next phone that pairs must
112
+ // not inherit this account's stickers, packs, or files.
113
+ require("../stickers/library.cjs").clearAll();
101
114
  try {
102
115
  groupMetadataCache.flushAll();
103
116
  } catch {}
104
117
  try {
105
- // Copies of deleted messages and the counters are account-derived; the
106
- // rules themselves are operator configuration and stay.
107
- clearAutoDeleteOnUnlink();
108
- } catch (error) {
109
- logger.warn({ err: error }, "[Session] failed to clear auto-delete copies after unlink");
110
- }
118
+ clearRecentMessages();
119
+ } catch {}
120
+ // Copies of deleted messages and the counters are account-derived; the
121
+ // rules themselves are operator configuration and stay.
122
+ clearAutoDeleteOnUnlink();
123
+ // Second advance. Logout and a logged-out close already moved the epoch
124
+ // before their first await. Work that sampled that value during the logout
125
+ // wait, then finishes after this wipe, must still drop its write.
126
+ advanceAccountEpoch();
127
+ require("../extensions/host.cjs").host.accountReset("unlink");
111
128
  }
112
129
 
113
130
  // Baileys' `end()` awaits `ws.close()`, which waits for the socket's own
@@ -174,6 +191,8 @@ export const SESSION_STATES = Object.freeze({
174
191
  RETRY_EXHAUSTED: "retry_exhausted",
175
192
  LOGGED_OUT: "logged_out",
176
193
  ERROR: "error",
194
+ // The installation has no valid Terms acceptance. No socket exists.
195
+ CONSENT_REQUIRED: "consent_required",
177
196
  });
178
197
 
179
198
  const S = SESSION_STATES;
@@ -188,6 +207,14 @@ const BUSY_STATES = new Set([
188
207
  S.PAUSED,
189
208
  ]);
190
209
 
210
+ /**
211
+ * States that pause while offline and start again when the network returns.
212
+ * A start was asked for in each of them: it is running, waiting for consent,
213
+ * or ran out of retries. Idle, stopped, unlinked and failed sessions keep
214
+ * their state, so a network change never starts a session by itself.
215
+ */
216
+ const NETWORK_RESUME_STATES = new Set([...BUSY_STATES, S.CONSENT_REQUIRED, S.RETRY_EXHAUSTED]);
217
+
191
218
  /** What the dashboard's status pill has always been told. Kept stable. */
192
219
  function legacyStatus(state, hasQr) {
193
220
  if (state === S.CONNECTED) return "Connected";
@@ -210,6 +237,7 @@ export class WhatsAppSession {
210
237
  #since = Date.now();
211
238
  #socket = null;
212
239
  #clearAll = null;
240
+ #fenceAuth = null;
213
241
 
214
242
  // Bumped for every socket. Events carrying an older number are ignored, which
215
243
  // is how a replaced socket stops being able to affect anything.
@@ -223,6 +251,27 @@ export class WhatsAppSession {
223
251
  // creating a second socket.
224
252
  #starting = null;
225
253
 
254
+ // Set when an in-flight #open was overtaken and the latest intent is still
255
+ // "be running". The start() that was waiting on that attempt consumes it.
256
+ #resumeAfterStart = false;
257
+
258
+ // Generation at which stop or shutdown recorded intent. A resume must not
259
+ // start when this is newer than the overtaken attempt.
260
+ #terminalGeneration = 0;
261
+
262
+ // Per-socket disposer from setupEventListeners. A test fake may return
263
+ // undefined; only a function is stored.
264
+ #listenerDisposers = new WeakMap();
265
+
266
+ // A logout() already in flight. Refuses concurrent start() calls and
267
+ // deduplicates concurrent unlinks while teardown is awaited.
268
+ #loggingOut = null;
269
+
270
+ // The credential wipe did not finish. Paired with bot_settings
271
+ // `auth:unlink-pending`: start stays refused until a later logout() deletes
272
+ // the credentials. The flag also covers a marker that could not be written.
273
+ #unlinkFailed = false;
274
+
226
275
  // True while this attempt is an unpaired pairing attempt that has not yet
227
276
  // been scanned. Its closes are terminal by design.
228
277
  #pairing = false;
@@ -246,6 +295,11 @@ export class WhatsAppSession {
246
295
  #isOnline = true;
247
296
  #wasActiveBeforeOffline = false;
248
297
 
298
+ // Re-reads the acceptance record while the session waits in
299
+ // consent_required. Deliberately ref'd, like the retry timer: in headless it
300
+ // is the only thing keeping the process up until somebody accepts.
301
+ #consentTimer = null;
302
+
249
303
  constructor({
250
304
  createSocket = createWhatsAppSocket,
251
305
  attachListeners = setupEventListeners,
@@ -253,8 +307,9 @@ export class WhatsAppSession {
253
307
  // The wipe of last resort. A socket hands us its own clearAll(), but a
254
308
  // session that is disconnected — 403, 405, retries exhausted, or simply
255
309
  // restarted — has no socket to ask, and that is exactly when an operator
256
- // wants to unlink and pair a different account.
257
- clearCredentials = clearAuthState,
310
+ // wants to unlink and pair a different account. Looked up on the store at
311
+ // call time so a retry sees the live deleter.
312
+ clearCredentials = () => store.authClearAll(),
258
313
  initializeScheduledJobs = null,
259
314
  stopScheduledJobs = null,
260
315
  // Read at socket-creation time, never cached at import: the operator can
@@ -265,9 +320,16 @@ export class WhatsAppSession {
265
320
  emit = () => {},
266
321
  retryDelaysMs = RETRY_SCHEDULE_MS,
267
322
  log = logger,
323
+ // Detail that belongs only in the sanitized debug log.
324
+ debugLog = logger.debugOnly,
268
325
  pairingCodeDelayMs = 1500,
269
326
  isLinked = isPairedSession,
270
327
  clearDirectory = clearAccountScopedState,
328
+ // Asked before every socket. `{ ok, reason }`; anything but ok === true
329
+ // keeps the session in consent_required. Injectable so the state machine
330
+ // can be tested without a database.
331
+ checkConsent = () => consent.consentStatus(),
332
+ consentPollMs = CONSENT_POLL_MS,
271
333
  } = {}) {
272
334
  this.createSocket = createSocket;
273
335
  this.attachListeners = attachListeners;
@@ -282,7 +344,10 @@ export class WhatsAppSession {
282
344
  this.clearCredentials = clearCredentials;
283
345
  this.retryDelaysMs = retryDelaysMs;
284
346
  this.log = log;
347
+ this.debugLog = debugLog;
285
348
  this.pairingCodeDelayMs = pairingCodeDelayMs;
349
+ this.checkConsent = checkConsent;
350
+ this.consentPollMs = consentPollMs;
286
351
  }
287
352
 
288
353
  // -------------------------------------------------------------------------
@@ -329,14 +394,20 @@ export class WhatsAppSession {
329
394
  attempt: this.#attempt,
330
395
  maxAttempts: this.retryDelaysMs.length,
331
396
  nextRetryAt: this.#nextRetryAt,
332
- canStart: !BUSY_STATES.has(this.#state) && !this.#shuttingDown,
397
+ canStart:
398
+ !BUSY_STATES.has(this.#state) &&
399
+ !this.#loggingOut &&
400
+ !this.#shuttingDown &&
401
+ !this.#incompleteUnlink(),
333
402
  canStop: BUSY_STATES.has(this.#state),
334
403
  // Not "is it connected": a pairing that WhatsApp has refused (403, 405)
335
404
  // leaves dead credentials behind, and unlinking is the only way out of
336
405
  // it. The one state with nothing to unlink is the one that just did.
337
- canUnlink: this.#state !== S.LOGGED_OUT && !this.#shuttingDown,
406
+ // ERROR unlink_incomplete stays unlinkable: that is the retry.
407
+ canUnlink: this.#state !== S.LOGGED_OUT && !this.#loggingOut && !this.#shuttingDown,
338
408
  // Finished WhatsApp pairing — resume/connect, do not offer QR/pair.
339
- linked: this.#state !== S.LOGGED_OUT && this.isLinked(),
409
+ // An unfinished wipe must not claim the surviving credentials are usable.
410
+ linked: this.#state !== S.LOGGED_OUT && !this.#incompleteUnlink() && this.isLinked(),
340
411
  // Redacted — never the password. Null when the socket is direct.
341
412
  proxy: this.#proxyLabel,
342
413
  // True when the saved proxy settings differ from what the live socket was
@@ -344,6 +415,7 @@ export class WhatsAppSession {
344
415
  // answer crosses the wire, never the fingerprint it was computed from.
345
416
  proxyChanged: this.#proxyIsStale(),
346
417
  connected: this.#state === S.CONNECTED,
418
+ consentRequired: this.#state === S.CONSENT_REQUIRED,
347
419
  isOnline: this.#isOnline,
348
420
  terminal,
349
421
  hasQr: !!this.#qr,
@@ -369,6 +441,7 @@ export class WhatsAppSession {
369
441
  * When offline (false):
370
442
  * - Pauses active connection attempts and cancels pending retry timers.
371
443
  * - Transitions to S.PAUSED without exhausting retries.
444
+ * - A session in no NETWORK_RESUME_STATES state keeps its state.
372
445
  *
373
446
  * When online (true):
374
447
  * - Restores connection if it was active before going offline or currently paused.
@@ -379,13 +452,26 @@ export class WhatsAppSession {
379
452
  if (this.#isOnline === isOnline) return this.getState();
380
453
  this.#isOnline = isOnline;
381
454
 
455
+ if (!isOnline && !NETWORK_RESUME_STATES.has(this.#state)) {
456
+ // Nothing was asked to run. Pausing here made network restore call
457
+ // start(), which opened a pairing socket or the Terms gate on its own.
458
+ this.#wasActiveBeforeOffline = false;
459
+ this.log.warn("[Session] Device is offline");
460
+ return this.getState();
461
+ }
462
+
382
463
  if (!isOnline) {
383
464
  this.log.warn("[Session] Device is offline — pausing WhatsApp connection and retries");
384
465
  this.#wasActiveBeforeOffline = BUSY_STATES.has(this.#state) || this.#state === S.PAUSED;
385
466
  this.#cancelRetry();
386
467
 
468
+ // #destroySocket() bumps the generation only when a socket exists.
469
+ // createSocket can still be in flight with #socket null; that attempt
470
+ // has to become stale too, or #open would adopt it after the pause.
387
471
  if (this.#socket) {
388
472
  await this.#destroySocket();
473
+ } else {
474
+ this.#generation += 1;
389
475
  }
390
476
  this.#transition(S.PAUSED, {
391
477
  reason: "offline",
@@ -409,26 +495,43 @@ export class WhatsAppSession {
409
495
  }
410
496
 
411
497
  /**
412
- * Bring the session up. Idempotent: if a socket exists or is being made, this
413
- * returns the state it is already in and creates nothing.
498
+ * Bring the session up. Idempotent while a socket exists or one is being
499
+ * made, except when that attempt was overtaken and the session should still
500
+ * be running: then this opens one replacement.
414
501
  */
415
502
  async start({ reason = "manual", method, phone } = {}) {
416
503
  if (this.#shuttingDown) return this.getState();
417
504
 
505
+ if (this.#loggingOut) {
506
+ await this.#loggingOut.catch(() => {});
507
+ return this.getState();
508
+ }
509
+
510
+ // Before pairing intent and before #open. A marker left by a failed wipe,
511
+ // including one written by a previous process, must not open a socket.
512
+ if (this.#refuseIncompleteUnlink()) return this.getState();
513
+
418
514
  if (this.#state === S.PAUSED && !this.#isOnline) {
419
515
  return this.getState();
420
516
  }
421
517
 
518
+ let resume = false;
422
519
  if (this.#starting) {
423
520
  await this.#starting.catch(() => {});
424
- return this.getState();
521
+ resume = this.#resumeAfterStart;
522
+ this.#resumeAfterStart = false;
523
+ if (!resume || this.#shuttingDown || this.#loggingOut || !this.#isOnline) {
524
+ return this.getState();
525
+ }
425
526
  }
426
- if (BUSY_STATES.has(this.#state) && this.#state !== S.PAUSED) return this.getState();
527
+ if (!resume && BUSY_STATES.has(this.#state) && this.#state !== S.PAUSED) return this.getState();
427
528
 
428
529
  // A known pairing reuses the stored session. Do not request a pairing code.
429
530
  if (this.isLinked()) {
430
531
  this.#pairingIntent = { method: "qr", phone: null };
431
- } else {
532
+ } else if (this.#state !== S.CONSENT_REQUIRED || method != null) {
533
+ // A Start pressed while waiting for consent must not replace an earlier
534
+ // pairing-code request with the default QR choice.
432
535
  this.#pairingIntent = parseStartOptions({ method, phone });
433
536
  }
434
537
 
@@ -452,11 +555,13 @@ export class WhatsAppSession {
452
555
  */
453
556
  async stop({ reason = "manual", state = S.IDLE, detail = null } = {}) {
454
557
  this.#cancelRetry();
558
+ this.#stopConsentWatch();
455
559
  this.#attempt = 0;
456
560
 
457
- // Wait for an in-flight start, or we would tear down a socket that has not
458
- // been assigned yet and then have it appear behind us.
459
- if (this.#starting) await this.#starting.catch(() => {});
561
+ // Intent before the wait. Otherwise a resume waiting on the same attempt
562
+ // can install a socket after stop has already looked and found none.
563
+ await this.#settleStarts();
564
+ if (this.#loggingOut) await this.#loggingOut.catch(() => {});
460
565
 
461
566
  // Again after the await: a close that landed while we were waiting is
462
567
  // entitled to schedule a retry, and it would outlive this stop.
@@ -466,6 +571,9 @@ export class WhatsAppSession {
466
571
  await this.#destroySocket();
467
572
  this.#clearQr();
468
573
  this.#pairing = false;
574
+ // A failed unlink stays in ERROR. Idle would look startable while the
575
+ // credentials and the marker are still there.
576
+ if (this.#incompleteUnlink()) return this.#failUnlink();
469
577
  this.#transition(state, { reason, detail });
470
578
  return this.getState();
471
579
  }
@@ -475,21 +583,97 @@ export class WhatsAppSession {
475
583
  * then clear the credentials whether or not that call got through.
476
584
  */
477
585
  async logout() {
478
- // A start that is still creating its socket has to finish first: otherwise
479
- // #open() assigns a live socket after this method has already declared the
480
- // session logged out, and the account is unlinked with a connection still
481
- // running.
586
+ if (this.#loggingOut) {
587
+ await this.#loggingOut;
588
+ return this.getState();
589
+ }
590
+ // The snapshot is taken after this promise settles. #runLogout resolves
591
+ // while the flag is still set, and canUnlink is false for that whole time.
592
+ let release = () => {};
593
+ let reject = () => {};
594
+ const done = new Promise((resolve, fail) => {
595
+ release = resolve;
596
+ reject = fail;
597
+ });
598
+ // The initiating caller gets the rejection below; concurrent callers share
599
+ // it through done. A single caller must not leave an unhandled rejection.
600
+ done.catch(() => {});
601
+ this.#loggingOut = done;
602
+ try {
603
+ await this.#runLogout();
604
+ } catch (error) {
605
+ reject(error);
606
+ throw error;
607
+ } finally {
608
+ this.#loggingOut = null;
609
+ release();
610
+ }
611
+ return this.getState();
612
+ }
613
+
614
+ /** Boot recovery before any pairing is resumed. Returns whether unlink still blocks start. */
615
+ async recoverPendingUnlink() {
616
+ let pending;
617
+ try {
618
+ pending = store.isUnlinkPending();
619
+ } catch (error) {
620
+ this.log.error({ err: error }, "[Session] could not read the pending-unlink marker at boot");
621
+ this.#failUnlink();
622
+ return true;
623
+ }
624
+ if (!pending) return false;
625
+ try {
626
+ await this.logout();
627
+ } catch (error) {
628
+ if (error.code !== "UNLINK_NOT_STARTED") throw error;
629
+ // The saved intent still blocks pairing even if storage refuses this retry.
630
+ this.#failUnlink();
631
+ }
632
+ return this.#refuseIncompleteUnlink();
633
+ }
634
+
635
+ async #runLogout() {
636
+ // Persist intent before changing the epoch, timers or socket. If this fails,
637
+ // restart may safely resume the pairing: WhatsApp was never asked to log out.
638
+ const retry = this.#incompleteUnlink();
639
+ try {
640
+ store.markUnlinkPending();
641
+ } catch (cause) {
642
+ this.log.error({ err: cause }, "[Session] could not start unlink");
643
+ const error = new Error(
644
+ "Unlink could not start: Levix could not save its progress. " +
645
+ "Check free storage and try again.",
646
+ { cause },
647
+ );
648
+ error.code = "UNLINK_NOT_STARTED";
649
+ throw error;
650
+ }
651
+
652
+ // Before the first await, so work already running for this account drops
653
+ // its account-scoped writes. Wait for an in-flight start without bumping
654
+ // the generation, so that start adopts its socket and logout tears it down.
655
+ this.#resumeAfterStart = false;
656
+ advanceAccountEpoch();
482
657
  this.#cancelRetry();
658
+ this.#stopConsentWatch();
483
659
  if (this.#starting) await this.#starting.catch(() => {});
484
660
 
485
661
  const sock = this.#socket;
486
662
  const clearAll = this.#clearAll;
663
+ const fence = this.#fenceAuth;
664
+ this.#socket = null;
665
+ this.#clearAll = null;
666
+ this.#fenceAuth = null;
667
+ this.#pairing = false;
487
668
 
488
669
  // Stale from here on: whatever the socket emits while logging out is not
489
670
  // allowed to schedule anything.
490
671
  this.#generation += 1;
491
672
  this.#cancelRetry();
492
673
  this.#attempt = 0;
674
+ // Reaction work for this socket must stop now, not after the logout wait below.
675
+ if (sock) disposeReactionIntake(sock);
676
+ this.#fence(fence);
493
677
 
494
678
  if (sock) {
495
679
  try {
@@ -507,30 +691,34 @@ export class WhatsAppSession {
507
691
  } catch {}
508
692
  }
509
693
 
510
- // clearAll() belongs to the socket that was alive; when there wasn't one,
511
- // the store-level wipe does the same job.
512
- try {
513
- await (clearAll ? clearAll() : this.clearCredentials?.());
514
- } catch (error) {
515
- this.log.error({ err: error }, "[Session] failed to clear credentials");
694
+ // If any socket was installed while teardown was awaited, fence and tear
695
+ // it down before and after wiping credentials.
696
+ if (this.#starting) await this.#starting.catch(() => {});
697
+ if (this.#socket || this.#fenceAuth) {
698
+ await this.#destroySocket();
699
+ }
700
+
701
+ // The marker commits before the credential transaction, so a rolled-back
702
+ // delete cannot erase it. The first attempt uses the socket's clearAll.
703
+ // A retry uses the store wipe: that clearAll belongs to a socket we stopped.
704
+ const wiped = await this.#wipeCredentials(clearAll, { retry });
705
+
706
+ if (this.#starting) await this.#starting.catch(() => {});
707
+ if (this.#socket || this.#fenceAuth) {
708
+ await this.#destroySocket();
516
709
  }
517
710
 
518
711
  this.#socket = null;
519
712
  this.#clearAll = null;
713
+ this.#fenceAuth = null;
520
714
  this.#pairing = false;
521
715
  this.#clearQr();
522
716
  this.#stopJobs();
523
- try {
524
- this.clearDirectory?.();
525
- } catch (error) {
526
- this.log.warn({ err: error }, "[Session] failed to clear WhatsApp directory after unlink");
527
- }
528
-
529
- this.#transition(S.LOGGED_OUT, {
717
+ if (!wiped) return this.#failUnlink();
718
+ return this.#finishUnlink({
530
719
  reason: "unlinked",
531
720
  detail: "The WhatsApp account was unlinked. Start a session to pair a new one.",
532
721
  });
533
- return this.getState();
534
722
  }
535
723
 
536
724
  /**
@@ -552,7 +740,9 @@ export class WhatsAppSession {
552
740
  async shutdown() {
553
741
  this.#shuttingDown = true;
554
742
  this.#cancelRetry();
555
- if (this.#starting) await this.#starting.catch(() => {});
743
+ this.#stopConsentWatch();
744
+ await this.#settleStarts();
745
+ if (this.#loggingOut) await this.#loggingOut.catch(() => {});
556
746
  this.#cancelRetry();
557
747
  await this.#destroySocket();
558
748
  // A code left in the database would be served by GET /qr on the next boot,
@@ -566,6 +756,16 @@ export class WhatsAppSession {
566
756
  // -------------------------------------------------------------------------
567
757
 
568
758
  async #open({ reason }) {
759
+ // Before the Terms gate. The retry timer calls #open() directly, and an
760
+ // unfinished wipe must not create a socket on any of those paths.
761
+ if (this.#refuseIncompleteUnlink()) return;
762
+
763
+ // The Terms gate (ADR-006). First, before the offline check and before any
764
+ // socket: start(), the retry timer, network restore, !restart and the
765
+ // panel all arrive here, so this is the one place a missing acceptance can
766
+ // be enforced on every path. Pairing credentials are not touched.
767
+ if (!this.#consentAllows()) return;
768
+
569
769
  if (!this.#isOnline) {
570
770
  this.#wasActiveBeforeOffline = true;
571
771
  this.#transition(S.PAUSED, {
@@ -579,9 +779,9 @@ export class WhatsAppSession {
579
779
  this.#clearQr();
580
780
  this.#transition(S.STARTING, { reason });
581
781
 
582
- // Anything that invalidates this attempt — stop, logout, shutdown — bumps
583
- // the generation. Creating a socket is asynchronous, so the attempt has to
584
- // recheck that it is still the current one when it comes back.
782
+ // Stop and shutdown bump the generation before they wait. Offline does too.
783
+ // Logout does not: it adopts this socket, then tears it down. Creating a
784
+ // socket is asynchronous, so the attempt rechecks when it comes back.
585
785
  const startedAt = this.#generation;
586
786
 
587
787
  // Read per attempt, so changing the proxy and pressing Reconnect is all it
@@ -610,48 +810,61 @@ export class WhatsAppSession {
610
810
  this.#proxyConfig = proxyConfig;
611
811
 
612
812
  let created;
813
+ let createError = null;
613
814
  try {
614
815
  created = await this.createSocket({
615
816
  proxy,
616
817
  pairingCode: !this.isLinked() && this.#pairingIntent.method === "pairing",
617
818
  });
618
819
  } catch (error) {
619
- this.log.error({ err: error }, "[Session] failed to create the WhatsApp socket");
820
+ createError = error;
821
+ }
822
+
823
+ if (this.#shuttingDown || this.#generation !== startedAt) {
824
+ // Overtaken, including by offline while createSocket was still running.
825
+ // Adopt nothing and do not turn a pause into ERROR. A rejection has no
826
+ // socket to throw away.
827
+ if (created?.sock) {
828
+ this.log.warn("[Session] discarding a socket whose start was overtaken");
829
+ this.#fence(created.fence);
830
+ this.#detach(created.sock);
831
+ try {
832
+ await withTimeout(created.sock?.end?.(undefined), SOCKET_CLOSE_TIMEOUT_MS);
833
+ } catch {}
834
+ }
835
+ this.#noteOvertakenStart(startedAt);
836
+ return;
837
+ }
838
+
839
+ if (createError) {
840
+ this.log.error({ err: createError }, "[Session] failed to create the WhatsApp socket");
620
841
  this.#transition(S.ERROR, {
621
842
  reason: "socket_failed",
622
843
  detail:
623
- describeProxyFailure(error, proxyConfig) ||
624
- error?.message ||
844
+ describeProxyFailure(createError, proxyConfig) ||
845
+ createError?.message ||
625
846
  "Could not create the WhatsApp socket",
626
847
  });
627
848
  return;
628
849
  }
629
850
 
630
- if (this.#shuttingDown || this.#generation !== startedAt) {
631
- // Overtaken. Throw the socket away rather than adopt it, or we would end
632
- // up with a live connection nobody asked for and no state pointing at it.
633
- this.log.warn("[Session] discarding a socket whose start was overtaken");
634
- this.#detach(created.sock);
635
- try {
636
- await withTimeout(created.sock?.end?.(undefined), SOCKET_CLOSE_TIMEOUT_MS);
637
- } catch {}
638
- return;
639
- }
640
-
641
- const { sock, saveCreds, clearAll, isPaired } = created;
851
+ const { sock, saveCreds, clearAll, fence, isPaired } = created;
642
852
 
853
+ this.#fence();
643
854
  const generation = (this.#generation += 1);
644
855
  this.#socket = sock;
645
856
  this.#clearAll = clearAll;
857
+ this.#fenceAuth = typeof fence === "function" ? fence : null;
646
858
  // An install with no pairing yet is on a pairing attempt: its closes are
647
859
  // terminal until a phone has actually scanned the code.
648
860
  this.#pairing = !isPaired;
649
861
 
650
- this.attachListeners(sock, {
862
+ const disposeListeners = this.attachListeners(sock, {
651
863
  saveCreds,
652
864
  onConnectionUpdate: (update) => this.#onConnectionUpdate(generation, update),
653
865
  onHandshakeRejected: (response) => this.#onHandshakeRejected(generation, sock, response),
654
866
  });
867
+ if (typeof disposeListeners === "function") this.#listenerDisposers.set(sock, disposeListeners);
655
868
 
656
869
  const waitingForCode = this.#pairing && this.#pairingIntent.method === "pairing";
657
870
  this.#transition(this.#pairing ? S.WAITING_FOR_QR : S.STARTING, {
@@ -699,8 +912,65 @@ export class WhatsAppSession {
699
912
  Promise.resolve(sock?.end?.(error)).catch(() => {});
700
913
  }
701
914
 
915
+ /** Close the auth-store fence for a socket we are tearing down or unlinking. */
916
+ #fence(fence = this.#fenceAuth) {
917
+ if (fence === this.#fenceAuth) {
918
+ this.#fenceAuth = null;
919
+ }
920
+ if (typeof fence !== "function") return;
921
+ try {
922
+ fence();
923
+ } catch (error) {
924
+ this.log.debug({ err: error?.message }, "[Session] auth fence threw");
925
+ }
926
+ }
927
+
928
+ /**
929
+ * The attempt that just returned was no longer current. If the device is
930
+ * online again and the session should be running, the start() waiting on
931
+ * this attempt opens one replacement. Same condition as setInternetOnline(true).
932
+ */
933
+ #noteOvertakenStart(startedAt) {
934
+ const stopped = this.#terminalGeneration > startedAt;
935
+ this.#resumeAfterStart =
936
+ !stopped &&
937
+ !this.#shuttingDown &&
938
+ !this.#loggingOut &&
939
+ this.#isOnline &&
940
+ (this.#wasActiveBeforeOffline || this.#state === S.PAUSED);
941
+ }
942
+
943
+ // stop and shutdown. Bump before waiting so an attempt already in
944
+ // createSocket cannot adopt, and so a resume queued on that attempt cannot
945
+ // open a replacement. Then wait out any replacement that still appeared.
946
+ #markTerminalIntent() {
947
+ this.#resumeAfterStart = false;
948
+ this.#generation += 1;
949
+ this.#terminalGeneration = this.#generation;
950
+ }
951
+
952
+ async #settleStarts() {
953
+ this.#markTerminalIntent();
954
+ let pending = this.#starting;
955
+ while (pending) {
956
+ await pending.catch(() => {});
957
+ pending = this.#starting;
958
+ if (pending) this.#markTerminalIntent();
959
+ }
960
+ }
961
+
702
962
  /** Cut every wire back from a socket we are done with. */
703
963
  #detach(sock) {
964
+ disposeReactionIntake(sock);
965
+ const dispose = sock ? this.#listenerDisposers.get(sock) : undefined;
966
+ if (sock) this.#listenerDisposers.delete(sock);
967
+ if (typeof dispose === "function") {
968
+ try {
969
+ dispose();
970
+ } catch (error) {
971
+ this.log.debug({ err: error?.message }, "[Session] listener dispose threw");
972
+ }
973
+ }
704
974
  for (const event of ["connection.update", "creds.update"]) {
705
975
  try {
706
976
  sock?.ev?.removeAllListeners?.(event);
@@ -710,6 +980,7 @@ export class WhatsAppSession {
710
980
 
711
981
  /** End the current socket without letting its close event mean anything. */
712
982
  async #destroySocket() {
983
+ this.#fence();
713
984
  const sock = this.#socket;
714
985
  if (!sock) return;
715
986
 
@@ -861,14 +1132,22 @@ export class WhatsAppSession {
861
1132
  try {
862
1133
  await this.onOpen(this.#socket, this.initializeScheduledJobs);
863
1134
  } catch (error) {
1135
+ if (error?.code === "ACTIVATION_UNSAFE") {
1136
+ this.log.error("[Session] Account activation rollback incomplete; stopping WhatsApp until recovery succeeds");
1137
+ await this.stop({ reason: "activation_unsafe", state: S.ERROR,
1138
+ detail: "Account recovery is incomplete. Restart Levix before connecting." });
1139
+ return;
1140
+ }
864
1141
  this.log.error({ err: error }, "[Session] post-connect setup failed");
865
1142
  }
866
1143
  }
867
1144
 
868
1145
  async #onClose(lastDisconnect) {
869
1146
  const statusCode = lastDisconnect?.error?.output?.statusCode;
1147
+ // The message first: for a WebSocket error the payload is only the HTTP
1148
+ // phrase for Boom's default 500, while the message names the real error.
870
1149
  const reasonText =
871
- lastDisconnect?.error?.output?.payload?.error || lastDisconnect?.error?.message || "Unknown";
1150
+ lastDisconnect?.error?.message || lastDisconnect?.error?.output?.payload?.error || "Unknown";
872
1151
 
873
1152
  this.#lastDisconnect = { statusCode: statusCode ?? null, reason: reasonText, at: Date.now() };
874
1153
  const closedSocket = this.#socket;
@@ -878,6 +1157,7 @@ export class WhatsAppSession {
878
1157
  // stop from `reconnecting` would leave the dead socket's generation current
879
1158
  // and anything it emitted afterwards would still be believed.
880
1159
  this.#generation += 1;
1160
+ this.#fence();
881
1161
  this.#detach(closedSocket);
882
1162
  // The scheduled jobs were armed with that socket. Leaving them running
883
1163
  // means a daily message firing into a closed connection, failing, and
@@ -896,6 +1176,10 @@ export class WhatsAppSession {
896
1176
  `[Session] Connection closed (${statusCode ?? "no status"}: ${reasonText}) — ${verdict.label}` +
897
1177
  (this.#proxyLabel ? ` via ${this.#proxyLabel}` : ""),
898
1178
  );
1179
+ this.debugLog.warn(
1180
+ { close: describeCloseError(lastDisconnect?.error), verdict: verdict.reason },
1181
+ "[Session] close detail",
1182
+ );
899
1183
 
900
1184
  if (this.#shuttingDown) return;
901
1185
 
@@ -940,35 +1224,201 @@ export class WhatsAppSession {
940
1224
 
941
1225
  async #handleLoggedOut(verdict, closedSocket) {
942
1226
  this.log.error("[Session] WhatsApp logged this device out. Clearing the stored credentials.");
1227
+ // WhatsApp already dropped the pairing. If saving intent fails here, stay
1228
+ // ERROR in this process. Restart may resume the surviving credentials, but
1229
+ // WhatsApp rejects them with 401 and takes this cleanup path again.
1230
+ // Before clearAll(), which is the first await on this path.
1231
+ this.#resumeAfterStart = false;
1232
+ advanceAccountEpoch();
943
1233
 
944
1234
  // Baileys destroys its emitter inside end() before this close is reported,
945
1235
  // so there is normally nothing left to hear from. Being explicit costs
946
1236
  // nothing and closes the one window where a late creds.update could write
947
1237
  // the dead credentials back over the wipe below.
1238
+ this.#fence();
948
1239
  this.#detach(closedSocket);
949
1240
 
950
1241
  const clearAll = this.#clearAll;
951
1242
  this.#clearAll = null;
952
- if (clearAll) {
953
- try {
954
- await clearAll();
955
- this.log.info("[Session] Credentials cleared");
956
- } catch (error) {
957
- this.log.error({ err: error }, "[Session] failed to clear credentials");
958
- }
959
- }
1243
+ const wiped = await this.#wipeCredentials(clearAll);
1244
+ if (wiped) this.log.info("[Session] Credentials cleared");
960
1245
 
961
1246
  this.#pairing = false;
962
1247
  this.#clearQr();
963
1248
  this.#cancelRetry();
964
1249
  this.#attempt = 0;
965
1250
  this.#stopJobs();
1251
+ if (!wiped) return this.#failUnlink();
1252
+ return this.#finishUnlink({ reason: verdict.reason, detail: verdict.detail });
1253
+ }
1254
+
1255
+ // True when this process saw a failed wipe, or the marker is on disk.
1256
+ // A read error blocks start as pending. It never authorizes a wipe: boot
1257
+ // recovery and the wipe itself refuse to delete when the marker read throws.
1258
+ #incompleteUnlink() {
1259
+ return this.#unlinkFailed || this.#unlinkPending();
1260
+ }
1261
+
1262
+ #unlinkPending() {
1263
+ try {
1264
+ return store.isUnlinkPending();
1265
+ } catch (error) {
1266
+ this.log.error({ err: error }, "[Session] could not read the pending-unlink marker");
1267
+ return true;
1268
+ }
1269
+ }
1270
+
1271
+ #refuseIncompleteUnlink() {
1272
+ if (!this.#incompleteUnlink()) return false;
1273
+ this.#failUnlink();
1274
+ return true;
1275
+ }
1276
+
1277
+ #failUnlink() {
1278
+ this.#unlinkFailed = true;
1279
+ this.#cancelRetry();
1280
+ this.#pairing = false;
1281
+ this.#clearQr();
1282
+ this.#transition(S.ERROR, {
1283
+ reason: "unlink_incomplete",
1284
+ detail: UNLINK_INCOMPLETE_DETAIL,
1285
+ });
1286
+ return this.getState();
1287
+ }
1288
+
1289
+ #dropUnlinkMarker() {
1290
+ try {
1291
+ store.clearUnlinkPending();
1292
+ return true;
1293
+ } catch (error) {
1294
+ this.log.error({ err: error }, "[Session] failed to clear the pending-unlink marker");
1295
+ return false;
1296
+ }
1297
+ }
1298
+
1299
+ // Account data is cleared only after this returns true. Epoch already moved
1300
+ // at the start of the unlink, so in-flight work drops its writes either way.
1301
+ async #wipeCredentials(clearAll, { retry = null } = {}) {
1302
+ let pendingBefore = false;
966
1303
  try {
967
- this.clearDirectory?.();
1304
+ pendingBefore = store.isUnlinkPending();
968
1305
  } catch (error) {
969
- this.log.warn({ err: error }, "[Session] failed to clear WhatsApp directory after logout");
1306
+ this.log.error({ err: error }, "[Session] could not read the pending-unlink marker");
1307
+ this.#unlinkFailed = true;
1308
+ return false;
1309
+ }
1310
+ if (!pendingBefore) {
1311
+ try {
1312
+ store.markUnlinkPending();
1313
+ } catch (error) {
1314
+ this.log.error({ err: error }, "[Session] failed to record the pending unlink");
1315
+ this.#unlinkFailed = true;
1316
+ return false;
1317
+ }
1318
+ }
1319
+
1320
+ // Manual unlink saved intent before teardown. Use its earlier snapshot so
1321
+ // the first attempt still uses the live socket's clearAll, not the fallback.
1322
+ const retryWipe = retry ?? (pendingBefore || this.#unlinkFailed);
1323
+ try {
1324
+ if (retryWipe || typeof clearAll !== "function") {
1325
+ if (typeof this.clearCredentials !== "function") {
1326
+ throw new Error("No credential wipe is available");
1327
+ }
1328
+ await this.clearCredentials();
1329
+ } else {
1330
+ await clearAll();
1331
+ }
1332
+ } catch (error) {
1333
+ this.log.error({ err: error }, "[Session] failed to clear credentials");
1334
+ this.#unlinkFailed = true;
1335
+ return false;
1336
+ }
1337
+ return true;
1338
+ }
1339
+
1340
+ // Account cleanup runs only once the credentials are gone. Keep the marker
1341
+ // on any cleanup failure or crash, so retry repeats the whole cleanup before
1342
+ // a new account can pair.
1343
+ #finishUnlink({ reason, detail }) {
1344
+ try {
1345
+ this.clearDirectory();
1346
+ } catch (error) {
1347
+ this.log.error({ err: error }, "[Session] failed to clear account data after unlink");
1348
+ return this.#failUnlink();
1349
+ }
1350
+ if (!this.#dropUnlinkMarker()) return this.#failUnlink();
1351
+ this.#unlinkFailed = false;
1352
+ this.#transition(S.LOGGED_OUT, { reason, detail });
1353
+ return this.getState();
1354
+ }
1355
+
1356
+ // -------------------------------------------------------------------------
1357
+ // Terms consent
1358
+ // -------------------------------------------------------------------------
1359
+
1360
+ /**
1361
+ * Continue a start that the Terms gate held back, if the installation now
1362
+ * has a valid acceptance. The panel calls this right after recording one;
1363
+ * the poll below calls it for an acceptance written by `levix terms`.
1364
+ */
1365
+ async recheckConsent() {
1366
+ if (this.#state !== S.CONSENT_REQUIRED || this.#shuttingDown) return this.getState();
1367
+ if (!this.#consentAllows()) return this.getState();
1368
+ this.#stopConsentWatch();
1369
+ const { method, phone } = this.#pairingIntent || {};
1370
+ return this.start({ reason: "consent_accepted", method, phone });
1371
+ }
1372
+
1373
+ #readConsent() {
1374
+ try {
1375
+ const status = this.checkConsent();
1376
+ if (status !== null && typeof status === "object" && !Array.isArray(status)) return status;
1377
+ } catch (error) {
1378
+ this.log.error({ err: error }, "[Session] the Terms acceptance check failed");
1379
+ }
1380
+ // Fail closed: an answer we cannot read is not an acceptance.
1381
+ return { ok: false, reason: consent.REASONS.UNREADABLE };
1382
+ }
1383
+
1384
+ #consentAllows() {
1385
+ const status = this.#readConsent();
1386
+ if (status.ok === true) return true;
1387
+
1388
+ const reason =
1389
+ typeof status.reason === "string" && status.reason
1390
+ ? status.reason
1391
+ : consent.REASONS.NOT_ACCEPTED;
1392
+ if (this.#state !== S.CONSENT_REQUIRED) {
1393
+ this.log.warn(`[Session] WhatsApp waits for the Terms to be accepted (${reason})`);
1394
+ this.#clearQr();
1395
+ this.#pairing = false;
1396
+ }
1397
+ if (this.#state !== S.CONSENT_REQUIRED || this.#reason !== reason) {
1398
+ this.#transition(S.CONSENT_REQUIRED, { reason, detail: consent.describeReason(reason) });
1399
+ }
1400
+ this.#watchConsent();
1401
+ return false;
1402
+ }
1403
+
1404
+ #watchConsent() {
1405
+ if (this.#consentTimer || this.#shuttingDown) return;
1406
+ this.#consentTimer = setInterval(() => {
1407
+ if (this.#state !== S.CONSENT_REQUIRED || this.#shuttingDown) {
1408
+ this.#stopConsentWatch();
1409
+ return;
1410
+ }
1411
+ this.recheckConsent().catch((error) =>
1412
+ this.log.error({ err: error }, "[Session] start after the Terms acceptance failed"),
1413
+ );
1414
+ }, this.consentPollMs);
1415
+ }
1416
+
1417
+ #stopConsentWatch() {
1418
+ if (this.#consentTimer) {
1419
+ clearInterval(this.#consentTimer);
1420
+ this.#consentTimer = null;
970
1421
  }
971
- this.#transition(S.LOGGED_OUT, { reason: verdict.reason, detail: verdict.detail });
972
1422
  }
973
1423
 
974
1424
  // -------------------------------------------------------------------------
@@ -1025,6 +1475,7 @@ export class WhatsAppSession {
1025
1475
  this.#retryTimer = null;
1026
1476
  this.#nextRetryAt = null;
1027
1477
  if (this.#shuttingDown) return;
1478
+ if (this.#loggingOut) return;
1028
1479
  if (this.#starting) return;
1029
1480
 
1030
1481
  this.#starting = this.#open({ reason: "reconnect" })
@@ -1077,6 +1528,7 @@ export class WhatsAppSession {
1077
1528
  }
1078
1529
 
1079
1530
  #transition(state, { reason = null, detail = null } = {}) {
1531
+ if (state !== S.CONSENT_REQUIRED) this.#stopConsentWatch();
1080
1532
  const changed = state !== this.#state;
1081
1533
  this.#state = state;
1082
1534
  this.#reason = reason;