levix-bot 4.7.0 → 4.9.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 (62) hide show
  1. package/README.md +21 -7
  2. package/SETUP.md +21 -2
  3. package/app.cjs +69 -23
  4. package/package.json +3 -2
  5. package/public/dashboard/assets/index-B1sOW2VX.js +561 -0
  6. package/public/dashboard/assets/index-CK8osB4o.css +2 -0
  7. package/public/dashboard/index.html +2 -2
  8. package/public/dashboard.css +50 -0
  9. package/public/dashboard.js +25 -2
  10. package/public/gateway-i18n.js +26 -0
  11. package/src/bootstrap/session-startup-policy.js +6 -6
  12. package/src/commands/group/antilink.cjs +82 -59
  13. package/src/commands/group/antispam.cjs +112 -0
  14. package/src/commands/group/clearwarns.cjs +6 -6
  15. package/src/commands/group/demote.cjs +11 -13
  16. package/src/commands/group/flagged.cjs +52 -0
  17. package/src/commands/group/kick.cjs +25 -15
  18. package/src/commands/group/media.cjs +65 -29
  19. package/src/commands/group/policy.cjs +215 -0
  20. package/src/commands/group/promote.cjs +11 -12
  21. package/src/commands/group/rules.cjs +9 -6
  22. package/src/commands/group/setwarn.cjs +17 -27
  23. package/src/commands/group/warn.cjs +13 -63
  24. package/src/commands/group.cjs +5 -2
  25. package/src/commands/md.cjs +44 -0
  26. package/src/commands/mod.cjs +101 -26
  27. package/src/commands/translate.cjs +585 -0
  28. package/src/config/ai-identity.cjs +53 -1
  29. package/src/config/ai-persona.md +32 -73
  30. package/src/config/defaults.cjs +3 -0
  31. package/src/config/secrets.cjs +71 -3
  32. package/src/config/settings.cjs +22 -1
  33. package/src/core/socket.js +27 -5
  34. package/src/db/db.cjs +66 -0
  35. package/src/db/store.cjs +264 -16
  36. package/src/diagnostics/crashReports.cjs +35 -9
  37. package/src/diagnostics/debugLog.cjs +405 -0
  38. package/src/handlers/command.handler.js +3 -1
  39. package/src/handlers/group.handler.js +32 -1
  40. package/src/handlers/message.handler.js +53 -17
  41. package/src/middleware/antispam.middleware.js +95 -48
  42. package/src/panel/feedback.cjs +32 -5
  43. package/src/panel/one-time-code.cjs +156 -0
  44. package/src/panel/password-reset.cjs +187 -91
  45. package/src/panel/recovery-email.cjs +333 -0
  46. package/src/routes/dashboard.api.esm.js +341 -29
  47. package/src/services/aiAgent.cjs +25 -3
  48. package/src/services/moderationPolicy.cjs +895 -0
  49. package/src/services/settingsTransfer.cjs +4 -2
  50. package/src/utils/linkedCreds.cjs +22 -0
  51. package/src/utils/logger.cjs +93 -34
  52. package/src/utils/markdownParser.cjs +208 -136
  53. package/src/utils/moderationAction.cjs +637 -0
  54. package/src/utils/moderationSummary.cjs +225 -0
  55. package/src/utils/permissions.cjs +70 -0
  56. package/src/utils/permissions.esm.js +48 -8
  57. package/src/utils/storage.cjs +8 -0
  58. package/src/utils/storage.esm.js +4 -0
  59. package/views/login.ejs +100 -28
  60. package/public/dashboard/assets/index-RnT7DAde.js +0 -540
  61. package/public/dashboard/assets/index-UcqCdCvG.css +0 -2
  62. package/src/commands/group/antiSpam.cjs +0 -97
@@ -16,14 +16,13 @@ import fs from "node:fs";
16
16
  import path from "node:path";
17
17
  import { Router } from "express";
18
18
  import { createRequire } from "module";
19
- import { groupMetadataCache } from "../core/socket.js";
19
+ import { fetchWhatsAppImage, groupMetadataCache } from "../core/socket.js";
20
20
  import { getCommandCatalog, rebuildCommandIndex } from "../handlers/command.handler.js";
21
21
  import { fileToBuffer, MultipartError, readMultipartForm } from "../utils/multipart.esm.js";
22
22
  import normalizeJid, { isLidJid } from "../utils/normalizeJid.esm.js";
23
23
  import { grantRole, listRoles, revokeRole } from "../utils/permissions.esm.js";
24
24
  import {
25
25
  countDebts,
26
- countGroups,
27
26
  countNotes,
28
27
  countSchedules,
29
28
  countTodos,
@@ -39,6 +38,7 @@ import {
39
38
  getGroupSettings,
40
39
  getRecentDebts,
41
40
  getSchedules,
41
+ listModerationFlags,
42
42
  rememberSavedName,
43
43
  resolveUserPhone,
44
44
  saveGroupSettings,
@@ -46,6 +46,24 @@ import {
46
46
 
47
47
  const require = createRequire(import.meta.url);
48
48
  const logger = require("../utils/logger.cjs");
49
+ const {
50
+ buildModerationSummaryBoth,
51
+ featureActionOf,
52
+ warnConfigOf,
53
+ normalizeWarnAction,
54
+ normalizeFeatureAction,
55
+ } = require("../utils/moderationSummary.cjs");
56
+ const {
57
+ describeModerationPolicy,
58
+ prepareGroupModeration,
59
+ commitPreparedModeration,
60
+ evaluateModerationDraft,
61
+ } = require("../services/moderationPolicy.cjs");
62
+ const {
63
+ kickGroupMember,
64
+ clearMemberModeration,
65
+ dismissMemberFlag,
66
+ } = require("../utils/moderationAction.cjs");
49
67
  const runtimeConfig = require("../config/runtime-config.cjs");
50
68
  const settings = require("../config/settings.cjs");
51
69
  const memory = require("../utils/memory.cjs");
@@ -57,16 +75,21 @@ const {
57
75
  TOPICS: FEEDBACK_TOPICS,
58
76
  MESSAGE_MAX: FEEDBACK_MESSAGE_MAX,
59
77
  MESSAGE_MIN: FEEDBACK_MESSAGE_MIN,
78
+ buildDiagnosticsAttachment,
60
79
  describeRuntime,
61
80
  feedbackRetryAfter,
62
81
  submitFeedback,
63
82
  validateFeedback,
64
83
  } = require("../panel/feedback.cjs");
65
84
  const { stampPanelSession } = require("../panel/session-auth.cjs");
85
+ const recoveryEmail = require("../panel/recovery-email.cjs");
66
86
  const { DATA_DIR } = require("../config/paths.cjs");
67
- const { buildDiagnostics } = require("../diagnostics/device.cjs");
68
87
  const crashReports = require("../diagnostics/crashReports.cjs");
69
- const { PERSONA_FILE, activeProviderKeySetting } = require("../services/aiAgent.cjs");
88
+ const {
89
+ PERSONA_FILE,
90
+ activeProviderKeySetting,
91
+ stripSealedSections,
92
+ } = require("../services/aiAgent.cjs");
70
93
  const {
71
94
  SCHEDULE_MEDIA_MAX_BYTES,
72
95
  deleteScheduledJob,
@@ -188,7 +211,7 @@ router.get("/stats", (req, res) => {
188
211
  success: true,
189
212
  stats: {
190
213
  connection,
191
- totalGroups: countGroups(),
214
+ totalGroups: knownGroupIds().size,
192
215
  totalWarnings: countWarnings(),
193
216
  totalTodos: countTodos(),
194
217
  totalNotes: countNotes(),
@@ -218,6 +241,23 @@ router.get("/stats", (req, res) => {
218
241
  }
219
242
  });
220
243
 
244
+ router.get("/logs", (_req, res) => {
245
+ try {
246
+ res.json({ success: true, logs: logger.readLogs() });
247
+ } catch (error) {
248
+ fail(res, error, "Error reading logs");
249
+ }
250
+ });
251
+
252
+ router.delete("/logs", (_req, res) => {
253
+ try {
254
+ logger.clearLogs();
255
+ res.json({ success: true });
256
+ } catch (error) {
257
+ fail(res, error, "Error clearing logs");
258
+ }
259
+ });
260
+
221
261
  router.get("/health", (req, res) => {
222
262
  const connection = sessionState();
223
263
  res.json({
@@ -411,7 +451,7 @@ router.get("/ai/persona", (req, res) => {
411
451
  const { header, body } = splitPersona(raw);
412
452
  res.json({
413
453
  success: true,
414
- persona: { header, body, file: path.basename(PERSONA_FILE) },
454
+ persona: { header, body: stripSealedSections(body), file: path.basename(PERSONA_FILE) },
415
455
  });
416
456
  } catch (error) {
417
457
  fail(res, error, "Error reading persona");
@@ -426,10 +466,11 @@ router.put("/ai/persona", (req, res) => {
426
466
  try {
427
467
  const raw = fs.existsSync(PERSONA_FILE) ? fs.readFileSync(PERSONA_FILE, "utf8") : "";
428
468
  const { header } = splitPersona(raw);
429
- const next = `${header}\n${PERSONA_SEPARATOR}\n${body.trim()}\n`;
469
+ const clean = stripSealedSections(body);
470
+ const next = `${header}\n${PERSONA_SEPARATOR}\n${clean}\n`;
430
471
  fs.writeFileSync(PERSONA_FILE, next, "utf8");
431
472
  logger.info("[Dashboard] AI persona updated");
432
- res.json({ success: true, persona: { header, body: body.trim() } });
473
+ res.json({ success: true, persona: { header, body: clean } });
433
474
  } catch (error) {
434
475
  fail(res, error, "Error writing persona");
435
476
  }
@@ -541,7 +582,7 @@ router.get("/ai/memory", (req, res) => {
541
582
  const stat = fs.statSync(path.join(memory.CHATS_DIR, file));
542
583
  scopes.push({
543
584
  scope: chatId,
544
- label: chatId,
585
+ label: chatIdentity(chatId).name || "",
545
586
  entries: memory.listMemory({ scope: "chat", chatId }).length,
546
587
  bytes: stat.size,
547
588
  updatedAt: stat.mtimeMs,
@@ -618,11 +659,22 @@ router.get("/ai/conversations/:chatId", (req, res) => {
618
659
  .catch((error) => fail(res, error, "Error reading conversation"));
619
660
  });
620
661
 
662
+ // Human-readable identity only; the JID remains the request key, never the label.
663
+ function chatIdentity(jid) {
664
+ const peer = describePeer(jid);
665
+ const name =
666
+ peer.kind === "group"
667
+ ? groupMetadataCache.get(jid)?.subject || getGroupDirectory(jid)?.subject || null
668
+ : peer.savedName || peer.pushName || peer.phone || null;
669
+ return { name, kind: peer.kind };
670
+ }
671
+
621
672
  async function getChatHistoryListAsync() {
622
673
  const { listChatHistoriesAsync } = require("../utils/storage-hub.cjs");
623
674
  const rows = await listChatHistoriesAsync();
624
675
  return (rows || []).map((row) => ({
625
676
  chatId: row.chatId,
677
+ ...chatIdentity(row.chatId),
626
678
  turns: row.turns ?? 0,
627
679
  updatedAt: row.updatedAt ?? null,
628
680
  }));
@@ -668,6 +720,7 @@ async function getChatConversationAsync(chatId) {
668
720
 
669
721
  return {
670
722
  chatId,
723
+ ...chatIdentity(chatId),
671
724
  updatedAt: meta.updatedAt ?? null,
672
725
  truncated: messages.length >= MAX_INSPECTOR_MESSAGES,
673
726
  messages,
@@ -678,10 +731,18 @@ async function getChatConversationAsync(chatId) {
678
731
  // Groups
679
732
  // ===========================================================================
680
733
 
734
+ function knownGroupIds() {
735
+ const ids = new Set(getAllGroupSettings().map((row) => row.group_id));
736
+ for (const jid of groupMetadataCache.keys()) ids.add(jid);
737
+ for (const row of getAllGroupDirectory()) ids.add(row.group_id);
738
+ return ids;
739
+ }
740
+
681
741
  function groupView(groupId, stored) {
682
742
  const live = groupMetadataCache.get(groupId) || null;
683
743
  const directory = getGroupDirectory(groupId) || null;
684
744
  const config = stored || {};
745
+ const described = describeModerationPolicy(config);
685
746
  const subject = live?.subject || directory?.subject || null;
686
747
  const memberCount = live?.participants?.length ?? directory?.participant_count ?? null;
687
748
  const mediaEnabled = !!config.media_control?.enabled;
@@ -698,25 +759,24 @@ function groupView(groupId, stored) {
698
759
  enabled: !!config.antilink?.enabled,
699
760
  mode: config.antilink?.mode || "ALL",
700
761
  allowed_domains: config.antilink?.allowed_domains || [],
762
+ action: featureActionOf(config, "antilink"),
701
763
  },
702
764
  antispam: {
703
765
  enabled: !!config.antispam?.enabled,
704
766
  time_window: config.antispam?.time_window ?? 10,
705
767
  message_count: config.antispam?.message_count ?? 5,
706
- action: config.antispam?.action || "WARN",
768
+ action: featureActionOf(config, "antispam"),
707
769
  },
708
770
  media_control: {
709
771
  enabled: !!config.media_control?.enabled,
710
772
  blocked_types: config.media_control?.blocked_types || [],
773
+ action: featureActionOf(config, "media"),
711
774
  },
712
775
  welcome_system: {
713
776
  enabled: !!config.welcome_system?.enabled,
714
777
  messages: config.welcome_system?.messages || [],
715
778
  },
716
- warn_system: {
717
- max_warnings: config.warn_system?.max_warnings ?? 3,
718
- action: config.warn_system?.action || "NONE",
719
- },
779
+ warn_system: warnConfigOf(config),
720
780
  join_requests: {
721
781
  auto_approve_enabled: !!config.join_requests?.auto_approve_enabled,
722
782
  },
@@ -725,20 +785,54 @@ function groupView(groupId, stored) {
725
785
  antilinkEnabled: !!config.antilink?.enabled,
726
786
  welcomeEnabled: !!config.welcome_system?.enabled,
727
787
  mediaRestriction,
788
+ forbidden_words: {
789
+ enabled: !!config.moderation?.forbiddenWords?.enabled,
790
+ count: Array.isArray(config.moderation?.forbiddenWords?.list)
791
+ ? config.moderation.forbiddenWords.list.length
792
+ : 0,
793
+ action: featureActionOf(config, "forbidden"),
794
+ },
795
+ moderation_summary: buildModerationSummaryBoth(config),
796
+ flagged_members: listModerationFlags(groupId).map((row) => {
797
+ const peer = describePeer(row.user_id);
798
+ return {
799
+ user_id: row.user_id,
800
+ name: peer.label || row.user_id,
801
+ phone: peer.phone,
802
+ warn_count: row.warn_count,
803
+ last_rule: row.last_rule,
804
+ flagged_at: row.flagged_at,
805
+ reasons: row.reasons,
806
+ };
807
+ }),
808
+ moderation_policy: described.effective,
809
+ moderation_policy_visibility: described.visibility,
728
810
  };
729
811
  }
730
812
 
813
+ router.post("/groups/moderation-preview", (req, res) => {
814
+ try {
815
+ const draft = evaluateModerationDraft(req.body || {});
816
+ const summary = buildModerationSummaryBoth(draft.settings);
817
+ res.json({
818
+ success: true,
819
+ en: summary.en,
820
+ ar: summary.ar,
821
+ visibility: draft.visibility,
822
+ errors: draft.errors || [],
823
+ });
824
+ } catch (error) {
825
+ fail(res, error, "Error building moderation preview");
826
+ }
827
+ });
828
+
731
829
  router.get("/groups", (req, res) => {
732
830
  try {
733
831
  const stored = new Map(getAllGroupSettings().map((row) => [row.group_id, row.settings || {}]));
734
832
 
735
833
  // Groups the bot is in but that have no settings row yet still belong in
736
834
  // the list — that's exactly where the operator goes to configure them.
737
- const ids = new Set(stored.keys());
738
- for (const jid of groupMetadataCache.keys()) ids.add(jid);
739
- for (const row of getAllGroupDirectory()) ids.add(row.group_id);
740
-
741
- const groups = [...ids]
835
+ const groups = [...knownGroupIds()]
742
836
  .map((id) => groupView(id, stored.get(id)))
743
837
  .sort((a, b) => (a.subject || a.id).localeCompare(b.subject || b.id));
744
838
 
@@ -748,6 +842,40 @@ router.get("/groups", (req, res) => {
748
842
  }
749
843
  });
750
844
 
845
+ // Keep expiring WhatsApp photo URLs inside the authenticated panel. Images are
846
+ // fetched only for visible cards, never as part of a stats poll or group sync.
847
+ router.get(
848
+ "/groups/:id/photo",
849
+ asyncRoute(async (req, res) => {
850
+ const id = req.params.id;
851
+ if (!id.endsWith("@g.us") || !knownGroupIds().has(id)) return res.sendStatus(404);
852
+ const sock = currentSocket();
853
+ if (!sock) return res.sendStatus(404);
854
+ let response;
855
+ try {
856
+ const url = await sock.profilePictureUrl(id, "image", 8000);
857
+ response = await fetchWhatsAppImage(sock, url, { signal: AbortSignal.timeout(8000) });
858
+ const mime = response.headers.get("content-type")?.split(";")[0];
859
+ if (!response.ok || !["image/jpeg", "image/png", "image/webp"].includes(mime)) {
860
+ return res.sendStatus(404);
861
+ }
862
+ const chunks = [];
863
+ let bytes = 0;
864
+ for await (const chunk of response.body) {
865
+ bytes += chunk.length;
866
+ if (bytes > 1024 * 1024) throw new Error("Group photo exceeds size limit");
867
+ chunks.push(chunk);
868
+ }
869
+ res.type(mime).send(Buffer.concat(chunks));
870
+ } catch {
871
+ // No photo, expired URL or private group: the card uses its local fallback.
872
+ res.sendStatus(404);
873
+ } finally {
874
+ if (response?.body && !response.body.locked) await response.body.cancel().catch(() => {});
875
+ }
876
+ }),
877
+ );
878
+
751
879
  const MEDIA_TYPES = ["image", "video", "sticker", "audio"];
752
880
  const ANTILINK_MODES = ["ALL", "WHITELIST", "BLACKLIST"];
753
881
 
@@ -770,6 +898,11 @@ router.patch("/groups/:id", (req, res) => {
770
898
  }
771
899
  }
772
900
  const current = getGroupSettings(groupId) || {};
901
+ const prepared = prepareGroupModeration(current, patch);
902
+ if (!prepared.ok) {
903
+ const message = prepared.errors[0]?.message || "Invalid moderation policy";
904
+ return res.status(400).json({ success: false, error: message, errors: prepared.errors });
905
+ }
773
906
 
774
907
  try {
775
908
  if (patch.antilink) {
@@ -780,6 +913,11 @@ router.patch("/groups/:id", (req, res) => {
780
913
  if (!ANTILINK_MODES.includes(mode)) throw new Error("Unknown antilink mode");
781
914
  next.mode = mode;
782
915
  }
916
+ if (patch.antilink.action !== undefined) {
917
+ const action = normalizeFeatureAction(patch.antilink.action);
918
+ if (!action) throw new Error("Unknown antilink action");
919
+ next.action = action;
920
+ }
783
921
  if (patch.antilink.allowed_domains !== undefined) {
784
922
  if (!Array.isArray(patch.antilink.allowed_domains)) {
785
923
  throw new Error("allowed_domains must be a list");
@@ -820,8 +958,8 @@ router.patch("/groups/:id", (req, res) => {
820
958
  enabled: !!next.enabled,
821
959
  time_window: next.time_window ?? 10,
822
960
  message_count: next.message_count ?? 5,
823
- action: next.action || "WARN",
824
961
  };
962
+ if (next.action === "WARN" || next.action === "KICK") current.antispam.action = next.action;
825
963
  }
826
964
 
827
965
  if (patch.media_control) {
@@ -839,10 +977,18 @@ router.patch("/groups/:id", (req, res) => {
839
977
  }
840
978
  next.blocked_types = [...new Set(types)];
841
979
  }
980
+ if (patch.media_control.action !== undefined) {
981
+ const action = normalizeFeatureAction(patch.media_control.action);
982
+ if (!action) throw new Error("Unknown media action");
983
+ next.action = action;
984
+ }
842
985
  current.media_control = {
843
986
  enabled: !!next.enabled,
844
987
  blocked_types: next.blocked_types || [],
845
988
  };
989
+ if (next.action === "DELETE" || next.action === "WARN" || next.action === "KICK") {
990
+ current.media_control.action = next.action;
991
+ }
846
992
  }
847
993
 
848
994
  if (patch.welcome_system) {
@@ -875,14 +1021,30 @@ router.patch("/groups/:id", (req, res) => {
875
1021
  next.max_warnings = Math.trunc(max);
876
1022
  }
877
1023
  if (patch.warn_system.action !== undefined) {
878
- const action = String(patch.warn_system.action).toUpperCase();
879
- if (!["KICK", "NONE"].includes(action)) throw new Error("Unknown warn action");
1024
+ const action = normalizeWarnAction(patch.warn_system.action);
1025
+ if (!action) throw new Error("Unknown warn action");
880
1026
  next.action = action;
881
1027
  }
882
- current.warn_system = {
1028
+ const stored = {
883
1029
  max_warnings: next.max_warnings ?? 3,
884
- action: next.action || "NONE",
885
1030
  };
1031
+ const existingAction = normalizeWarnAction(next.action);
1032
+ if (existingAction) stored.action = existingAction;
1033
+ current.warn_system = stored;
1034
+ }
1035
+
1036
+ if (patch.forbidden_words) {
1037
+ current.moderation ||= {};
1038
+ current.moderation.forbiddenWords ||= { enabled: false, list: [] };
1039
+ const words = current.moderation.forbiddenWords;
1040
+ if (patch.forbidden_words.enabled !== undefined) {
1041
+ words.enabled = !!patch.forbidden_words.enabled;
1042
+ }
1043
+ if (patch.forbidden_words.action !== undefined) {
1044
+ const action = normalizeFeatureAction(patch.forbidden_words.action);
1045
+ if (!action) throw new Error("Unknown forbidden-words action");
1046
+ words.action = action;
1047
+ }
886
1048
  }
887
1049
 
888
1050
  if (patch.join_requests) {
@@ -894,6 +1056,7 @@ router.patch("/groups/:id", (req, res) => {
894
1056
  if (patch.rules !== undefined) {
895
1057
  current.rules = String(patch.rules).slice(0, 4000);
896
1058
  }
1059
+ commitPreparedModeration(current, prepared);
897
1060
  } catch (error) {
898
1061
  return badRequest(res, error.message);
899
1062
  }
@@ -907,6 +1070,77 @@ router.patch("/groups/:id", (req, res) => {
907
1070
  }
908
1071
  });
909
1072
 
1073
+ function flaggedUserId(req) {
1074
+ return String(req.body?.user_id || "").trim();
1075
+ }
1076
+
1077
+ router.post(
1078
+ "/groups/:id/flagged/kick",
1079
+ asyncRoute(async (req, res) => {
1080
+ const groupId = req.params.id;
1081
+ if (!groupId?.endsWith("@g.us")) return badRequest(res, "Not a group id");
1082
+ const userId = flaggedUserId(req);
1083
+ if (!userId) return badRequest(res, "user_id is required");
1084
+ const sock = currentSocket();
1085
+ if (!sock) {
1086
+ return res.status(503).json({ success: false, error: "WhatsApp is disconnected" });
1087
+ }
1088
+ let meta = groupMetadataCache.get(groupId);
1089
+ if (!meta) {
1090
+ try {
1091
+ meta = await sock.groupMetadata(groupId);
1092
+ } catch (error) {
1093
+ return fail(res, error, "Could not load group roster", 503);
1094
+ }
1095
+ }
1096
+ try {
1097
+ const result = await kickGroupMember(sock, {
1098
+ groupId,
1099
+ groupMetadata: meta,
1100
+ targetCandidates: [userId],
1101
+ });
1102
+ if (!result.kicked) {
1103
+ const message =
1104
+ result.error === "protected"
1105
+ ? "That member can't be kicked"
1106
+ : result.error === "bot-not-admin"
1107
+ ? "The bot must be a group admin to kick"
1108
+ : "Could not kick that member";
1109
+ return badRequest(res, message);
1110
+ }
1111
+ res.json({ success: true, group: groupView(groupId, getGroupSettings(groupId)) });
1112
+ } catch (error) {
1113
+ fail(res, error, "Error kicking flagged member");
1114
+ }
1115
+ }),
1116
+ );
1117
+
1118
+ router.post("/groups/:id/flagged/clear", (req, res) => {
1119
+ const groupId = req.params.id;
1120
+ if (!groupId?.endsWith("@g.us")) return badRequest(res, "Not a group id");
1121
+ const userId = flaggedUserId(req);
1122
+ if (!userId) return badRequest(res, "user_id is required");
1123
+ try {
1124
+ clearMemberModeration(groupId, userId);
1125
+ res.json({ success: true, group: groupView(groupId, getGroupSettings(groupId)) });
1126
+ } catch (error) {
1127
+ fail(res, error, "Error clearing flagged member");
1128
+ }
1129
+ });
1130
+
1131
+ router.post("/groups/:id/flagged/dismiss", (req, res) => {
1132
+ const groupId = req.params.id;
1133
+ if (!groupId?.endsWith("@g.us")) return badRequest(res, "Not a group id");
1134
+ const userId = flaggedUserId(req);
1135
+ if (!userId) return badRequest(res, "user_id is required");
1136
+ try {
1137
+ dismissMemberFlag(groupId, userId);
1138
+ res.json({ success: true, group: groupView(groupId, getGroupSettings(groupId)) });
1139
+ } catch (error) {
1140
+ fail(res, error, "Error dismissing flag");
1141
+ }
1142
+ });
1143
+
910
1144
  // ===========================================================================
911
1145
  // Data tables
912
1146
  // ===========================================================================
@@ -1314,6 +1548,81 @@ router.post("/security/password", (req, res) => {
1314
1548
  });
1315
1549
  });
1316
1550
 
1551
+ // ===========================================================================
1552
+ // Recovery email — sealed account security, not a setting
1553
+ // ===========================================================================
1554
+ //
1555
+ // The address is never returned. `publicStatus()` is a mask plus `verified`.
1556
+ // A new address does not replace the saved one until its code is verified.
1557
+ // Same-origin and the panel session come from the /dashboard/api mount.
1558
+
1559
+ // Wrong codes and a wrong password are 400, not 401. The panel client treats
1560
+ // every 401 as a dead session and sends the operator to /login. Login-page
1561
+ // reset confirm stays 401; that page does not use this client. A wrong verify
1562
+ // code does not count toward the login lockout (the relay limits guesses); a
1563
+ // wrong password does.
1564
+ const RECOVERY_HTTP = {
1565
+ throttled: 429,
1566
+ rate_limited: 429,
1567
+ wrong_password: 400,
1568
+ invalid_email: 400,
1569
+ invalid: 400,
1570
+ unavailable: 502,
1571
+ wrong_code: 400,
1572
+ expired: 400,
1573
+ too_many_attempts: 400,
1574
+ no_pending: 400,
1575
+ };
1576
+
1577
+ function recoveryFailure(res, result) {
1578
+ const status = RECOVERY_HTTP[result.reason] ?? 400;
1579
+ if (result.retryAfter) res.set("Retry-After", String(result.retryAfter));
1580
+ const body = { success: false, error: result.reason || "unavailable" };
1581
+ if (result.retryAfter) body.retryAfter = result.retryAfter;
1582
+ if (result.attemptsLeft != null) body.attemptsLeft = result.attemptsLeft;
1583
+ return res.status(status).json(body);
1584
+ }
1585
+
1586
+ router.get("/recovery-email", (req, res) => {
1587
+ res.json({ success: true, ...recoveryEmail.publicStatus() });
1588
+ });
1589
+
1590
+ // A recovery address can reset the password, so binding one asks for the
1591
+ // password again, like changing it does. Otherwise a stolen session or an
1592
+ // unattended browser could add its own address and keep the panel after the
1593
+ // operator signs it out or changes the password.
1594
+ router.post(
1595
+ "/recovery-email/start",
1596
+ asyncRoute(async (req, res) => {
1597
+ const peer = clientAddress(req);
1598
+ const retryAfter = blockedFor(peer);
1599
+ if (retryAfter) return recoveryFailure(res, { reason: "throttled", retryAfter });
1600
+ if (!secrets.verifyDashboardPassword(req.body?.current)) {
1601
+ recordFailure(peer);
1602
+ return recoveryFailure(res, { reason: "wrong_password" });
1603
+ }
1604
+ clearAttempts(peer);
1605
+
1606
+ const result = await recoveryEmail.startVerification(req.body?.email, req.body?.lang, peer);
1607
+ if (!result.ok) return recoveryFailure(res, result);
1608
+ res.json({ success: true });
1609
+ }),
1610
+ );
1611
+
1612
+ router.post(
1613
+ "/recovery-email/verify",
1614
+ asyncRoute(async (req, res) => {
1615
+ const result = await recoveryEmail.confirmVerification(req.body?.code);
1616
+ if (!result.ok) return recoveryFailure(res, result);
1617
+ res.json({ success: true, verified: true, masked: result.masked });
1618
+ }),
1619
+ );
1620
+
1621
+ router.delete("/recovery-email", (req, res) => {
1622
+ recoveryEmail.remove();
1623
+ res.json({ success: true, verified: false });
1624
+ });
1625
+
1317
1626
  // ===========================================================================
1318
1627
  // Feedback — the operator's line to the developer
1319
1628
  // ===========================================================================
@@ -1333,13 +1642,15 @@ router.get("/feedback/meta", (req, res) => {
1333
1642
  });
1334
1643
  });
1335
1644
 
1336
- // The exact object the server would forward as `diagnostics`, so the operator
1337
- // can see what they are about to share before they send it. This is the same
1338
- // builder submitFeedback() uses, so the preview cannot lie.
1645
+ // Preview of the diagnostics object plus a frozen debug-log snapshot. Send
1646
+ // redeems `debugLogId`; it does not rebuild the tail.
1339
1647
  router.post("/feedback/diagnostics-preview", (req, res) => {
1340
1648
  const parsed = parseDiagnosticsInput(req.body?.client);
1341
1649
  if (parsed.error) return badRequest(res, parsed.error);
1342
- res.json({ success: true, diagnostics: buildDiagnostics(parsed.present ? parsed.value : {}) });
1650
+ res.json({
1651
+ success: true,
1652
+ ...buildDiagnosticsAttachment(parsed.present ? parsed.value : {}),
1653
+ });
1343
1654
  });
1344
1655
 
1345
1656
  // Leaves this machine only when the operator presses Send, and carries nothing
@@ -1395,6 +1706,7 @@ router.post(
1395
1706
  parsed.value,
1396
1707
  attachment,
1397
1708
  diagnostics.present ? diagnostics.value : undefined,
1709
+ typeof body.debugLogId === "string" ? body.debugLogId : undefined,
1398
1710
  );
1399
1711
  if (!result.ok) {
1400
1712
  return res.status(result.status).json({ success: false, error: result.error });
@@ -1703,7 +2015,7 @@ router.post("/crash-reports", (req, res) => {
1703
2015
  router.post(
1704
2016
  "/crash-reports/:id/send",
1705
2017
  asyncRoute(async (req, res) => {
1706
- const result = await crashReports.sendReport(req.params.id);
2018
+ const result = await crashReports.sendReport(req.params.id, req.body?.debugLogId);
1707
2019
  if (!result.ok) {
1708
2020
  return res.status(result.status || 502).json({ success: false, error: result.error });
1709
2021
  }
@@ -95,6 +95,23 @@ const DEFAULT_PERSONA = `You are a capable personal WhatsApp assistant.
95
95
  Be concise and direct by default, reply in the language the user writes in, and
96
96
  use your tools instead of guessing when something needs to be looked up.`;
97
97
 
98
+ // Sections the code owns now (OPERATING_RULES in src/config/ai-identity.cjs).
99
+ // A copy of ai-persona.md from before that split still carries them, and an
100
+ // operator can type one back in: both are dropped here, so the rules are stated
101
+ // once, from code, and no edit of the persona can weaken them.
102
+ const SEALED_HEADINGS = new Set(["tools", "memory", "chats and groups", "boundaries"]);
103
+
104
+ function stripSealedSections(text) {
105
+ const kept = [];
106
+ let sealed = false;
107
+ for (const line of String(text).split("\n")) {
108
+ const heading = /^#{1,3}\s+(.+?)\s*$/.exec(line);
109
+ if (heading) sealed = SEALED_HEADINGS.has(heading[1].toLowerCase());
110
+ if (!sealed) kept.push(line);
111
+ }
112
+ return kept.join("\n").trim();
113
+ }
114
+
98
115
  let personaCache = { text: null, stamp: null };
99
116
 
100
117
  /**
@@ -121,7 +138,7 @@ function loadPersona() {
121
138
  .slice(1)
122
139
  .join("\n---\n")
123
140
  : raw;
124
- personaCache = { text: body.trim() || DEFAULT_PERSONA, stamp };
141
+ personaCache = { text: stripSealedSections(body) || DEFAULT_PERSONA, stamp };
125
142
  return personaCache.text;
126
143
  } catch {
127
144
  return DEFAULT_PERSONA;
@@ -142,13 +159,17 @@ function nowLabel() {
142
159
 
143
160
  function botLangDirective() {
144
161
  const botLang = settings.get("bot_language") || "auto";
162
+ // The dialect rule lives here on purpose, not in the persona: the operator
163
+ // owns src/config/ai-persona.md and can rewrite every line of it, and this
164
+ // one must survive every edit (Levix users worldwide; Levix is built in
165
+ // Egypt, and Egyptian dialect in should mean Egyptian dialect out).
145
166
  if (botLang === "ar") {
146
- return "- Language instruction: Always reply in Modern Standard Arabic (العربية الفصحى), clear, professional, and well-phrased.";
167
+ return "- Language instruction: Always reply in Arabic. Match the dialect the user writes in: Egyptian Arabic gets natural Egyptian Arabic back; formal Arabic or any other Arabic dialect gets clear, natural Arabic matching the user's.";
147
168
  }
148
169
  if (botLang === "en") {
149
170
  return "- Language instruction: Always reply in English, clear, professional, natural, and direct.";
150
171
  }
151
- return "- Language instruction: Automatically reply in the language the user writes in (Modern Standard Arabic if Arabic, English if English).";
172
+ return "- Language instruction: Reply in the language and dialect the user writes in. Egyptian Arabic gets natural Egyptian Arabic back; formal Arabic or other Arabic dialects get clear, natural Arabic matching the user; English gets English; any other language gets that language.";
152
173
  }
153
174
 
154
175
  /**
@@ -658,6 +679,7 @@ module.exports = {
658
679
  GOOGLE_SEARCH_TOOL,
659
680
  buildSystemInstruction,
660
681
  loadPersona,
682
+ stripSealedSections,
661
683
  isAgentEnabled,
662
684
  activeProviderKeySetting,
663
685
  isFileReferenceError,