levix-bot 4.9.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +46 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +1 -1
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +182 -10
  138. package/src/core/connection.js +37 -8
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +525 -82
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/debugLog.cjs +16 -4
  147. package/src/diagnostics/device.cjs +4 -2
  148. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  149. package/src/domain/command.js +24 -22
  150. package/src/extensions/autoReply.cjs +521 -0
  151. package/src/extensions/context.cjs +73 -0
  152. package/src/extensions/contract.cjs +69 -0
  153. package/src/extensions/entitlement/client.cjs +381 -0
  154. package/src/extensions/entitlement/index.cjs +629 -0
  155. package/src/extensions/entitlement/installation.cjs +117 -0
  156. package/src/extensions/entitlement/keys.cjs +72 -0
  157. package/src/extensions/entitlement/state.cjs +201 -0
  158. package/src/extensions/entitlement/target.cjs +7 -0
  159. package/src/extensions/entitlement/token.cjs +225 -0
  160. package/src/extensions/host.cjs +519 -0
  161. package/src/extensions/templateKeys.cjs +81 -0
  162. package/src/handlers/command.handler.js +191 -64
  163. package/src/handlers/group.handler.js +78 -18
  164. package/src/handlers/message.handler.js +56 -25
  165. package/src/i18n/catalog.generated.cjs +3537 -0
  166. package/src/index.js +51 -12
  167. package/src/legal/bundled/ar.json +102 -0
  168. package/src/legal/bundled/en.json +102 -0
  169. package/src/legal/bundled/es-419.json +102 -0
  170. package/src/legal/bundled/pt-BR.json +102 -0
  171. package/src/legal/cli.cjs +200 -0
  172. package/src/legal/consent.cjs +187 -0
  173. package/src/legal/document.cjs +156 -0
  174. package/src/legal/keys.cjs +100 -0
  175. package/src/legal/release.cjs +226 -0
  176. package/src/legal/remote.cjs +419 -0
  177. package/src/legal/terms.cjs +142 -0
  178. package/src/messaging/escape.cjs +31 -0
  179. package/src/messaging/health.cjs +65 -0
  180. package/src/messaging/identity.cjs +42 -0
  181. package/src/messaging/message.cjs +136 -0
  182. package/src/messaging/parser.cjs +88 -0
  183. package/src/messaging/router.cjs +217 -0
  184. package/src/middleware/permissions.middleware.js +34 -2
  185. package/src/panel/account-profile.cjs +489 -0
  186. package/src/panel/fallback-page.cjs +177 -0
  187. package/src/panel/password-reset.cjs +13 -14
  188. package/src/panel/recovery-email.cjs +3 -1
  189. package/src/routes/backup.api.esm.js +175 -0
  190. package/src/routes/dashboard.api.esm.js +183 -7
  191. package/src/routes/plus.api.esm.js +172 -0
  192. package/src/routes/reactions.api.esm.js +60 -0
  193. package/src/services/aiAgent.cjs +56 -43
  194. package/src/services/aiDocs.cjs +187 -0
  195. package/src/services/aiImage.cjs +183 -0
  196. package/src/services/aiMedia.cjs +146 -0
  197. package/src/services/aiProviders.cjs +76 -80
  198. package/src/services/aiRouter.cjs +2 -2
  199. package/src/services/aiToolAuth.cjs +76 -4
  200. package/src/services/aiTools.cjs +431 -105
  201. package/src/services/autoDelete.cjs +9 -1
  202. package/src/services/levix-docs.generated.json +2623 -0
  203. package/src/services/memoryPolicy.cjs +56 -0
  204. package/src/services/updateCheck.cjs +362 -0
  205. package/src/stickers/errors.cjs +53 -97
  206. package/src/stickers/library.cjs +13 -6
  207. package/src/stickers/owner.cjs +1 -1
  208. package/src/utils/commandContext.cjs +13 -0
  209. package/src/utils/commandDocs.cjs +42 -20
  210. package/src/utils/geminiHttpOptions.cjs +56 -0
  211. package/src/utils/geminiMedia.cjs +28 -3
  212. package/src/utils/groupMetadataCache.cjs +386 -21
  213. package/src/utils/httpsFetch.cjs +113 -0
  214. package/src/utils/i18n.cjs +117 -7
  215. package/src/utils/linkPreview.cjs +90 -0
  216. package/src/utils/markdownParser.cjs +3 -3
  217. package/src/utils/memory.cjs +375 -28
  218. package/src/utils/messageContent.cjs +7 -1
  219. package/src/utils/moderationAction.cjs +116 -73
  220. package/src/utils/moderationSummary.cjs +32 -56
  221. package/src/utils/permissionLevel.cjs +7 -28
  222. package/src/utils/permissions.cjs +23 -14
  223. package/src/utils/permissions.esm.js +99 -166
  224. package/src/utils/recentMessageCache.esm.js +241 -37
  225. package/src/utils/recurrence.cjs +78 -66
  226. package/src/utils/sendBotMessage.cjs +14 -29
  227. package/src/utils/sendBotMessage.esm.js +28 -13
  228. package/src/utils/statusMessage.cjs +94 -33
  229. package/src/utils/stickerBot.cjs +18 -16
  230. package/src/utils/storage.cjs +2 -0
  231. package/src/utils/storage.esm.js +2 -0
  232. package/src/utils/thumbnail.cjs +5 -21
  233. package/public/dashboard/assets/index-4xhK_Tpl.js +0 -561
  234. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  235. package/public/dashboard.css +0 -3127
  236. package/public/dashboard.js +0 -1981
  237. package/public/gateway-i18n.js +0 -321
  238. package/public/gateway.js +0 -70
  239. package/views/dashboard.ejs +0 -775
  240. package/views/login.ejs +0 -408
  241. package/views/qr.ejs +0 -155
  242. package/views/setup.ejs +0 -118
@@ -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
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
@@ -270,6 +325,11 @@ export class WhatsAppSession {
270
325
  pairingCodeDelayMs = 1500,
271
326
  isLinked = isPairedSession,
272
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,
273
333
  } = {}) {
274
334
  this.createSocket = createSocket;
275
335
  this.attachListeners = attachListeners;
@@ -286,6 +346,8 @@ export class WhatsAppSession {
286
346
  this.log = log;
287
347
  this.debugLog = debugLog;
288
348
  this.pairingCodeDelayMs = pairingCodeDelayMs;
349
+ this.checkConsent = checkConsent;
350
+ this.consentPollMs = consentPollMs;
289
351
  }
290
352
 
291
353
  // -------------------------------------------------------------------------
@@ -332,14 +394,20 @@ export class WhatsAppSession {
332
394
  attempt: this.#attempt,
333
395
  maxAttempts: this.retryDelaysMs.length,
334
396
  nextRetryAt: this.#nextRetryAt,
335
- 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(),
336
402
  canStop: BUSY_STATES.has(this.#state),
337
403
  // Not "is it connected": a pairing that WhatsApp has refused (403, 405)
338
404
  // leaves dead credentials behind, and unlinking is the only way out of
339
405
  // it. The one state with nothing to unlink is the one that just did.
340
- 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,
341
408
  // Finished WhatsApp pairing — resume/connect, do not offer QR/pair.
342
- 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(),
343
411
  // Redacted — never the password. Null when the socket is direct.
344
412
  proxy: this.#proxyLabel,
345
413
  // True when the saved proxy settings differ from what the live socket was
@@ -347,6 +415,7 @@ export class WhatsAppSession {
347
415
  // answer crosses the wire, never the fingerprint it was computed from.
348
416
  proxyChanged: this.#proxyIsStale(),
349
417
  connected: this.#state === S.CONNECTED,
418
+ consentRequired: this.#state === S.CONSENT_REQUIRED,
350
419
  isOnline: this.#isOnline,
351
420
  terminal,
352
421
  hasQr: !!this.#qr,
@@ -372,6 +441,7 @@ export class WhatsAppSession {
372
441
  * When offline (false):
373
442
  * - Pauses active connection attempts and cancels pending retry timers.
374
443
  * - Transitions to S.PAUSED without exhausting retries.
444
+ * - A session in no NETWORK_RESUME_STATES state keeps its state.
375
445
  *
376
446
  * When online (true):
377
447
  * - Restores connection if it was active before going offline or currently paused.
@@ -382,13 +452,26 @@ export class WhatsAppSession {
382
452
  if (this.#isOnline === isOnline) return this.getState();
383
453
  this.#isOnline = isOnline;
384
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
+
385
463
  if (!isOnline) {
386
464
  this.log.warn("[Session] Device is offline — pausing WhatsApp connection and retries");
387
465
  this.#wasActiveBeforeOffline = BUSY_STATES.has(this.#state) || this.#state === S.PAUSED;
388
466
  this.#cancelRetry();
389
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.
390
471
  if (this.#socket) {
391
472
  await this.#destroySocket();
473
+ } else {
474
+ this.#generation += 1;
392
475
  }
393
476
  this.#transition(S.PAUSED, {
394
477
  reason: "offline",
@@ -412,26 +495,43 @@ export class WhatsAppSession {
412
495
  }
413
496
 
414
497
  /**
415
- * Bring the session up. Idempotent: if a socket exists or is being made, this
416
- * 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.
417
501
  */
418
502
  async start({ reason = "manual", method, phone } = {}) {
419
503
  if (this.#shuttingDown) return this.getState();
420
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
+
421
514
  if (this.#state === S.PAUSED && !this.#isOnline) {
422
515
  return this.getState();
423
516
  }
424
517
 
518
+ let resume = false;
425
519
  if (this.#starting) {
426
520
  await this.#starting.catch(() => {});
427
- 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
+ }
428
526
  }
429
- 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();
430
528
 
431
529
  // A known pairing reuses the stored session. Do not request a pairing code.
432
530
  if (this.isLinked()) {
433
531
  this.#pairingIntent = { method: "qr", phone: null };
434
- } 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.
435
535
  this.#pairingIntent = parseStartOptions({ method, phone });
436
536
  }
437
537
 
@@ -455,11 +555,13 @@ export class WhatsAppSession {
455
555
  */
456
556
  async stop({ reason = "manual", state = S.IDLE, detail = null } = {}) {
457
557
  this.#cancelRetry();
558
+ this.#stopConsentWatch();
458
559
  this.#attempt = 0;
459
560
 
460
- // Wait for an in-flight start, or we would tear down a socket that has not
461
- // been assigned yet and then have it appear behind us.
462
- 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(() => {});
463
565
 
464
566
  // Again after the await: a close that landed while we were waiting is
465
567
  // entitled to schedule a retry, and it would outlive this stop.
@@ -469,6 +571,9 @@ export class WhatsAppSession {
469
571
  await this.#destroySocket();
470
572
  this.#clearQr();
471
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();
472
577
  this.#transition(state, { reason, detail });
473
578
  return this.getState();
474
579
  }
@@ -478,21 +583,97 @@ export class WhatsAppSession {
478
583
  * then clear the credentials whether or not that call got through.
479
584
  */
480
585
  async logout() {
481
- // A start that is still creating its socket has to finish first: otherwise
482
- // #open() assigns a live socket after this method has already declared the
483
- // session logged out, and the account is unlinked with a connection still
484
- // 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();
485
657
  this.#cancelRetry();
658
+ this.#stopConsentWatch();
486
659
  if (this.#starting) await this.#starting.catch(() => {});
487
660
 
488
661
  const sock = this.#socket;
489
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;
490
668
 
491
669
  // Stale from here on: whatever the socket emits while logging out is not
492
670
  // allowed to schedule anything.
493
671
  this.#generation += 1;
494
672
  this.#cancelRetry();
495
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);
496
677
 
497
678
  if (sock) {
498
679
  try {
@@ -510,30 +691,34 @@ export class WhatsAppSession {
510
691
  } catch {}
511
692
  }
512
693
 
513
- // clearAll() belongs to the socket that was alive; when there wasn't one,
514
- // the store-level wipe does the same job.
515
- try {
516
- await (clearAll ? clearAll() : this.clearCredentials?.());
517
- } catch (error) {
518
- 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();
519
709
  }
520
710
 
521
711
  this.#socket = null;
522
712
  this.#clearAll = null;
713
+ this.#fenceAuth = null;
523
714
  this.#pairing = false;
524
715
  this.#clearQr();
525
716
  this.#stopJobs();
526
- try {
527
- this.clearDirectory?.();
528
- } catch (error) {
529
- this.log.warn({ err: error }, "[Session] failed to clear WhatsApp directory after unlink");
530
- }
531
-
532
- this.#transition(S.LOGGED_OUT, {
717
+ if (!wiped) return this.#failUnlink();
718
+ return this.#finishUnlink({
533
719
  reason: "unlinked",
534
720
  detail: "The WhatsApp account was unlinked. Start a session to pair a new one.",
535
721
  });
536
- return this.getState();
537
722
  }
538
723
 
539
724
  /**
@@ -555,7 +740,9 @@ export class WhatsAppSession {
555
740
  async shutdown() {
556
741
  this.#shuttingDown = true;
557
742
  this.#cancelRetry();
558
- if (this.#starting) await this.#starting.catch(() => {});
743
+ this.#stopConsentWatch();
744
+ await this.#settleStarts();
745
+ if (this.#loggingOut) await this.#loggingOut.catch(() => {});
559
746
  this.#cancelRetry();
560
747
  await this.#destroySocket();
561
748
  // A code left in the database would be served by GET /qr on the next boot,
@@ -569,6 +756,16 @@ export class WhatsAppSession {
569
756
  // -------------------------------------------------------------------------
570
757
 
571
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
+
572
769
  if (!this.#isOnline) {
573
770
  this.#wasActiveBeforeOffline = true;
574
771
  this.#transition(S.PAUSED, {
@@ -582,9 +779,9 @@ export class WhatsAppSession {
582
779
  this.#clearQr();
583
780
  this.#transition(S.STARTING, { reason });
584
781
 
585
- // Anything that invalidates this attempt — stop, logout, shutdown — bumps
586
- // the generation. Creating a socket is asynchronous, so the attempt has to
587
- // 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.
588
785
  const startedAt = this.#generation;
589
786
 
590
787
  // Read per attempt, so changing the proxy and pressing Reconnect is all it
@@ -613,48 +810,61 @@ export class WhatsAppSession {
613
810
  this.#proxyConfig = proxyConfig;
614
811
 
615
812
  let created;
813
+ let createError = null;
616
814
  try {
617
815
  created = await this.createSocket({
618
816
  proxy,
619
817
  pairingCode: !this.isLinked() && this.#pairingIntent.method === "pairing",
620
818
  });
621
819
  } catch (error) {
622
- 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");
623
841
  this.#transition(S.ERROR, {
624
842
  reason: "socket_failed",
625
843
  detail:
626
- describeProxyFailure(error, proxyConfig) ||
627
- error?.message ||
844
+ describeProxyFailure(createError, proxyConfig) ||
845
+ createError?.message ||
628
846
  "Could not create the WhatsApp socket",
629
847
  });
630
848
  return;
631
849
  }
632
850
 
633
- if (this.#shuttingDown || this.#generation !== startedAt) {
634
- // Overtaken. Throw the socket away rather than adopt it, or we would end
635
- // up with a live connection nobody asked for and no state pointing at it.
636
- this.log.warn("[Session] discarding a socket whose start was overtaken");
637
- this.#detach(created.sock);
638
- try {
639
- await withTimeout(created.sock?.end?.(undefined), SOCKET_CLOSE_TIMEOUT_MS);
640
- } catch {}
641
- return;
642
- }
643
-
644
- const { sock, saveCreds, clearAll, isPaired } = created;
851
+ const { sock, saveCreds, clearAll, fence, isPaired } = created;
645
852
 
853
+ this.#fence();
646
854
  const generation = (this.#generation += 1);
647
855
  this.#socket = sock;
648
856
  this.#clearAll = clearAll;
857
+ this.#fenceAuth = typeof fence === "function" ? fence : null;
649
858
  // An install with no pairing yet is on a pairing attempt: its closes are
650
859
  // terminal until a phone has actually scanned the code.
651
860
  this.#pairing = !isPaired;
652
861
 
653
- this.attachListeners(sock, {
862
+ const disposeListeners = this.attachListeners(sock, {
654
863
  saveCreds,
655
864
  onConnectionUpdate: (update) => this.#onConnectionUpdate(generation, update),
656
865
  onHandshakeRejected: (response) => this.#onHandshakeRejected(generation, sock, response),
657
866
  });
867
+ if (typeof disposeListeners === "function") this.#listenerDisposers.set(sock, disposeListeners);
658
868
 
659
869
  const waitingForCode = this.#pairing && this.#pairingIntent.method === "pairing";
660
870
  this.#transition(this.#pairing ? S.WAITING_FOR_QR : S.STARTING, {
@@ -702,8 +912,65 @@ export class WhatsAppSession {
702
912
  Promise.resolve(sock?.end?.(error)).catch(() => {});
703
913
  }
704
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
+
705
962
  /** Cut every wire back from a socket we are done with. */
706
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
+ }
707
974
  for (const event of ["connection.update", "creds.update"]) {
708
975
  try {
709
976
  sock?.ev?.removeAllListeners?.(event);
@@ -713,6 +980,7 @@ export class WhatsAppSession {
713
980
 
714
981
  /** End the current socket without letting its close event mean anything. */
715
982
  async #destroySocket() {
983
+ this.#fence();
716
984
  const sock = this.#socket;
717
985
  if (!sock) return;
718
986
 
@@ -864,6 +1132,12 @@ export class WhatsAppSession {
864
1132
  try {
865
1133
  await this.onOpen(this.#socket, this.initializeScheduledJobs);
866
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
+ }
867
1141
  this.log.error({ err: error }, "[Session] post-connect setup failed");
868
1142
  }
869
1143
  }
@@ -883,6 +1157,7 @@ export class WhatsAppSession {
883
1157
  // stop from `reconnecting` would leave the dead socket's generation current
884
1158
  // and anything it emitted afterwards would still be believed.
885
1159
  this.#generation += 1;
1160
+ this.#fence();
886
1161
  this.#detach(closedSocket);
887
1162
  // The scheduled jobs were armed with that socket. Leaving them running
888
1163
  // means a daily message firing into a closed connection, failing, and
@@ -949,35 +1224,201 @@ export class WhatsAppSession {
949
1224
 
950
1225
  async #handleLoggedOut(verdict, closedSocket) {
951
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();
952
1233
 
953
1234
  // Baileys destroys its emitter inside end() before this close is reported,
954
1235
  // so there is normally nothing left to hear from. Being explicit costs
955
1236
  // nothing and closes the one window where a late creds.update could write
956
1237
  // the dead credentials back over the wipe below.
1238
+ this.#fence();
957
1239
  this.#detach(closedSocket);
958
1240
 
959
1241
  const clearAll = this.#clearAll;
960
1242
  this.#clearAll = null;
961
- if (clearAll) {
962
- try {
963
- await clearAll();
964
- this.log.info("[Session] Credentials cleared");
965
- } catch (error) {
966
- this.log.error({ err: error }, "[Session] failed to clear credentials");
967
- }
968
- }
1243
+ const wiped = await this.#wipeCredentials(clearAll);
1244
+ if (wiped) this.log.info("[Session] Credentials cleared");
969
1245
 
970
1246
  this.#pairing = false;
971
1247
  this.#clearQr();
972
1248
  this.#cancelRetry();
973
1249
  this.#attempt = 0;
974
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() {
975
1263
  try {
976
- this.clearDirectory?.();
1264
+ return store.isUnlinkPending();
977
1265
  } catch (error) {
978
- this.log.warn({ err: error }, "[Session] failed to clear WhatsApp directory after logout");
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;
1303
+ try {
1304
+ pendingBefore = store.isUnlinkPending();
1305
+ } catch (error) {
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;
979
1421
  }
980
- this.#transition(S.LOGGED_OUT, { reason: verdict.reason, detail: verdict.detail });
981
1422
  }
982
1423
 
983
1424
  // -------------------------------------------------------------------------
@@ -1034,6 +1475,7 @@ export class WhatsAppSession {
1034
1475
  this.#retryTimer = null;
1035
1476
  this.#nextRetryAt = null;
1036
1477
  if (this.#shuttingDown) return;
1478
+ if (this.#loggingOut) return;
1037
1479
  if (this.#starting) return;
1038
1480
 
1039
1481
  this.#starting = this.#open({ reason: "reconnect" })
@@ -1086,6 +1528,7 @@ export class WhatsAppSession {
1086
1528
  }
1087
1529
 
1088
1530
  #transition(state, { reason = null, detail = null } = {}) {
1531
+ if (state !== S.CONSENT_REQUIRED) this.#stopConsentWatch();
1089
1532
  const changed = state !== this.#state;
1090
1533
  this.#state = state;
1091
1534
  this.#reason = reason;