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
@@ -12,19 +12,14 @@
12
12
  // `autoStart` and starts even when pairing is still required.
13
13
 
14
14
  import { createRequire } from "module";
15
- import { WhatsAppSession } from "../core/session.js";
16
- import { initStore } from "../db/store.esm.js";
17
- import { getLoadedCommands, loadCommands } from "../handlers/command.handler.js";
18
- import { deleteQrCode } from "../utils/storage.esm.js";
19
- import { hasPairedCredentials, sessionStartupPolicy } from "./session-startup-policy.js";
20
15
 
21
16
  const require = createRequire(import.meta.url);
22
17
  const logger = require("../utils/logger.cjs");
23
18
  const { sink } = require("./events.cjs");
24
19
  const { acquireSingleInstanceLock } = require("../config/lock.cjs");
20
+ const { prepareDatabase } = require("../db/db.cjs");
21
+ const { runRestoreRecovery } = require("../backup/recovery.cjs");
25
22
  const { ensureDataDir } = require("../config/paths.cjs");
26
- const store = require("../db/store.cjs");
27
- const { initializeScheduledJobs, stopAllScheduledJobs } = require("../../scheduler.cjs");
28
23
 
29
24
  /**
30
25
  * Start the bot.
@@ -40,6 +35,20 @@ export async function bootstrapCore({ autoStart = false } = {}) {
40
35
  // second copy has to fail here, not after it has written to the auth rows
41
36
  // the first one is using.
42
37
  acquireSingleInstanceLock();
38
+ await prepareDatabase();
39
+ await runRestoreRecovery();
40
+
41
+ const { WhatsAppSession } = await import("../core/session.js");
42
+ const { initStore } = await import("../db/store.esm.js");
43
+ const { getLoadedCommands, loadCommands } = await import("../handlers/command.handler.js");
44
+ const { deleteQrCode } = await import("../utils/storage.esm.js");
45
+ const { hasPairedCredentials, sessionStartupPolicy } = await import("./session-startup-policy.js");
46
+ const store = require("../db/store.cjs");
47
+ const { initializeScheduledJobs, stopAllScheduledJobs } = require("../../scheduler.cjs");
48
+
49
+ // Runtime, CA store and (when connection debug logging is on) every
50
+ // outbound socket. See src/diagnostics/nodeRuntime.cjs.
51
+ require("../diagnostics/nodeRuntime.cjs").installNodeDiagnostics();
43
52
 
44
53
  // Temp media the commands write while answering lives with the rest of the
45
54
  // bot's state, not next to the code.
@@ -54,10 +63,6 @@ export async function bootstrapCore({ autoStart = false } = {}) {
54
63
  logger.warn({ err: error }, "[crash-reports] boot sweep failed");
55
64
  }
56
65
 
57
- // A `creds` row alone is not enough: Baileys creates one before pairing.
58
- // `me.id` is the durable proof that this install was actually linked.
59
- const wasPaired = hasPairedCredentials(store.authRead("creds"));
60
-
61
66
  await initStore();
62
67
  await loadCommands();
63
68
 
@@ -79,13 +84,46 @@ export async function bootstrapCore({ autoStart = false } = {}) {
79
84
  // panel does — nothing here ever touches a socket directly.
80
85
  require("../core/session-holder.cjs").setSession(session);
81
86
 
82
- const startup = sessionStartupPolicy({ autoStart, wasPaired });
87
+ // One recovery before any socket. The session owns marker read/write errors:
88
+ // unreadable progress stays ERROR unlink_incomplete without crashing boot.
89
+ const unlinkPending = await session.recoverPendingUnlink();
90
+
91
+ let stopExtensions = async () => {};
92
+ try {
93
+ const { host } = require("../extensions/host.cjs");
94
+ const entitlement = require("../extensions/entitlement/index.cjs");
95
+ await host.start();
96
+ entitlement.start();
97
+ stopExtensions = async () => {
98
+ await host.stop();
99
+ entitlement.stop();
100
+ };
101
+ } catch (error) {
102
+ logger.warn({ err: error }, "[extensions] host failed to start");
103
+ }
104
+
105
+ // A `creds` row alone is not enough: Baileys creates one before pairing.
106
+ // `me.id` is the durable proof that this install was actually linked.
107
+ // Read after the retry so a wipe that just finished is not resumed.
108
+ const wasPaired = hasPairedCredentials(store.authRead("creds"));
109
+ const startup = sessionStartupPolicy({
110
+ autoStart,
111
+ wasPaired,
112
+ unlinkPending,
113
+ });
83
114
  if (startup.start) await session.start({ reason: startup.reason });
84
115
 
116
+ // Remote Terms. An empty trusted-key list makes this a no-op: no timer and
117
+ // no request. The first refresh is a minute after boot, off the #open path.
118
+ const { startRemoteTermsSchedule } = require("../legal/remote.cjs");
119
+ const stopRemoteTerms = startRemoteTermsSchedule();
120
+
85
121
  return {
86
122
  session,
87
123
  commandCount: getLoadedCommands().size,
88
124
  wasPaired,
125
+ stopRemoteTerms,
126
+ stopExtensions,
89
127
  /** The live socket, or null. Re-read it; a reconnect replaces it. */
90
128
  get sock() {
91
129
  return session.socket;
@@ -11,7 +11,7 @@ const fs = require("node:fs");
11
11
  const logger = require("../utils/logger.cjs");
12
12
  const settings = require("../config/settings.cjs");
13
13
  const paths = require("../config/paths.cjs");
14
- const { attach } = require("./events.cjs");
14
+ const { attach, emit } = require("./events.cjs");
15
15
 
16
16
  /** Unix socket path for the Android host. Bionic Node cannot bind TCP. */
17
17
  export function androidPanelSocketPath() {
@@ -47,6 +47,52 @@ export async function bootstrapPanel({ core } = {}) {
47
47
  "../routes/dashboard.api.esm.js"
48
48
  );
49
49
  const stickerApi = await import("../routes/stickers.api.esm.js");
50
+ const backupApi = await import("../routes/backup.api.esm.js");
51
+ const reactionsApi = await import("../routes/reactions.api.esm.js");
52
+ const { createPlusRouter } = await import("../routes/plus.api.esm.js");
53
+ require("../backup/jobs.cjs").sweepBackupTemp();
54
+ require("../backup/uploads.cjs").sweepUploads(true);
55
+
56
+ // Plus extension panel API. Same auth as the rest of the dashboard; a
57
+ // tighter JSON cap than the 2mb dashboard parser. /plus/status, /prepare,
58
+ // /claim and /refresh are mounted with the dashboard API below.
59
+ const express = require("express");
60
+ const { host: plusHost } = require("../extensions/host.cjs");
61
+ const entitlement = require("../extensions/entitlement/index.cjs");
62
+ entitlement.subscribe(() => emit("plus_status", {}));
63
+ plusHost.subscribe(() => emit("plus_status", {}));
64
+ const plusApi = createPlusRouter({
65
+ entitlement,
66
+ extensionStatus: () => ({ state: plusHost.status().state }),
67
+ });
68
+ app.use(
69
+ "/dashboard/api/plus/ext",
70
+ requireLoginApi,
71
+ noStore,
72
+ express.json({ limit: "64kb" }),
73
+ (req, res) => {
74
+ Promise.resolve(plusHost.handlePanel(req.method, req.url || "/", req.body, req.signal))
75
+ .then((result) => {
76
+ const status = result?.status || 404;
77
+ res.status(status).json(result?.body ?? { error: "not_found" });
78
+ })
79
+ .catch((error) => {
80
+ logger.error({ err: error }, "[plus] panelApi failed");
81
+ res.status(500).json({ error: "internal" });
82
+ });
83
+ },
84
+ );
85
+
86
+ app.use(
87
+ "/dashboard/api/plus",
88
+ requireLoginApi,
89
+ noStore,
90
+ express.json({ limit: "4kb" }),
91
+ (err, req, res, next) => {
92
+ if (res.headersSent) return next(err);
93
+ res.status(400).json({ ok: false, code: "BAD_REQUEST" });
94
+ },
95
+ );
50
96
 
51
97
  // Same session as the control panel. One chain and one JSON parser: the
52
98
  // sticker upload is raw bytes (any Content-Type, up to the upload cap) and
@@ -55,8 +101,11 @@ export async function bootstrapPanel({ core } = {}) {
55
101
  "/dashboard/api",
56
102
  requireLoginApi,
57
103
  noStore,
58
- stickerApi.jsonUnlessStickerUpload(dashboardJson),
104
+ stickerApi.jsonUnlessStickerUpload(backupApi.jsonUnlessBackupUpload(dashboardJson)),
59
105
  stickerApi.default,
106
+ backupApi.default,
107
+ reactionsApi.default,
108
+ plusApi,
60
109
  dashboardApiRoutes,
61
110
  );
62
111
  logger.info("Dashboard API routes registered");
@@ -77,6 +126,8 @@ export async function bootstrapPanel({ core } = {}) {
77
126
  if (core?.session) {
78
127
  setSession(core.session);
79
128
  stickerApi.setSession(core.session);
129
+ reactionsApi.setSession(core.session);
130
+ require("../backup/jobs.cjs").setSession(core.session);
80
131
  }
81
132
  // The WhatsApp-code password reset talks to the same session manager.
82
133
  if (core?.session) require("../panel/password-reset.cjs").setSession(core.session);
@@ -19,7 +19,14 @@ export function hasPairedCredentials(rawCreds) {
19
19
  // Panel mode must not create a fresh pairing attempt on a brand-new install,
20
20
  // but once a real pairing exists a process restart should restore that session
21
21
  // automatically. Headless has no Start button, so it always forces a start.
22
- export function sessionStartupPolicy({ autoStart = false, wasPaired = false } = {}) {
22
+ // An unfinished unlink is neither: the credentials may still be the old
23
+ // account, so boot must not resume or auto-start until the wipe completes.
24
+ export function sessionStartupPolicy({
25
+ autoStart = false,
26
+ wasPaired = false,
27
+ unlinkPending = false,
28
+ } = {}) {
29
+ if (unlinkPending) return { start: false, reason: "unlink_incomplete" };
23
30
  if (autoStart) return { start: true, reason: "autostart" };
24
31
  if (wasPaired) return { start: true, reason: "resume-paired" };
25
32
  return { start: false, reason: null };
package/src/cli.js CHANGED
@@ -10,22 +10,41 @@ import { createRequire } from "node:module";
10
10
  const require = createRequire(import.meta.url);
11
11
  const pkg = require("../package.json");
12
12
 
13
- const MIN_MAJOR = 24;
13
+ // Official builds and tests use Node 24. Older majors lack what Levix needs
14
+ // and are refused. Newer majors start with a warning: no official build or
15
+ // test runs on them.
16
+ const SUPPORTED_MAJOR = 24;
14
17
 
15
18
  function checkNode() {
16
- const major = Number(process.versions.node.split(".")[0]);
17
- if (major >= MIN_MAJOR) return;
19
+ const version = process.versions.node;
20
+ const major = Number(version.split(".")[0]);
21
+ if (major === SUPPORTED_MAJOR) return;
22
+
23
+ if (major > SUPPORTED_MAJOR) {
24
+ console.error(
25
+ [
26
+ "",
27
+ ` Warning: Node ${version} is newer than Node ${SUPPORTED_MAJOR}, ` +
28
+ `the version ${pkg.name} is built and`,
29
+ ` tested on. It will start, but Node ${version} is not officially supported, and`,
30
+ " help with problems on it is best effort. For a supported setup, install",
31
+ ` Node ${SUPPORTED_MAJOR} LTS from https://nodejs.org.`,
32
+ "",
33
+ ].join("\n"),
34
+ );
35
+ return;
36
+ }
18
37
 
19
38
  console.error(
20
39
  [
21
40
  "",
22
- ` ${pkg.name} needs Node ${MIN_MAJOR} or newer (you have ${process.versions.node}).`,
41
+ ` ${pkg.name} needs Node ${SUPPORTED_MAJOR} (you have ${version}).`,
23
42
  "",
24
43
  " It stores everything in SQLite, which Node ships with itself from",
25
- ` version ${MIN_MAJOR} on — that is what makes the install a single command`,
44
+ ` version ${SUPPORTED_MAJOR} on — that is what makes the install a single command`,
26
45
  " with nothing to compile.",
27
46
  "",
28
- " Get it from https://nodejs.org (pick the LTS build).",
47
+ ` Get Node ${SUPPORTED_MAJOR} LTS from https://nodejs.org.`,
29
48
  "",
30
49
  ].join("\n"),
31
50
  );
@@ -43,6 +62,8 @@ function help() {
43
62
  " levix headless start Levix with no web UI at all",
44
63
  " levix where print the data directory",
45
64
  " levix reset-password reset the panel password",
65
+ " levix terms read and accept the Terms of Use",
66
+ " (show · status · accept · revoke)",
46
67
  " levix domain [name] point a domain at Levix (may need sudo)",
47
68
  "",
48
69
  " Options",
@@ -61,30 +82,123 @@ function help() {
61
82
  // The command is the first argument that isn't a flag or a flag's value.
62
83
  // `levix --data /var/lib/levix where` has to run `where`, not start the bot —
63
84
  // which is exactly how someone debugging a systemd install types it.
64
- const FLAGS_WITH_VALUES = new Set(["--data"]);
85
+ const FLAGS_WITH_VALUES = new Set(["--data", "--terms-version", "--sha256", "--lang"]);
65
86
 
66
87
  export function parseArgv(argv) {
67
88
  const flags = new Set();
89
+ const values = new Map();
68
90
  const positional = [];
69
91
 
70
92
  for (let i = 2; i < argv.length; i += 1) {
71
93
  const arg = argv[i];
72
94
  if (FLAGS_WITH_VALUES.has(arg)) {
73
- i += 1; // skip its value
95
+ // A value flag given last with no argument is present-but-empty, so
96
+ // `accept` and `--lang` fail closed instead of inheriting a default.
97
+ if (i + 1 >= argv.length) {
98
+ values.set(arg, "");
99
+ continue;
100
+ }
101
+ values.set(arg, argv[i + 1]);
102
+ i += 1;
74
103
  continue;
75
104
  }
76
105
  if (arg.startsWith("-")) {
77
- flags.add(arg.split("=")[0]);
106
+ const [name, ...rest] = arg.split("=");
107
+ flags.add(name);
108
+ if (rest.length && FLAGS_WITH_VALUES.has(name)) values.set(name, rest.join("="));
78
109
  continue;
79
110
  }
80
111
  positional.push(arg);
81
112
  }
82
113
 
83
- return { command: positional[0] ?? null, positional, flags };
114
+ return { command: positional[0] ?? null, positional, flags, values };
115
+ }
116
+
117
+ /** Run data access as the data directory owner; keep domain setup privileged. */
118
+ export function createCliDataIdentity({
119
+ proc = process,
120
+ fs = require("node:fs"),
121
+ dataDir,
122
+ } = {}) {
123
+ const direct = async (fn) => fn();
124
+ if (proc.getuid?.() !== 0) return direct;
125
+
126
+ const directory = dataDir ?? require("./config/data-dir.cjs").DATA_DIR;
127
+ let owner;
128
+ try {
129
+ owner = fs.lstatSync(directory);
130
+ } catch (error) {
131
+ if (error.code === "ENOENT") {
132
+ throw new Error("Create the Levix data directory as the service user before running this command with sudo");
133
+ }
134
+ throw error;
135
+ }
136
+ if (owner.isSymbolicLink() || !owner.isDirectory()) {
137
+ throw new Error("Levix data directory must be a real directory for sudo commands");
138
+ }
139
+ if (owner.uid === 0) return direct;
140
+
141
+ return async (fn) => {
142
+ proc.setegid(owner.gid);
143
+ let changedUid = false;
144
+ try {
145
+ proc.seteuid(owner.uid);
146
+ changedUid = true;
147
+ return await fn();
148
+ } finally {
149
+ try {
150
+ if (changedUid) proc.seteuid(0);
151
+ } finally {
152
+ proc.setegid(0);
153
+ }
154
+ }
155
+ };
156
+ }
157
+
158
+ /** CLI commands that use settings share the same lock and schema boundary. */
159
+ export async function withCliDatabase(fn) {
160
+ const asDataOwner = createCliDataIdentity();
161
+ const { DATA_UNAVAILABLE } = (await import("./config/exit-codes.cjs")).default;
162
+ let lock;
163
+ let database;
164
+ let ownsLock = false;
165
+ try {
166
+ const ready = await asDataOwner(async () => {
167
+ lock = (await import("./config/lock.cjs")).default;
168
+ database = (await import("./db/db.cjs")).default;
169
+ try {
170
+ lock.acquireSingleInstanceLock();
171
+ ownsLock = true;
172
+ } catch (error) {
173
+ if (error.code !== "ELEVIXLOCKED") throw error;
174
+ }
175
+ if (ownsLock) {
176
+ await database.prepareDatabase();
177
+ await (await import("./backup/recovery.cjs")).default.runRestoreRecovery();
178
+ } else {
179
+ const current = database.schemaVersion(database.openWithoutMigration());
180
+ if (current !== database.MIGRATIONS.length) {
181
+ console.error(`Cannot access this data directory while Levix runs: schema ${current} differs from this build's schema ${database.MIGRATIONS.length}. Stop Levix and use the matching version.`);
182
+ return false;
183
+ }
184
+ }
185
+ return true;
186
+ });
187
+ if (!ready) return DATA_UNAVAILABLE;
188
+ return await fn(asDataOwner);
189
+ } finally {
190
+ if (database) await asDataOwner(async () => {
191
+ try {
192
+ database.close();
193
+ } finally {
194
+ if (ownsLock) lock.release();
195
+ }
196
+ });
197
+ }
84
198
  }
85
199
 
86
200
  export async function main(argv = process.argv) {
87
- const { command, positional, flags } = parseArgv(argv);
201
+ const { command, positional, flags, values } = parseArgv(argv);
88
202
 
89
203
  if (flags.has("--help") || flags.has("-h") || command === "help") {
90
204
  help();
@@ -106,19 +220,35 @@ export async function main(argv = process.argv) {
106
220
  }
107
221
 
108
222
  case "reset-password": {
109
- const store = (await import("./db/store.cjs")).default;
110
- const { close } = await import("./db/db.cjs");
111
- store.deleteBotSetting("auth:password");
112
- close();
113
- console.log("\n Password cleared. Start the bot and open the panel to choose a new one.\n");
114
- return 0;
223
+ return withCliDatabase(async (asDataOwner) => {
224
+ const store = (await import("./db/store.cjs")).default;
225
+ await asDataOwner(() => store.deleteBotSetting("auth:password"));
226
+ console.log("\n Password cleared. Start the bot and open the panel to choose a new one.\n");
227
+ return 0;
228
+ });
229
+ }
230
+
231
+ case "terms": {
232
+ const { runTerms, terminalIo } = (await import("./legal/cli.cjs")).default;
233
+ const io = terminalIo();
234
+ // `show` only prints the bundled documents. Opening the database would
235
+ // migrate it and run restore recovery, which is a write.
236
+ if ((positional[1] ?? null) === "show") {
237
+ return runTerms({ positional, values, io });
238
+ }
239
+ return withCliDatabase(async (asDataOwner) =>
240
+ runTerms({ positional, values, io, asDataOwner }),
241
+ );
115
242
  }
116
243
 
117
244
  case "domain": {
118
- const { runDomainCommand } = await import("./domain/command.js");
119
- return runDomainCommand({
120
- domain: positional[1] ?? null,
121
- assumeYes: flags.has("--yes") || flags.has("-y"),
245
+ return withCliDatabase(async (asDataOwner) => {
246
+ const { runDomainCommand } = await import("./domain/command.js");
247
+ return runDomainCommand({
248
+ domain: positional[1] ?? null,
249
+ assumeYes: flags.has("--yes") || flags.has("-y"),
250
+ asDataOwner,
251
+ });
122
252
  });
123
253
  }
124
254
 
@@ -143,7 +273,18 @@ export async function main(argv = process.argv) {
143
273
 
144
274
  /** Entry point for bin/levix.js and for the packaged executable. */
145
275
  export async function run(argv = process.argv) {
146
- const code = await main(argv);
276
+ let code;
277
+ try {
278
+ code = await main(argv);
279
+ } catch (error) {
280
+ const classified = (await import("./config/exit-codes.cjs")).default.exitCodeFor(error);
281
+ if (classified !== null) {
282
+ console.error(error.message);
283
+ code = classified;
284
+ } else {
285
+ throw error;
286
+ }
287
+ }
147
288
  // `null` means "the bot is running now" — exiting would kill it.
148
289
  if (code !== null) process.exit(code);
149
290
  }
@@ -1,4 +1,4 @@
1
- const { tr } = require("../utils/i18n.cjs");
1
+ const { t } = require("../utils/i18n.cjs");
2
2
  const logger = require("../utils/logger.cjs");
3
3
  const autoDelete = require("../services/autoDelete.cjs");
4
4
 
@@ -28,31 +28,28 @@ function parseIdArg(value) {
28
28
  }
29
29
 
30
30
  function formatRule(rule) {
31
- const state = rule.enabled ? tr("on", "تشغيل") : tr("off", "إيقاف");
31
+ const state = rule.enabled ? t("bot.moderation.autodelete.on") : t("bot.moderation.autodelete.off");
32
32
  const label = rule.name ? ` "${rule.name}"` : "";
33
33
  const keywords = rule.keywords.join(", ");
34
- return tr(
35
- `#${rule.id}${label} · ${state} · ${rule.match} · ${rule.keywords.length} keyword(s) · deleted ${rule.deletedCount}\n ${keywords}`,
36
- `#${rule.id}${label} · ${state} · ${rule.match} · ${rule.keywords.length} كلمة · حُذف ${rule.deletedCount}\n ${keywords}`,
37
- );
34
+ return t("bot.moderation.autodelete.ruleListLine", {
35
+ id: rule.id,
36
+ label,
37
+ state,
38
+ match: rule.match,
39
+ keywordCount: rule.keywords.length,
40
+ deletedCount: rule.deletedCount,
41
+ keywords,
42
+ });
38
43
  }
39
44
 
40
45
  function formatWhen(ts) {
41
- if (!ts) return tr("never", "أبداً");
46
+ if (!ts) return t("bot.moderation.autodelete.never");
42
47
  return new Date(ts).toISOString();
43
48
  }
44
49
 
45
50
  module.exports = {
46
51
  name: "autodelete",
47
52
  aliases: [...autoDelete.DECLARED_ALIASES],
48
- description: {
49
- en: "Manages keyword auto-delete rules: add, remove, enable, disable, and counters.",
50
- ar: "يدير قواعد الحذف التلقائي حسب الكلمات: إضافة وإزالة وتشغيل وإيقاف والعداد.",
51
- },
52
- usage: {
53
- en: "autodelete list\nautodelete add <word> [| <word> ...]\nautodelete remove <id>\nautodelete on <id>\nautodelete off <id>\nautodelete stats [id]\nautodelete reset <id>",
54
- ar: "autodelete list\nautodelete add <كلمة> [| <كلمة> ...]\nautodelete remove <id>\nautodelete on <id>\nautodelete off <id>\nautodelete stats [id]\nautodelete reset <id>",
55
- },
56
53
  chat: "all",
57
54
  keywords: [
58
55
  ...LIST_WORDS,
@@ -73,13 +70,10 @@ module.exports = {
73
70
  const rules = autoDelete.listRules();
74
71
  if (!rules.length) {
75
72
  return sock.sendMessage(jid, {
76
- text: tr("No auto-delete rules yet.", "لا توجد قواعد حذف تلقائي بعد."),
73
+ text: t("bot.moderation.autodelete.noAutoDeleteRulesYet"),
77
74
  });
78
75
  }
79
- const header = tr(
80
- `*Auto-delete rules (${rules.length}):*\n\n`,
81
- `*قواعد الحذف التلقائي (${rules.length}):*\n\n`,
82
- );
76
+ const header = t("bot.moderation.autodelete.autoDeleteRules", { count: rules.length });
83
77
  return sock.sendMessage(jid, {
84
78
  text: header + rules.map(formatRule).join("\n"),
85
79
  });
@@ -89,10 +83,7 @@ module.exports = {
89
83
  const keywords = parseKeywords(args.slice(1));
90
84
  if (!keywords.length) {
91
85
  return sock.sendMessage(jid, {
92
- text: tr(
93
- "Write one or more words to auto-delete, separated by |.",
94
- "اكتب كلمة أو أكثر للحذف التلقائي، مفصولة بـ |.",
95
- ),
86
+ text: t("bot.moderation.autodelete.writeOneOrMoreWords"),
96
87
  });
97
88
  }
98
89
  const rule = autoDelete.createRule({
@@ -106,10 +97,10 @@ module.exports = {
106
97
  enabled: true,
107
98
  });
108
99
  return sock.sendMessage(jid, {
109
- text: tr(
110
- `Added auto-delete rule #${rule.id} (${rule.keywords.join(", ")}).`,
111
- `تمت إضافة قاعدة الحذف التلقائي #${rule.id} (${rule.keywords.join(", ")}).`,
112
- ),
100
+ text: t("bot.moderation.autodelete.addedAutoDeleteRule", {
101
+ id: rule.id,
102
+ keywords: rule.keywords.join(", "),
103
+ }),
113
104
  });
114
105
  }
115
106
 
@@ -117,12 +108,12 @@ module.exports = {
117
108
  const id = parseIdArg(args[1]);
118
109
  if (!id) {
119
110
  return sock.sendMessage(jid, {
120
- text: tr("Give a rule id to remove.", "أدخل رقم القاعدة للحذف."),
111
+ text: t("bot.moderation.autodelete.ruleIdToRemoveRequired"),
121
112
  });
122
113
  }
123
114
  autoDelete.deleteRule(id);
124
115
  return sock.sendMessage(jid, {
125
- text: tr(`Removed auto-delete rule #${id}.`, `تم حذف قاعدة الحذف التلقائي #${id}.`),
116
+ text: t("bot.moderation.autodelete.removedAutoDeleteRule", { id }),
126
117
  });
127
118
  }
128
119
 
@@ -130,15 +121,15 @@ module.exports = {
130
121
  const id = parseIdArg(args[1]);
131
122
  if (!id) {
132
123
  return sock.sendMessage(jid, {
133
- text: tr("Give a rule id.", "أدخل رقم القاعدة."),
124
+ text: t("bot.moderation.autodelete.giveARuleId"),
134
125
  });
135
126
  }
136
127
  const enabled = ON_WORDS.has(action);
137
128
  autoDelete.updateRule(id, { enabled });
138
129
  return sock.sendMessage(jid, {
139
130
  text: enabled
140
- ? tr(`Auto-delete rule #${id} is on.`, `قاعدة الحذف التلقائي #${id} مفعّلة.`)
141
- : tr(`Auto-delete rule #${id} is off.`, `قاعدة الحذف التلقائي #${id} موقوفة.`),
131
+ ? t("bot.moderation.autodelete.autoDeleteRuleIsOn", { id })
132
+ : t("bot.moderation.autodelete.autoDeleteRuleIsOff", { id }),
142
133
  });
143
134
  }
144
135
 
@@ -147,24 +138,26 @@ module.exports = {
147
138
  const id = parseIdArg(args[1]);
148
139
  if (!id) {
149
140
  return sock.sendMessage(jid, {
150
- text: tr("Give a rule id.", "أدخل رقم القاعدة."),
141
+ text: t("bot.moderation.autodelete.giveARuleId"),
151
142
  });
152
143
  }
153
144
  const rule = autoDelete.getRule(id);
154
145
  return sock.sendMessage(jid, {
155
- text: tr(
156
- `*Rule #${rule.id}*${rule.name ? ` ${rule.name}` : ""}\nDeleted: ${rule.deletedCount}\nLast: ${formatWhen(rule.lastDeletedAt)}`,
157
- `*القاعدة #${rule.id}*${rule.name ? ` ${rule.name}` : ""}\nحُذف: ${rule.deletedCount}\nآخر مرة: ${formatWhen(rule.lastDeletedAt)}`,
158
- ),
146
+ text: t("bot.moderation.autodelete.ruleStats", {
147
+ id: rule.id,
148
+ name: rule.name ? ` ${rule.name}` : "",
149
+ deletedCount: rule.deletedCount,
150
+ last: formatWhen(rule.lastDeletedAt),
151
+ }),
159
152
  });
160
153
  }
161
154
  const rules = autoDelete.listRules();
162
155
  const total = rules.reduce((sum, rule) => sum + (rule.deletedCount || 0), 0);
163
156
  return sock.sendMessage(jid, {
164
- text: tr(
165
- `*Auto-delete counters*\nRules: ${rules.length}\nDeleted: ${total}`,
166
- `*عدادات الحذف التلقائي*\nالقواعد: ${rules.length}\nحُذف: ${total}`,
167
- ),
157
+ text: t("bot.moderation.autodelete.autoDeleteCountersRulesDeleted", {
158
+ count: rules.length,
159
+ total,
160
+ }),
168
161
  });
169
162
  }
170
163
 
@@ -172,41 +165,32 @@ module.exports = {
172
165
  const id = parseIdArg(args[1]);
173
166
  if (!id) {
174
167
  return sock.sendMessage(jid, {
175
- text: tr("Give a rule id to reset.", "أدخل رقم القاعدة لتصفير العداد."),
168
+ text: t("bot.moderation.autodelete.ruleIdToResetRequired"),
176
169
  });
177
170
  }
178
171
  autoDelete.resetCounter(id);
179
172
  return sock.sendMessage(jid, {
180
- text: tr(
181
- `Reset the counter for auto-delete rule #${id}.`,
182
- `تم تصفير عداد قاعدة الحذف التلقائي #${id}.`,
183
- ),
173
+ text: t("bot.moderation.autodelete.resetTheCounterForAuto", { id }),
184
174
  });
185
175
  }
186
176
 
187
177
  return sock.sendMessage(jid, {
188
- text: tr(
189
- "Unknown sub-command. Try list, add, remove, on, off, stats, reset.",
190
- "أمر فرعي غير معروف. جرّب list أو add أو remove أو on أو off أو stats أو reset.",
191
- ),
178
+ text: t("bot.moderation.autodelete.unknownSubCommandTryList"),
192
179
  });
193
180
  } catch (error) {
194
181
  if (error?.status === 404) {
195
182
  return sock.sendMessage(jid, {
196
- text: tr("No auto-delete rule with that id.", "لا توجد قاعدة حذف تلقائي بهذا الرقم."),
183
+ text: t("bot.moderation.autodelete.noAutoDeleteRuleWith"),
197
184
  });
198
185
  }
199
186
  if (error?.name === "AutoDeleteError" || error?.status === 400) {
200
187
  return sock.sendMessage(jid, {
201
- text: tr(
202
- `Could not update that rule: ${error.message}`,
203
- `تعذر تحديث القاعدة: ${error.message}`,
204
- ),
188
+ text: t("bot.moderation.autodelete.couldNotUpdateThatRule", { message: error.message }),
205
189
  });
206
190
  }
207
191
  logger.error({ err: error, command: "autodelete" }, "auto-delete command failed");
208
192
  return sock.sendMessage(jid, {
209
- text: tr("Something went wrong with auto-delete.", "حدث خطأ أثناء معالجة الحذف التلقائي."),
193
+ text: t("bot.moderation.autodelete.somethingWentWrongWithAuto"),
210
194
  });
211
195
  }
212
196
  },