levix-bot 4.2.1 → 4.3.1

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 (55) hide show
  1. package/app.cjs +50 -4
  2. package/package.json +1 -1
  3. package/public/dashboard/assets/index-B6RhYFIy.js +446 -0
  4. package/public/dashboard/assets/index-vEwOcxiH.css +2 -0
  5. package/public/dashboard/index.html +2 -2
  6. package/public/dashboard.css +71 -1
  7. package/public/gateway.js +41 -0
  8. package/src/bootstrap/core.js +4 -0
  9. package/src/bootstrap/panel.js +2 -0
  10. package/src/commands/autoschedule.cjs +11 -14
  11. package/src/commands/blacklist.cjs +1 -1
  12. package/src/commands/block.cjs +1 -1
  13. package/src/commands/calc.cjs +9 -9
  14. package/src/commands/gemini.cjs +26 -26
  15. package/src/commands/group/add.cjs +2 -2
  16. package/src/commands/group/demote.cjs +2 -2
  17. package/src/commands/group/members.cjs +2 -2
  18. package/src/commands/group/rules.cjs +1 -1
  19. package/src/commands/group/setname.cjs +3 -3
  20. package/src/commands/group/setpp.cjs +3 -3
  21. package/src/commands/group/setrules.cjs +1 -1
  22. package/src/commands/group/tagadmins.cjs +1 -1
  23. package/src/commands/group.cjs +1 -1
  24. package/src/commands/lang.cjs +3 -3
  25. package/src/commands/listschedules.cjs +1 -1
  26. package/src/commands/loop.cjs +3 -3
  27. package/src/commands/memory.cjs +18 -18
  28. package/src/commands/notes.cjs +1 -1
  29. package/src/commands/perm.cjs +2 -2
  30. package/src/commands/poll.cjs +3 -3
  31. package/src/commands/rand.cjs +2 -2
  32. package/src/commands/restart.cjs +46 -17
  33. package/src/commands/schedule.cjs +9 -11
  34. package/src/commands/send.cjs +116 -0
  35. package/src/commands/status.cjs +2 -2
  36. package/src/commands/stopbot.cjs +68 -0
  37. package/src/commands/stt.cjs +1 -1
  38. package/src/commands/tts.cjs +2 -2
  39. package/src/commands/unblock.cjs +1 -1
  40. package/src/config/defaults.cjs +2 -1
  41. package/src/config/settings.cjs +4 -2
  42. package/src/core/session-holder.cjs +23 -0
  43. package/src/handlers/command.handler.js +4 -6
  44. package/src/panel/password-reset.cjs +187 -0
  45. package/src/routes/dashboard.api.esm.js +48 -78
  46. package/src/services/aiAgent.cjs +2 -2
  47. package/src/services/aiProviders.cjs +1 -1
  48. package/src/services/aiTools.cjs +27 -27
  49. package/src/services/settingsTransfer.cjs +246 -0
  50. package/src/utils/memory.cjs +7 -7
  51. package/views/login.ejs +209 -9
  52. package/views/setup.ejs +19 -5
  53. package/public/dashboard/assets/index-4AuqfnH5.js +0 -431
  54. package/public/dashboard/assets/index-LvfJ8ybs.css +0 -2
  55. package/src/commands/shutdown.cjs +0 -55
@@ -1,13 +1,20 @@
1
- // file: /commands/restart.js
2
- const { delay } = require("@whiskeysockets/baileys");
1
+ // Restarts the WhatsApp connection — not the process.
2
+ //
3
+ // It used to SIGTERM the whole bot and lean on the supervisor to bring it
4
+ // back, which took the control panel down with the socket. What people mean
5
+ // by restart here is the connection: session.reconnect() is the same
6
+ // stop()+start() the panel's Connection screen uses, so the state machine
7
+ // stays the only socket owner and a restart never kicks whoever is watching
8
+ // the panel out.
9
+ const { getSession } = require("../core/session-holder.cjs");
3
10
  const logger = require("../utils/logger.cjs");
4
11
  const { tr } = require("../utils/i18n.cjs");
5
12
 
6
13
  module.exports = {
7
14
  name: "restart",
8
15
  description: {
9
- en: "Restarts the bot.",
10
- ar: "يعيد تشغيل البوت.",
16
+ en: "Reconnects WhatsApp (the process and panel stay up).",
17
+ ar: "يعيد تشغيل اتصال واتساب (مع استمرار تشغيل البوت ولوحة التحكم).",
11
18
  },
12
19
  usage: {
13
20
  en: "restart",
@@ -16,24 +23,46 @@ module.exports = {
16
23
  chat: "all",
17
24
 
18
25
  async execute(sock, msg) {
19
- logger.warn("Received !restart command. Restarting bot...");
26
+ const chatId = msg.key.remoteJid;
27
+ const session = getSession();
28
+ if (!session) {
29
+ return await sock.sendMessage(chatId, {
30
+ text: tr("The session manager isn't ready yet.", "مدير الجلسة غير جاهز بعد."),
31
+ });
32
+ }
20
33
 
21
- // Send a confirmation message before exiting
22
- await sock.sendMessage(msg.key.remoteJid, {
34
+ // Goes out while the current socket is still alive.
35
+ await sock.sendMessage(chatId, {
23
36
  text: tr(
24
- "✅ Restarting the bot... back in a moment.",
25
- "✅ جاري إعادة تشغيل البوت... سأعود بعد لحظات.",
37
+ "🔄 Reconnecting WhatsApp... back in a moment.",
38
+ "🔄 جارٍ إعادة تشغيل اتصال واتساب... سأعود خلال لحظات.",
26
39
  ),
27
40
  });
28
41
 
29
- // A small delay to ensure the message is sent before the process exits
30
- await delay(2000); // 2-second delay
42
+ let state = null;
43
+ try {
44
+ state = await session.reconnect({ reason: "command" });
45
+ logger.info("[commands] WhatsApp connection restarted by !restart");
46
+ } catch (error) {
47
+ logger.error({ err: error, command: "restart" }, "Failed to reconnect WhatsApp");
48
+ }
31
49
 
32
- // SIGTERM to ourselves, not process.exit(): that is the path in
33
- // src/index.js that cancels the reconnect timers, closes the WhatsApp
34
- // socket, flushes the store and closes the database. Exiting straight from
35
- // here skipped all four and left the WAL unchecked-pointed. The supervisor
36
- // (pm2 / systemd / docker) brings the process back.
37
- process.kill(process.pid, "SIGTERM");
50
+ if (state?.connected) {
51
+ await sock.sendMessage(chatId, {
52
+ text: tr("✅ WhatsApp is back online.", "✅ اتصال واتساب رجع يشتغل."),
53
+ });
54
+ } else {
55
+ // Not connected (a QR wait, a retry, a failure) — say where things
56
+ // stand instead of claiming success. The old socket is gone either way,
57
+ // so this send is best-effort.
58
+ await sock
59
+ .sendMessage(chatId, {
60
+ text: tr(
61
+ `Connection state now: ${state?.status || "unknown"}. Check the panel's Connection screen.`,
62
+ `حالة الاتصال الحالية: ${state?.status || "غير معروفة"}. راجع صفحة الاتصال في لوحة التحكم.`,
63
+ ),
64
+ })
65
+ .catch(() => {});
66
+ }
38
67
  },
39
68
  };
@@ -1,6 +1,7 @@
1
1
  // file: commands/schedule.js
2
2
  const { scheduleNewJob, saveScheduledJob } = require("../../scheduler.cjs");
3
- const { zonedTimeToDate, defaultTimezone } = require("../utils/datetime.cjs");
3
+ const { zonedTimeToDate } = require("../utils/datetime.cjs");
4
+ const logger = require("../utils/logger.cjs");
4
5
  const { tr } = require("../utils/i18n.cjs");
5
6
 
6
7
  const DATETIME_RE = /^(\d{1,2}):(\d{2})\s+(\d{1,2})-(\d{1,2})-(\d{4})$/;
@@ -85,21 +86,18 @@ module.exports = {
85
86
  return await sock.sendMessage(creatorJid, {
86
87
  text: tr(
87
88
  "I couldn't schedule that message. Check the time and try again.",
88
- "معرفتش أجدول الرسالة دي. راجع الوقت وجرب تاني.",
89
+ "تعذّرت جدولة هذه الرسالة. راجع الوقت وحاول مرة أخرى.",
89
90
  ),
90
91
  });
91
92
  }
92
93
 
93
94
  saveScheduledJob(newJob);
94
95
 
95
- const when = scheduleDate.toLocaleString(tr("en-GB", "ar-EG"), {
96
- timeZone: defaultTimezone(),
97
- });
98
- await sock.sendMessage(creatorJid, {
99
- text: tr(
100
- `✅ Your message is scheduled for:\n*${when}*`,
101
- `✅ تم جدولة رسالتك بنجاح ليتم إرسالها في:\n*${when}*`,
102
- ),
103
- });
96
+ // تأكيد صامت: تفاعل على رسالة الإنشاء بدل رسالة "تم الجدولة" المنفصلة
97
+ try {
98
+ await sock.sendMessage(targetJid, { react: { text: "✅", key: msg.key } });
99
+ } catch (error) {
100
+ logger.warn({ err: error, command: "schedule" }, "failed to react to the scheduled message");
101
+ }
104
102
  },
105
103
  };
@@ -0,0 +1,116 @@
1
+ // Re-sends content into the current chat. Built for statuses (stories): reply
2
+ // to one with !send and the bot re-posts it here, so a photo that lives 24
3
+ // hours on the status ring stays in the chat. Works on any replied message —
4
+ // photo, video, voice note, sticker, document or plain text.
5
+ //
6
+ // No storage is involved: the reply's quotedMessage carries the full media
7
+ // metadata (url, mediaKey, directPath), which is enough to download and
8
+ // decrypt it again — nothing is cached and nothing is archived.
9
+ const { downloadContentFromMessage } = require("@whiskeysockets/baileys");
10
+ const { downloadMedia } = require("../utils/geminiMedia.cjs");
11
+ const { unwrapMessage, visibleText } = require("../utils/messageContent.cjs");
12
+ const { createStatus } = require("../utils/statusMessage.cjs");
13
+ const logger = require("../utils/logger.cjs");
14
+ const { tr } = require("../utils/i18n.cjs");
15
+
16
+ // The media in a message plus the download type that decrypts it — the type
17
+ // WhatsApp filed it under, not the MIME type (same rule as the AI command).
18
+ function pickMedia(message) {
19
+ const inner = unwrapMessage(message);
20
+ if (inner.stickerMessage) return { media: inner.stickerMessage, type: "sticker" };
21
+ if (inner.imageMessage) return { media: inner.imageMessage, type: "image" };
22
+ if (inner.videoMessage) return { media: inner.videoMessage, type: "video" };
23
+ if (inner.audioMessage) return { media: inner.audioMessage, type: "audio" };
24
+ if (inner.documentMessage) return { media: inner.documentMessage, type: "document" };
25
+ return null;
26
+ }
27
+
28
+ function quotedOf(msg) {
29
+ const own = unwrapMessage(msg.message);
30
+ return own.extendedTextMessage?.contextInfo?.quotedMessage || null;
31
+ }
32
+
33
+ module.exports = {
34
+ name: "send",
35
+ description: {
36
+ en: "Re-sends the replied message here: a status/story, photo, video, voice note, sticker, document or text.",
37
+ ar: "يعيد إرسال الرسالة الموجّه لها الرد هنا: استوري، صورة، فيديو، رسالة صوتية، ستيكر، مستند أو نص.",
38
+ },
39
+ usage: {
40
+ en: "send (reply to a status or any message with it)",
41
+ ar: "send (اعمل رد على استوري أو أي رسالة بالأمر)",
42
+ },
43
+ chat: "all",
44
+
45
+ async execute(sock, msg) {
46
+ const chatId = msg.key.remoteJid;
47
+ const quoted = quotedOf(msg);
48
+
49
+ // Media attached to the command itself counts too — "send this" with a
50
+ // caption works like a reply does.
51
+ const target = pickMedia(msg.message) || (quoted ? pickMedia(quoted) : null);
52
+
53
+ if (!target) {
54
+ const quotedText = quoted ? visibleText(quoted) : "";
55
+ if (quotedText) {
56
+ return await sock.sendMessage(chatId, { text: quotedText });
57
+ }
58
+ return await sock.sendMessage(chatId, {
59
+ text: tr(
60
+ "Reply to a status or any message with `!send` and I'll re-send it here.",
61
+ "اعمل رد على استوري أو أي رسالة بالأمر `!send` وأنا هعيد إرسالها هنا.",
62
+ ),
63
+ });
64
+ }
65
+
66
+ const status = await createStatus(sock, chatId, tr("📥 Sending...", "📥 جارٍ الإرسال..."), {
67
+ replyTo: msg,
68
+ });
69
+
70
+ try {
71
+ const buffer = await downloadMedia(downloadContentFromMessage, target.media, target.type);
72
+ const media = target.media;
73
+ const { mimetype, caption } = media;
74
+
75
+ let content;
76
+ if (target.type === "image") {
77
+ content = {
78
+ image: buffer,
79
+ ...(caption ? { caption } : {}),
80
+ ...(mimetype ? { mimetype } : {}),
81
+ };
82
+ } else if (target.type === "video") {
83
+ content = {
84
+ video: buffer,
85
+ ...(caption ? { caption } : {}),
86
+ ...(mimetype ? { mimetype } : {}),
87
+ ...(media.gifPlayback ? { gifPlayback: true } : {}),
88
+ };
89
+ } else if (target.type === "audio") {
90
+ content = { audio: buffer, ...(mimetype ? { mimetype } : {}), ptt: !!media.ptt };
91
+ } else if (target.type === "sticker") {
92
+ content = { sticker: buffer, ...(mimetype ? { mimetype } : {}) };
93
+ } else {
94
+ content = {
95
+ document: buffer,
96
+ ...(mimetype ? { mimetype } : {}),
97
+ ...(media.fileName ? { fileName: media.fileName } : {}),
98
+ ...(caption ? { caption } : {}),
99
+ };
100
+ }
101
+
102
+ await sock.sendMessage(chatId, content);
103
+ // The media is the answer — the status line goes away.
104
+ await status.remove();
105
+ } catch (error) {
106
+ logger.error({ err: error, command: "send" }, "Failed to re-send replied media");
107
+ await status.fail(
108
+ error,
109
+ tr(
110
+ "Couldn't re-send it — the media may have expired",
111
+ "تعذّر إرساله — ربما انتهت صلاحية ملف الوسائط",
112
+ ),
113
+ );
114
+ }
115
+ },
116
+ };
@@ -57,8 +57,8 @@ module.exports = {
57
57
  // binary is otherwise invisible.
58
58
  const ffmpeg = await checkFfmpeg();
59
59
  const ffmpegLine = ffmpeg.ok
60
- ? `✅ ${ffmpeg.version || tr("working", "شغال")}`
61
- : tr(`❌ not working (${ffmpeg.path})`, `❌ مش شغال (${ffmpeg.path})`);
60
+ ? `✅ ${ffmpeg.version || tr("working", "يعمل")}`
61
+ : tr(`❌ not working (${ffmpeg.path})`, `❌ لا يعمل (${ffmpeg.path})`);
62
62
 
63
63
  // --- BUILDING THE REPLY ---
64
64
  const reply = tr(
@@ -0,0 +1,68 @@
1
+ // Pauses the WhatsApp connection without touching the process.
2
+ //
3
+ // It replaced `!shutdown`, which shelled out to `pm2 stop` — a command from an
4
+ // install shape Levix outgrew, and one that took the control panel down with
5
+ // the bot. This is the panel's own "Stop" from inside a chat: the same state
6
+ // machine call, pairing kept, panel up, no retry afterwards. Resuming is the
7
+ // Connection screen — once the socket is down no message can arrive, so there
8
+ // is no way to type a start command.
9
+ const { getSession } = require("../core/session-holder.cjs");
10
+ const logger = require("../utils/logger.cjs");
11
+ const { tr } = require("../utils/i18n.cjs");
12
+
13
+ module.exports = {
14
+ name: "stopbot",
15
+ aliases: ["stop", "pause"],
16
+ description: {
17
+ en: "Pauses the WhatsApp connection (the bot process and panel keep running).",
18
+ ar: "يوقف اتصال واتساب مؤقتًا (مع استمرار تشغيل البوت ولوحة التحكم).",
19
+ },
20
+ usage: {
21
+ en: "stopbot",
22
+ ar: "stopbot",
23
+ },
24
+ chat: "all",
25
+
26
+ async execute(sock, msg) {
27
+ const chatId = msg.key.remoteJid;
28
+ const session = getSession();
29
+ if (!session) {
30
+ return await sock.sendMessage(chatId, {
31
+ text: tr("The session manager isn't ready yet.", "مدير الجلسة غير جاهز بعد."),
32
+ });
33
+ }
34
+
35
+ const state = session.getState();
36
+ if (!state.connected && !state.canStop) {
37
+ return await sock.sendMessage(chatId, {
38
+ text: tr(
39
+ "The WhatsApp connection isn't up — nothing to pause.",
40
+ "اتصال واتساب متوقف بالفعل.",
41
+ ),
42
+ });
43
+ }
44
+
45
+ // The goodbye goes out before the socket comes down: once stop() runs,
46
+ // nothing can be sent through this chat until the session starts again.
47
+ await sock.sendMessage(chatId, {
48
+ text: tr(
49
+ "⏸️ Pausing the WhatsApp connection. The bot and the control panel stay up — resume from the Connection screen in the panel.",
50
+ "⏸️ جارٍ إيقاف اتصال واتساب مؤقتًا. سيستمر تشغيل البوت ولوحة التحكم. يمكنك استئناف الاتصال من صفحة الاتصال في لوحة التحكم.",
51
+ ),
52
+ });
53
+
54
+ try {
55
+ await session.stop({ reason: "command" });
56
+ logger.warn("[commands] WhatsApp connection paused by !stopbot");
57
+ } catch (error) {
58
+ logger.error({ err: error, command: "stopbot" }, "Failed to pause the WhatsApp connection");
59
+ // The socket may still be up, so the operator can actually read this.
60
+ await sock.sendMessage(chatId, {
61
+ text: tr(
62
+ "Couldn't pause the connection. Try the panel's Connection screen.",
63
+ "تعذّر إيقاف الاتصال. حاول من صفحة الاتصال في لوحة التحكم.",
64
+ ),
65
+ });
66
+ }
67
+ },
68
+ };
@@ -248,7 +248,7 @@ module.exports = {
248
248
  const status = await createStatus(
249
249
  sock,
250
250
  chatId,
251
- tr("🎧 Transcribing...", "🎧 جاري تحويل الصوت إلى نص..."),
251
+ tr("🎧 Transcribing...", "🎧 جارٍ تحويل الصوت إلى نص..."),
252
252
  {
253
253
  replyTo: msg,
254
254
  },
@@ -140,7 +140,7 @@ module.exports = {
140
140
  },
141
141
  usage: {
142
142
  en: "tts <text> (or reply to a text message)",
143
- ar: "tts <النص> (أو رد على رسالة نصية)",
143
+ ar: "tts <النص> (أو ردّ على رسالة نصية)",
144
144
  },
145
145
  chat: "all",
146
146
 
@@ -161,7 +161,7 @@ module.exports = {
161
161
  {
162
162
  text: tr(
163
163
  "📢 Usage:\n!tts <text>\n\nor reply to a text message with !tts\n\n✨ Completely free — no costs!",
164
- "📢 الاستخدام:\n!tts <النص>\n\nأو رد على رسالة نصية بالأمر !tts\n\n✨ مجاني تماماً - بدون تكاليف!",
164
+ "📢 الاستخدام:\n!tts <النص>\n\nأو ردّ على رسالة نصية بالأمر !tts\n\n✨ الخدمة مجانية!",
165
165
  ),
166
166
  },
167
167
  { replyTo: msg },
@@ -1,6 +1,6 @@
1
1
  // file: /commands/unblock.js (Upgraded with private chat context)
2
2
  const logger = require("../utils/logger.cjs");
3
- const normalizeJid = require("../utils/normalizeJid.esm.js");
3
+ const normalizeJid = require("../utils/normalizeJid.esm.js").default;
4
4
  const { tr } = require("../utils/i18n.cjs");
5
5
 
6
6
  module.exports = {
@@ -47,12 +47,13 @@ const COMMAND_PERMISSIONS = Object.freeze({
47
47
  perm: "OWNER_ONLY",
48
48
  setprefix: "OWNER_ONLY",
49
49
  restart: "OWNER_ONLY",
50
- shutdown: "OWNER_ONLY",
50
+ stopbot: "OWNER_ONLY",
51
51
  status: "OWNER_ONLY",
52
52
  lang: "MEMBERS",
53
53
  digit: "MEMBERS",
54
54
  block: "OWNER_ONLY",
55
55
  unblock: "OWNER_ONLY",
56
+ send: "MEMBERS",
56
57
  group: {
57
58
  default_permission: "ADMINS_OWNER",
58
59
  sub_commands: {
@@ -586,8 +586,7 @@ function set(key, value) {
586
586
  }
587
587
 
588
588
  const clean = validate(definition, value);
589
- const toStore =
590
- definition.type === "secret" ? require("./vault.cjs").seal(String(clean)) : clean;
589
+ const toStore = definition.type === "secret" ? require("./vault.cjs").seal(String(clean)) : clean;
591
590
  storage.saveBotSetting(`setting:${key}`, toStore);
592
591
  // Never log the value of a secret.
593
592
  logger.info(`[settings] ${key} -> ${definition.type === "secret" ? "(updated)" : clean}`);
@@ -629,4 +628,7 @@ module.exports = {
629
628
  sourceOf,
630
629
  SETTING_KEYS: [...BY_KEY.keys()],
631
630
  SECRET_SETTING_KEYS: [...SECRET_SETTING_KEYS],
631
+ RESTART_SETTING_KEYS: SETTINGS.filter((definition) => definition.restart === true).map(
632
+ (definition) => definition.key,
633
+ ),
632
634
  };
@@ -0,0 +1,23 @@
1
+ // A process-wide pointer to the backend's session manager.
2
+ //
3
+ // The state machine in session.js is the only thing allowed to create or
4
+ // destroy a Baileys socket, but it is built once in bootstrap/core.js and not
5
+ // every caller sits on that dependency path — the WhatsApp commands (!stopbot,
6
+ // !restart) don't (the panel gets its own hand-over in bootstrap/panel.js).
7
+ // bootstrapCore() sets this right after constructing the manager; commands
8
+ // read it at call time.
9
+ //
10
+ // Null until the core is up — callers answer that with a friendly line,
11
+ // never a crash.
12
+
13
+ let session = null;
14
+
15
+ function setSession(manager) {
16
+ session = manager;
17
+ }
18
+
19
+ function getSession() {
20
+ return session;
21
+ }
22
+
23
+ module.exports = { setSession, getSession };
@@ -3,8 +3,8 @@ import { createRequire } from "module";
3
3
  import { dirname, join } from "path";
4
4
  import { fileURLToPath } from "url";
5
5
  import { checkBotAdmin, checkCommandPermission } from "../middleware/permissions.middleware.js";
6
- import { sendBotMessage } from "../utils/sendBotMessage.esm.js";
7
6
  import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
7
+ import { sendBotMessage } from "../utils/sendBotMessage.esm.js";
8
8
 
9
9
  const __filename = fileURLToPath(import.meta.url);
10
10
  const __dirname = dirname(__filename);
@@ -32,6 +32,7 @@ const EDIT_IN_PLACE_EXCLUDE = new Set([
32
32
  "prayer",
33
33
  "tts",
34
34
  "stt",
35
+ "send",
35
36
  "weather",
36
37
  "qr",
37
38
  "status",
@@ -298,7 +299,7 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
298
299
  await sendBotMessage(
299
300
  sock,
300
301
  msg.key.remoteJid,
301
- { text: tr("⛔ This command is turned off right now.", "⛔ الأمر ده متوقف حاليًا.") },
302
+ { text: tr("⛔ This command is turned off right now.", "⛔ هذا الأمر معطّل حاليًا.") },
302
303
  { replyTo: msg },
303
304
  );
304
305
  return true;
@@ -319,10 +320,7 @@ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup
319
320
  sock,
320
321
  msg.key.remoteJid,
321
322
  {
322
- text: tr(
323
- "⚠️ This command only works in groups.",
324
- "⚠️ هذا الأمر يعمل في المجموعات فقط.",
325
- ),
323
+ text: tr("⚠️ This command only works in groups.", "⚠️ هذا الأمر يعمل في المجموعات فقط."),
326
324
  },
327
325
  { replyTo: msg },
328
326
  );
@@ -0,0 +1,187 @@
1
+ // Password reset over WhatsApp.
2
+ //
3
+ // The panel password is a one-way hash (src/config/secrets.cjs) — there is
4
+ // nothing to "recover". This is the recovery path that matches the product:
5
+ // the bot itself messages the operator's WhatsApp with a one-time code. It
6
+ // works because the paired account IS the operator's account, so "send the
7
+ // code over WhatsApp" means "drop it in your own chat" — reachable whenever
8
+ // the session is up, with no email server and nothing to configure.
9
+ //
10
+ // Why a WhatsApp code rather than passkeys / biometrics (WebAuthn)? WebAuthn
11
+ // only exists in a secure context: HTTPS or localhost. A Levix panel is very
12
+ // often opened at plain http://<lan-ip>:3001, where no browser will offer a
13
+ // passkey at all. The code works on every shape of install, and
14
+ // `levix reset-password` on the server stays the offline fallback for when
15
+ // WhatsApp itself is down.
16
+ //
17
+ // The code lives only in this process's memory — hashed, 10 minutes, five
18
+ // verification attempts, single use. A restart clears it, which is fine:
19
+ // requesting a new one costs nothing. Requests are throttled per TCP peer
20
+ // (never `req.ip`, same discipline as login-throttle) and globally, because
21
+ // every accepted request costs the operator one WhatsApp message.
22
+
23
+ const crypto = require("node:crypto");
24
+
25
+ const logger = require("../utils/logger.cjs");
26
+ const secrets = require("../config/secrets.cjs");
27
+ const brand = require("../config/brand.cjs");
28
+ const { sendBotMessage } = require("../utils/sendBotMessage.cjs");
29
+ const { withLang, detectLang, tr } = require("../utils/i18n.cjs");
30
+ const normalizeJid = require("../utils/normalizeJid.esm.js").default;
31
+
32
+ const CODE_TTL_MS = 10 * 60 * 1000;
33
+ const MAX_CODE_ATTEMPTS = 5;
34
+ const REQUEST_WINDOW_MS = 15 * 60 * 1000;
35
+ const MAX_REQUESTS_PER_WINDOW = 3;
36
+ // Any peer may not trigger two sends closer than this — the code goes to the
37
+ // operator's own WhatsApp, and nobody should be able to machine-gun it.
38
+ const GLOBAL_COOLDOWN_MS = 60 * 1000;
39
+
40
+ // The backend's WhatsApp session manager, handed over by bootstrapPanel()
41
+ // next to the dashboard API's setSession(). Re-read the socket every time —
42
+ // a reconnect replaces it.
43
+ let session = null;
44
+ let pending = null; // { salt, hash, expiresAt, attempts }
45
+ let lastRequestAt = 0;
46
+ const requests = new Map(); // peer -> { count, firstAt }
47
+
48
+ function setSession(manager) {
49
+ session = manager;
50
+ }
51
+
52
+ /** Tests: drop the in-memory code and throttle state. */
53
+ function _resetForTests() {
54
+ pending = null;
55
+ lastRequestAt = 0;
56
+ requests.clear();
57
+ }
58
+
59
+ function hashCode(code, salt) {
60
+ return crypto.createHash("sha256").update(`${salt}:${code}`).digest("hex");
61
+ }
62
+
63
+ function codeMessage(code) {
64
+ return withLang(detectLang(""), () =>
65
+ tr(
66
+ `🔐 *${brand.name} — password reset code: ${code}*\n\n` +
67
+ `Enter it in the control panel within 10 minutes. ` +
68
+ `If you didn't request this, ignore this message — nobody else can use it.`,
69
+ `🔐 *${brand.name} — كود إعادة تعيين كلمة السر: ${code}*\n\n` +
70
+ `ادخل الكود في لوحة التحكم خلال ١٠ دقائق. ` +
71
+ `إذا لم تطلب هذا الرمز، فتجاهل الرسالة — لا يمكن لأحد سواك استخدامه.`,
72
+ ),
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Generate a reset code and WhatsApp it to the linked account's own chat.
78
+ *
79
+ * @returns {Promise<object>} { ok: true } or { ok: false, reason, ... }
80
+ */
81
+ async function requestResetCode(peer) {
82
+ const now = Date.now();
83
+
84
+ for (const [key, entry] of requests) {
85
+ if (now - entry.firstAt > REQUEST_WINDOW_MS) requests.delete(key);
86
+ }
87
+ const entry = requests.get(peer);
88
+ if (entry && entry.count >= MAX_REQUESTS_PER_WINDOW) {
89
+ return {
90
+ ok: false,
91
+ reason: "throttled",
92
+ retryAfter: Math.ceil((REQUEST_WINDOW_MS - (now - entry.firstAt)) / 1000),
93
+ };
94
+ }
95
+ const sinceLast = now - lastRequestAt;
96
+ if (lastRequestAt && sinceLast < GLOBAL_COOLDOWN_MS) {
97
+ return {
98
+ ok: false,
99
+ reason: "throttled",
100
+ retryAfter: Math.ceil((GLOBAL_COOLDOWN_MS - sinceLast) / 1000),
101
+ };
102
+ }
103
+
104
+ const sock = session?.socket ?? null;
105
+ if (!sock?.user?.id) {
106
+ return { ok: false, reason: "no_session" };
107
+ }
108
+
109
+ const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");
110
+ const salt = crypto.randomBytes(16).toString("hex");
111
+ pending = { salt, hash: hashCode(code, salt), expiresAt: now + CODE_TTL_MS, attempts: 0 };
112
+
113
+ try {
114
+ await sendBotMessage(
115
+ sock,
116
+ normalizeJid(sock.user.id),
117
+ { text: codeMessage(code) },
118
+ {
119
+ typing: false,
120
+ delayMs: 0,
121
+ },
122
+ );
123
+ } catch (error) {
124
+ pending = null;
125
+ logger.error({ err: error }, "[reset] failed to send the reset code over WhatsApp");
126
+ return { ok: false, reason: "send_failed" };
127
+ }
128
+
129
+ lastRequestAt = now;
130
+ if (entry) entry.count += 1;
131
+ else requests.set(peer, { count: 1, firstAt: now });
132
+
133
+ logger.info({ ip: peer }, "[reset] Reset code sent over WhatsApp");
134
+ return { ok: true, expiresInMinutes: Math.round(CODE_TTL_MS / 60000) };
135
+ }
136
+
137
+ /**
138
+ * Verify the code and, when it matches, set the new password. A wrong code
139
+ * burns one of the five attempts; a mismatched confirmation or a too-short
140
+ * password does not.
141
+ *
142
+ * @returns {object} { ok: true } or { ok: false, reason, ... }
143
+ */
144
+ function completeReset(code, password, confirm) {
145
+ if (!pending) return { ok: false, reason: "no_pending" };
146
+ if (Date.now() > pending.expiresAt) {
147
+ pending = null;
148
+ return { ok: false, reason: "expired" };
149
+ }
150
+ if (String(password ?? "") !== String(confirm ?? "")) {
151
+ return { ok: false, reason: "mismatch" };
152
+ }
153
+
154
+ pending.attempts += 1;
155
+ const expected = Buffer.from(pending.hash, "hex");
156
+ const actual = Buffer.from(hashCode(String(code ?? "").trim(), pending.salt), "hex");
157
+ if (expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {
158
+ const attemptsLeft = MAX_CODE_ATTEMPTS - pending.attempts;
159
+ if (attemptsLeft <= 0) {
160
+ pending = null;
161
+ return { ok: false, reason: "too_many_attempts" };
162
+ }
163
+ return { ok: false, reason: "wrong_code", attemptsLeft };
164
+ }
165
+
166
+ try {
167
+ // Bumps the password epoch, so every panel session stamped before this
168
+ // moment — including any an attacker might hold — stops being valid.
169
+ secrets.setDashboardPassword(password);
170
+ } catch (error) {
171
+ // The code is still good; the operator may fix the password and retry.
172
+ return { ok: false, reason: "invalid_password", message: error.message };
173
+ }
174
+
175
+ pending = null;
176
+ logger.info("[reset] Panel password reset via WhatsApp code");
177
+ return { ok: true };
178
+ }
179
+
180
+ module.exports = {
181
+ CODE_TTL_MS,
182
+ MAX_CODE_ATTEMPTS,
183
+ setSession,
184
+ requestResetCode,
185
+ completeReset,
186
+ _resetForTests,
187
+ };