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
@@ -50,6 +50,7 @@ const COMMAND_PERMISSIONS = Object.freeze({
50
50
  restart: "OWNER_ONLY",
51
51
  stopbot: "OWNER_ONLY",
52
52
  status: "OWNER_ONLY",
53
+ update: "OWNER_ONLY",
53
54
  lang: "MEMBERS",
54
55
  digit: "MEMBERS",
55
56
  md: "MEMBERS",
@@ -0,0 +1,11 @@
1
+ const DATA_UNAVAILABLE = 78;
2
+ const DATA_ERRORS = new Set([
3
+ "SCHEMA_NEWER", "BACKUP_FAILED", "MIGRATION_FAILED", "DATABASE_NOT_PREPARED",
4
+ "ACTIVATION_RECOVERY_FAILED",
5
+ ]);
6
+
7
+ function exitCodeFor(error) {
8
+ return DATA_ERRORS.has(error?.code) ? DATA_UNAVAILABLE : null;
9
+ }
10
+
11
+ module.exports = { DATA_UNAVAILABLE, exitCodeFor };
@@ -1,110 +1,84 @@
1
- // One bot process per data directory.
2
- //
3
- // A WhatsApp pairing is a single session. Two Levix processes on one database
4
- // would both hold the same Baileys credentials, overwrite each other's session
5
- // keys, and answer every message twice — and the second one would only fail
6
- // much later, when it tried to bind the panel's port, long after it had
7
- // touched the auth rows.
8
- //
9
- // So the bot claims the data directory before it does anything else. This is a
10
- // lock file with a pid in it, which is the simplest thing that works on a
11
- // single machine — which is the only place a WhatsApp pairing can run anyway.
12
- // No daemon, no distributed anything.
13
- //
14
- // The CLI's read-only and recovery commands (`where`, `reset-password`) do NOT
15
- // take this lock: they have to work while the bot is running, or when it is
16
- // wedged, which is the whole point of having them.
17
-
1
+ // SQLite holds this lock until the connection closes, including on a crash.
2
+ // The text file is only a pid hint for a useful error message.
18
3
  const fs = require("node:fs");
19
-
4
+ const { DatabaseSync } = require("node:sqlite");
20
5
  const { dataPath } = require("./paths.cjs");
21
- const logger = require("../utils/logger.cjs");
22
6
 
23
7
  const LOCK_FILE = dataPath("levix.lock");
8
+ const LOCK_DB_FILE = dataPath("levix.lock.db");
9
+ let connection = null;
24
10
 
25
- /** Is that pid a process that still exists? */
26
11
  function processAlive(pid) {
27
12
  if (!Number.isInteger(pid) || pid <= 0) return false;
28
13
  try {
29
- // Signal 0 checks for existence without delivering anything.
30
14
  process.kill(pid, 0);
31
15
  return true;
32
- } catch (err) {
33
- // EPERM means it exists and belongs to somebody else — still alive.
34
- return err.code === "EPERM";
16
+ } catch (error) {
17
+ return error.code === "EPERM";
35
18
  }
36
19
  }
37
20
 
38
- function readLock() {
21
+ function readPid() {
39
22
  try {
40
- const raw = fs.readFileSync(LOCK_FILE, "utf8");
41
- const pid = Number.parseInt(String(raw).trim(), 10);
42
- return Number.isFinite(pid) ? pid : null;
23
+ const pid = Number.parseInt(fs.readFileSync(LOCK_FILE, "utf8").trim(), 10);
24
+ return Number.isInteger(pid) && pid > 0 ? pid : "unknown";
43
25
  } catch {
44
- return null;
26
+ return "unknown";
45
27
  }
46
28
  }
47
29
 
48
- let held = false;
30
+ function lockedError() {
31
+ const error = new Error(
32
+ `Another Levix (pid ${readPid()}) is already using this data directory.\n` +
33
+ ` ${LOCK_FILE}\n\n` +
34
+ ` Only one Levix can run per data directory. Stop the other one, or use --data.`,
35
+ );
36
+ error.code = "ELEVIXLOCKED";
37
+ return error;
38
+ }
49
39
 
50
40
  function release() {
51
- if (!held) return;
52
- held = false;
41
+ if (!connection) return;
53
42
  try {
54
- // Only remove it if it is still ours — a stale-lock takeover elsewhere
55
- // could have replaced it.
56
- if (readLock() === process.pid) fs.unlinkSync(LOCK_FILE);
43
+ if (readPid() === process.pid) fs.rmSync(LOCK_FILE, { force: true });
57
44
  } catch {}
45
+ connection.close();
46
+ connection = null;
58
47
  }
59
48
 
60
- /**
61
- * Claim the data directory for this process.
62
- *
63
- * @throws {Error} when another live Levix already holds it. The message is
64
- * written for whoever is reading the terminal, not for a stack trace.
65
- */
66
- function acquireSingleInstanceLock() {
67
- if (held) return LOCK_FILE;
68
-
69
- const claim = () => {
70
- // "wx" fails if the file exists — the check and the create are one
71
- // syscall, so two processes starting together can't both win.
72
- const handle = fs.openSync(LOCK_FILE, "wx");
73
- fs.writeFileSync(handle, String(process.pid));
74
- fs.closeSync(handle);
75
- };
76
-
77
- try {
78
- claim();
79
- } catch (err) {
80
- if (err.code !== "EEXIST") throw err;
49
+ function isLockHeld() {
50
+ return connection !== null;
51
+ }
81
52
 
82
- const owner = readLock();
83
- if (owner !== null && owner !== process.pid && processAlive(owner)) {
84
- const error = new Error(
85
- `Another Levix (pid ${owner}) is already using this data directory.\n` +
86
- ` ${LOCK_FILE}\n\n` +
87
- ` Only one Levix can run per data directory — a WhatsApp pairing is a\n` +
88
- ` single session. Stop the other one, or start this one with --data\n` +
89
- ` pointing somewhere else.`,
90
- );
91
- error.code = "ELEVIXLOCKED";
92
- throw error;
53
+ function acquireSingleInstanceLock() {
54
+ if (connection) return LOCK_FILE;
55
+ // Two fresh SQLite connections can both hold a shared lock and fail to
56
+ // promote it. Close before retrying so neither prevents the other winning.
57
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
58
+ for (let attempt = 0; attempt < 10; attempt += 1) {
59
+ let candidate;
60
+ try {
61
+ candidate = new DatabaseSync(LOCK_DB_FILE);
62
+ candidate.exec("PRAGMA busy_timeout = 0");
63
+ candidate.exec("PRAGMA locking_mode = EXCLUSIVE");
64
+ candidate.exec("BEGIN EXCLUSIVE");
65
+ candidate.exec("CREATE TABLE IF NOT EXISTS owner (pid INTEGER NOT NULL)");
66
+ candidate.exec("DELETE FROM owner");
67
+ candidate.prepare("INSERT INTO owner (pid) VALUES (?)").run(process.pid);
68
+ candidate.exec("COMMIT");
69
+ connection = candidate;
70
+ fs.writeFileSync(LOCK_FILE, String(process.pid), { mode: 0o600 });
71
+ process.once("exit", release);
72
+ return LOCK_FILE;
73
+ } catch (error) {
74
+ candidate?.close();
75
+ if (connection === candidate) connection = null;
76
+ const busy = error.code === "SQLITE_BUSY" || error.errcode === 5 || /database is locked/i.test(error.message);
77
+ if (!busy) throw error;
78
+ if (attempt === 9) throw lockedError();
79
+ Atomics.wait(sleeper, 0, 0, 1 + Math.floor(Math.random() * 25));
93
80
  }
94
-
95
- // The holder is gone (a crash, a kill -9, a reboot). Take it over.
96
- logger.warn(
97
- `[lock] Removing a stale lock from pid ${owner ?? "unknown"} — that process is gone`,
98
- );
99
- fs.rmSync(LOCK_FILE, { force: true });
100
- claim();
101
81
  }
102
-
103
- held = true;
104
- // Best effort: a SIGKILL or a power cut leaves the file behind, which the
105
- // stale check above handles on the next start.
106
- process.once("exit", release);
107
- return LOCK_FILE;
108
82
  }
109
83
 
110
- module.exports = { acquireSingleInstanceLock, release, LOCK_FILE, processAlive };
84
+ module.exports = { acquireSingleInstanceLock, release, isLockHeld, LOCK_FILE, LOCK_DB_FILE, processAlive };
@@ -0,0 +1,61 @@
1
+ // src/config/official-links.cjs
2
+ // Official links and trustworthy external navigation validator (Phase 09).
3
+ //
4
+ // Links are frozen constants representing official Levix destinations.
5
+ // safeOfficialUrl() ensures only exact official destinations or validated
6
+ // GitHub release detail URLs are accepted, preventing arbitrary redirects,
7
+ // credential spoofing, port injection, or hash injection.
8
+
9
+ const LINKS = Object.freeze({
10
+ website: "https://levix.leviro.net",
11
+ docs: "https://levix.leviro.net/docs",
12
+ github: "https://github.com/Abdodiab2005/levix",
13
+ releases: "https://github.com/Abdodiab2005/levix/releases",
14
+ play: "https://play.google.com/store/apps/details?id=net.leviro.levix",
15
+ studio: "https://leviro.net",
16
+ portfolio: "https://abdelrhman.leviro.net",
17
+ support: "https://levix.leviro.net/feedback",
18
+ });
19
+
20
+ const FIXED_URLS = new Set(Object.values(LINKS));
21
+
22
+ // Strict SemVer tag regex: matches v1.2.3, 1.2.3, v5.0.0-beta.1, 5.0.0+android.69
23
+ const TAG_REGEX =
24
+ /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
25
+
26
+ function isValidTag(tag) {
27
+ return typeof tag === "string" && tag.length <= 128 && TAG_REGEX.test(tag);
28
+ }
29
+
30
+ /**
31
+ * Builds a trustworthy release detail URL from a validated tag.
32
+ * Returns null if the tag is not valid SemVer.
33
+ */
34
+ function releaseDetailUrl(tag) {
35
+ if (typeof tag !== "string") return null;
36
+ if (!isValidTag(tag)) return null;
37
+ return `${LINKS.releases}/tag/${tag}`;
38
+ }
39
+
40
+ /**
41
+ * Validates that a URL is an exact official link or a validated version-tag
42
+ * release detail URL. Disallows credentials, non-standard ports, hashes,
43
+ * search parameters (unless part of the exact fixed links), and hostile schemes.
44
+ *
45
+ * @param {unknown} value
46
+ * @returns {boolean}
47
+ */
48
+ function safeOfficialUrl(value) {
49
+ if (typeof value !== "string" || !value) return false;
50
+ if (FIXED_URLS.has(value)) return true;
51
+
52
+ const prefix = `${LINKS.releases}/tag/`;
53
+ return value.startsWith(prefix) && isValidTag(value.slice(prefix.length));
54
+ }
55
+
56
+ module.exports = {
57
+ LINKS,
58
+ safeOfficialUrl,
59
+ releaseDetailUrl,
60
+ isValidTag,
61
+ };
@@ -15,45 +15,16 @@
15
15
  // node_modules) — keeps a developer's data next to the code
16
16
  // 4. `~/.levix` — global installs, packaged binaries, read-only images
17
17
  //
18
- // This module deliberately has no dependencies: the logger and the database
19
- // both need it, and neither can wait for the other.
18
+ // This module has no application dependencies: the logger and database both
19
+ // need it, and neither can wait for the other.
20
20
 
21
21
  const fs = require("node:fs");
22
- const os = require("node:os");
23
22
  const path = require("node:path");
23
+ const { ROOT, DATA_DIR } = require("./data-dir.cjs");
24
24
 
25
- const ROOT = path.join(__dirname, "..", "..");
26
-
27
- function argDataDir() {
28
- const index = process.argv.indexOf("--data");
29
- if (index !== -1 && process.argv[index + 1]) return process.argv[index + 1];
30
- const inline = process.argv.find((arg) => arg.startsWith("--data="));
31
- return inline ? inline.slice("--data=".length) : null;
32
- }
33
-
34
- function isWritable(dir) {
35
- try {
36
- fs.accessSync(dir, fs.constants.W_OK);
37
- return true;
38
- } catch {
39
- return false;
40
- }
41
- }
42
-
43
- function resolveDataDir() {
44
- const explicit = argDataDir() || process.env.LEVIX_DATA_DIR;
45
- if (explicit) return path.resolve(explicit);
46
-
47
- const installed = ROOT.includes(`${path.sep}node_modules${path.sep}`);
48
- if (!installed && isWritable(ROOT)) return path.join(ROOT, "data");
49
-
50
- return path.join(os.homedir(), ".levix");
51
- }
52
-
53
- const DATA_DIR = resolveDataDir();
54
25
  fs.mkdirSync(DATA_DIR, { recursive: true });
55
26
 
56
- // Where the read-only files that ship with the bot live: views/, public/, the
27
+ // Where the read-only files that ship with the bot live: public/ and the
57
28
  // persona template. Normally that is the package itself. A packaged build
58
29
  // (a single executable has no package directory) unpacks them somewhere the
59
30
  // filesystem can see and points this at that copy instead.
@@ -0,0 +1,87 @@
1
+ // The release identity an acceptance is bound to (ADR-020).
2
+ //
3
+ // npm, Docker, the single executable and headless have only the package.json
4
+ // version. An Android archive also ships levix-build.json, written by
5
+ // android/scripts/stage-levix-app.sh, and the identity is
6
+ // "<version>+android.<versionCode>". A missing file is the non-Android case.
7
+ // A file that is present but cannot be read or parsed fails closed, so a
8
+ // broken build cannot keep an acceptance recorded for some other build.
9
+ //
10
+ // The file is read on the first releaseIdentity() call, not when this module
11
+ // loads. Nothing here reads the environment. LEVIX_ANDROID_VERSION_CODE is
12
+ // the stage script's build-time input, not a Node setting.
13
+
14
+ const fs = require("node:fs");
15
+
16
+ const BUILD_FILE = "levix-build.json";
17
+ const VERSION_CODE_MAX = 2100000000;
18
+ const BUILD_KEYS = Object.freeze(["schema", "platform", "versionCode"]);
19
+
20
+ let cachedIdentity;
21
+
22
+ function packageVersion() {
23
+ return String(require("../../package.json").version);
24
+ }
25
+
26
+ function invalidBuildInfo(message) {
27
+ const error = new Error(message);
28
+ error.code = "BUILD_INFO_INVALID";
29
+ return error;
30
+ }
31
+
32
+ /** Pure. Accepts exactly schema 1, platform "android", versionCode 1..2100000000. */
33
+ function parseBuildInfo(text) {
34
+ let value;
35
+ try {
36
+ value = JSON.parse(text);
37
+ } catch {
38
+ throw invalidBuildInfo("levix-build.json is not JSON");
39
+ }
40
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
41
+ throw invalidBuildInfo("levix-build.json must be an object");
42
+ }
43
+ const keys = Object.keys(value);
44
+ if (keys.length !== BUILD_KEYS.length || BUILD_KEYS.some((key) => !Object.hasOwn(value, key))) {
45
+ throw invalidBuildInfo("levix-build.json must have only schema, platform and versionCode");
46
+ }
47
+ if (value.schema !== 1) throw invalidBuildInfo("levix-build.json schema must be 1");
48
+ if (value.platform !== "android") throw invalidBuildInfo("levix-build.json platform must be android");
49
+ const code = value.versionCode;
50
+ if (typeof code !== "number" || !Number.isInteger(code) || code < 1 || code > VERSION_CODE_MAX) {
51
+ throw invalidBuildInfo("levix-build.json versionCode must be an integer from 1 to 2100000000");
52
+ }
53
+ return { schema: 1, platform: "android", versionCode: code };
54
+ }
55
+
56
+ /** Pure. No build info keeps the version; Android appends "+android.<versionCode>". */
57
+ function composeIdentity(version, buildInfo) {
58
+ const base = String(version);
59
+ if (buildInfo == null) return base;
60
+ return `${base}+android.${buildInfo.versionCode}`;
61
+ }
62
+
63
+ function releaseIdentity() {
64
+ if (cachedIdentity !== undefined) return cachedIdentity;
65
+ // Lazy so loading this module does not create the data directory.
66
+ const { assetPath } = require("./paths.cjs");
67
+ const file = assetPath(BUILD_FILE);
68
+ let text;
69
+ try {
70
+ text = fs.readFileSync(file, "utf8");
71
+ } catch (error) {
72
+ if (error && error.code === "ENOENT") {
73
+ cachedIdentity = packageVersion();
74
+ return cachedIdentity;
75
+ }
76
+ throw error;
77
+ }
78
+ // parseBuildInfo runs before the assignment. A bad file is not cached.
79
+ cachedIdentity = composeIdentity(packageVersion(), parseBuildInfo(text));
80
+ return cachedIdentity;
81
+ }
82
+
83
+ module.exports = {
84
+ parseBuildInfo,
85
+ composeIdentity,
86
+ releaseIdentity,
87
+ };
@@ -32,15 +32,34 @@ const SETTINGS = [
32
32
  key: "bot_language",
33
33
  type: "string",
34
34
  default: "auto",
35
- choices: ["auto", "ar", "en"],
35
+ choices: ["auto", "ar", "en", "pt-BR", "es-419"],
36
36
  choiceLabels: {
37
37
  auto: "Auto-detect (follow user message)",
38
38
  ar: "Modern Standard Arabic (العربية الفصحى)",
39
39
  en: "English",
40
+ "pt-BR": "Portuguese (Brazil) (Português)",
41
+ "es-419": "Spanish (Latin America) (Español)",
40
42
  },
41
43
  group: "general",
42
44
  label: "Bot response language",
43
- hint: "Preferred language for AI replies, status updates and !help. Auto follows the language each message is written in. Can also be switched with !lang.",
45
+ hint: "Preferred language for bot replies, status updates and !help. Auto follows the language each message is written in. Can also be switched with !lang.",
46
+ },
47
+ {
48
+ key: "ai_reply_language",
49
+ type: "string",
50
+ default: "follow_bot",
51
+ choices: ["follow_bot", "auto", "ar", "en", "pt-BR", "es-419"],
52
+ choiceLabels: {
53
+ follow_bot: "Follow bot reply language",
54
+ auto: "Auto-detect (follow user message)",
55
+ ar: "Modern Standard Arabic (العربية الفصحى)",
56
+ en: "English",
57
+ "pt-BR": "Portuguese (Brazil) (Português)",
58
+ "es-419": "Spanish (Latin America) (Español)",
59
+ },
60
+ group: "general",
61
+ label: "AI reply language",
62
+ hint: "Follow bot uses the bot reply language. Auto follows the language the user writes in.",
44
63
  },
45
64
  {
46
65
  key: "link_previews_enabled",
@@ -69,6 +88,73 @@ const SETTINGS = [
69
88
  group: "general",
70
89
  label: "Max reply delay (ms)",
71
90
  },
91
+ {
92
+ key: "command_parser",
93
+ type: "string",
94
+ default: "v2",
95
+ choices: ["v1", "v2"],
96
+ choiceLabels: {
97
+ v2: "v2 (newline between a command and its sub-command)",
98
+ v1: "v1 (previous parser)",
99
+ },
100
+ group: "general",
101
+ label: "Command parser",
102
+ hint: "v2 is the current parser. v1 is the previous one, kept for one release. Both still send through the reply router.",
103
+ },
104
+ {
105
+ key: "reply_route",
106
+ type: "string",
107
+ default: "same_chat",
108
+ choices: ["same_chat", "owner_private", "authorized_chat"],
109
+ choiceLabels: {
110
+ same_chat: "Same chat",
111
+ owner_private: "Owner's private chat",
112
+ authorized_chat: "An authorized chat",
113
+ },
114
+ group: "general",
115
+ label: "Reply destination",
116
+ hint: "Where command replies go. The default is the chat the command was typed in. Another chat is used only after the backend checks it. A refused destination never falls back to a group.",
117
+ },
118
+ {
119
+ key: "reply_route_chat",
120
+ type: "string",
121
+ default: "",
122
+ group: "general",
123
+ label: "Authorized reply chat",
124
+ hint: "A WhatsApp chat id (phone, LID, or group). Not a link. Used only when the reply destination is an authorized chat.",
125
+ },
126
+ {
127
+ key: "reply_route_overrides",
128
+ type: "string",
129
+ default: "",
130
+ group: "general",
131
+ label: "Reply route overrides",
132
+ hint: 'Optional JSON, for example {"commands":{"ping":"same_chat"},"categories":{"progress":"same_chat"}}. Invalid JSON is refused.',
133
+ },
134
+ {
135
+ key: "reply_hide_progress",
136
+ type: "bool",
137
+ default: false,
138
+ group: "general",
139
+ label: "Hide progress messages",
140
+ hint: "Hides progress lines. Results, errors and security notices still appear.",
141
+ },
142
+ {
143
+ key: "message_watermark",
144
+ type: "bool",
145
+ default: false,
146
+ group: "general",
147
+ label: "Powered by Levix watermark",
148
+ hint: "Adds a short watermark to eligible text results. Security notices, errors, files and exact-output commands stay clean.",
149
+ },
150
+ {
151
+ key: "plus_enabled",
152
+ type: "bool",
153
+ default: true,
154
+ group: "general",
155
+ label: "Levix Plus",
156
+ hint: "Turns the Levix Plus extension off without uninstalling it. Free features are not affected.",
157
+ },
72
158
 
73
159
  // --- AI ----------------------------------------------------------------
74
160
  //
@@ -149,6 +235,33 @@ const SETTINGS = [
149
235
  group: "ai",
150
236
  label: "Conversation turns kept",
151
237
  },
238
+ {
239
+ key: "ai_global_memory_read",
240
+ type: "string",
241
+ default: "privileged",
242
+ choices: ["off", "owner", "privileged", "everyone"],
243
+ group: "ai",
244
+ label: "Global memory read access",
245
+ hint: "Who may use global memory in explicit AI turns. Privileged means bot owners and bot admins. Auto Reply uses its per-chat settings.",
246
+ },
247
+ {
248
+ key: "ai_global_memory_write",
249
+ type: "string",
250
+ default: "off",
251
+ choices: ["off", "owner", "privileged"],
252
+ group: "ai",
253
+ label: "Global memory write access",
254
+ hint: "Who may let the AI save, delete or summarize into global memory. Privileged means bot owners and bot admins. Explicit !memory commands keep their own permissions.",
255
+ },
256
+ {
257
+ key: "ai_global_memory_where",
258
+ type: "string",
259
+ default: "own_chat",
260
+ choices: ["own_chat", "private", "all"],
261
+ group: "ai",
262
+ label: "Global memory allowed chats",
263
+ hint: "Own chat allows a caller's own private chat, including the linked account's self chat. Private allows any private chat; all also allows groups. Applies to explicit AI turns.",
264
+ },
152
265
  {
153
266
  key: "memory_context_chars",
154
267
  type: "int",
@@ -322,14 +435,6 @@ const SETTINGS = [
322
435
  label: "OpenWeatherMap API key",
323
436
  hint: "Needed by !weather.",
324
437
  },
325
- {
326
- key: "youtube_api_key",
327
- type: "secret",
328
- default: "",
329
- group: "integrations",
330
- label: "YouTube Data API key",
331
- hint: "For YouTube video and search tools.",
332
- },
333
438
 
334
439
  // --- Media -------------------------------------------------------------
335
440
  {
@@ -435,6 +540,23 @@ const SETTINGS = [
435
540
  label: "Proxy password",
436
541
  hint: "Stored like an API key: never sent back to this page, never logged.",
437
542
  },
543
+ {
544
+ key: "connection_log_level",
545
+ type: "string",
546
+ default: "info",
547
+ choices: ["silent", "error", "warn", "info", "debug", "trace"],
548
+ choiceLabels: {
549
+ silent: "Off",
550
+ error: "Errors",
551
+ warn: "Warnings",
552
+ info: "Info",
553
+ debug: "Debug (detailed)",
554
+ trace: "Trace (every frame)",
555
+ },
556
+ group: "whatsapp",
557
+ label: "Connection debug logging",
558
+ hint: "How much Baileys and Node's network layer write to the sanitized debug log, which leaves the device only when you attach it to a crash report or feedback. Applies on the next session start. Trace records every protocol frame and fills the 5 MB daily cap fast.",
559
+ },
438
560
 
439
561
  // --- Server ------------------------------------------------------------
440
562
  {
@@ -509,6 +631,56 @@ const SECRET_SETTING_KEYS = SETTINGS.filter((definition) => definition.type ===
509
631
  (definition) => definition.key,
510
632
  );
511
633
 
634
+ const ROUTE_MODES = ["same_chat", "owner_private", "authorized_chat"];
635
+ const ROUTE_CATEGORIES = ["progress", "result", "error", "security", "system"];
636
+ const ROUTE_JID = /^[0-9]{1,30}@(s\.whatsapp\.net|lid|g\.us)$/;
637
+
638
+ function validateRouteChat(text) {
639
+ if (!text) return "";
640
+ if (!ROUTE_JID.test(text)) {
641
+ throw new Error("Authorized reply chat must be a WhatsApp chat id, not a link");
642
+ }
643
+ return text;
644
+ }
645
+
646
+ function validateRouteOverrides(text) {
647
+ if (!text) return "";
648
+ if (text.length > 2000) throw new Error("Reply route overrides are too long");
649
+ let parsed;
650
+ try {
651
+ parsed = JSON.parse(text);
652
+ } catch {
653
+ throw new Error("Reply route overrides must be JSON");
654
+ }
655
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
656
+ throw new Error("Reply route overrides must be a JSON object");
657
+ }
658
+ for (const key of Object.keys(parsed)) {
659
+ if (key !== "commands" && key !== "categories") {
660
+ throw new Error("Reply route overrides only accept commands and categories");
661
+ }
662
+ }
663
+ const commands = parsed.commands || {};
664
+ const categories = parsed.categories || {};
665
+ if (typeof commands !== "object" || Array.isArray(commands)) {
666
+ throw new Error("Reply route command overrides must be an object");
667
+ }
668
+ if (typeof categories !== "object" || Array.isArray(categories)) {
669
+ throw new Error("Reply route category overrides must be an object");
670
+ }
671
+ for (const [name, mode] of Object.entries(commands)) {
672
+ if (!/^[a-z0-9_-]{1,32}$/.test(name) || !ROUTE_MODES.includes(mode)) {
673
+ throw new Error("A command route override is not allowed");
674
+ }
675
+ }
676
+ for (const [name, mode] of Object.entries(categories)) {
677
+ if (!ROUTE_CATEGORIES.includes(name) || !ROUTE_MODES.includes(mode)) {
678
+ throw new Error("A category route override is not allowed");
679
+ }
680
+ }
681
+ return JSON.stringify({ commands, categories });
682
+ }
683
+
512
684
  const GROUP_LABELS = {
513
685
  general: "General",
514
686
  ai: "AI",
@@ -595,6 +767,8 @@ function validate(definition, value) {
595
767
  throw new Error(`${definition.label} must be one of: ${definition.choices.join(", ")}`);
596
768
  }
597
769
 
770
+ if (definition.key === "reply_route_chat") return validateRouteChat(text);
771
+ if (definition.key === "reply_route_overrides") return validateRouteOverrides(text);
598
772
  if (text.length > 500) throw new Error(`${definition.label} is too long`);
599
773
  if (definition.key === "bot_timezone" && text) {
600
774
  try {
@@ -662,7 +836,22 @@ function describe() {
662
836
  });
663
837
  }
664
838
 
839
+ // Error surfaces need secret redaction without diagnostics' identity/path filtering.
840
+ // Read current values here so key rotation takes effect on the next error.
841
+ // Values below four characters are skipped to avoid corrupting ordinary text.
842
+ function redactSecrets(text) {
843
+ let out = String(text ?? "");
844
+ const secrets = SECRET_SETTING_KEYS.map((key) => get(key))
845
+ .filter((value) => typeof value === "string" && value.length >= 4)
846
+ .sort((a, b) => b.length - a.length);
847
+ for (const secret of secrets) out = out.split(secret).join("[redacted]");
848
+ return out
849
+ .replace(/\bBearer\s+[^\s"'<>`,;]+/gi, "Bearer [redacted]")
850
+ .replace(/(\bkey=)[^\s&#"'<>`]+/gi, "$1[redacted]");
851
+ }
852
+
665
853
  module.exports = {
854
+ redactSecrets,
666
855
  get,
667
856
  set,
668
857
  describe,