levix-bot 4.8.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 (60) hide show
  1. package/README.md +9 -5
  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 +21 -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/mod.cjs +101 -26
  26. package/src/commands/translate.cjs +585 -0
  27. package/src/config/ai-identity.cjs +53 -1
  28. package/src/config/ai-persona.md +32 -73
  29. package/src/config/defaults.cjs +2 -0
  30. package/src/config/secrets.cjs +71 -3
  31. package/src/config/settings.cjs +22 -1
  32. package/src/core/socket.js +4 -5
  33. package/src/db/db.cjs +66 -0
  34. package/src/db/store.cjs +264 -16
  35. package/src/diagnostics/crashReports.cjs +35 -9
  36. package/src/diagnostics/debugLog.cjs +405 -0
  37. package/src/handlers/command.handler.js +1 -0
  38. package/src/handlers/group.handler.js +32 -1
  39. package/src/handlers/message.handler.js +53 -17
  40. package/src/middleware/antispam.middleware.js +95 -48
  41. package/src/panel/feedback.cjs +32 -5
  42. package/src/panel/one-time-code.cjs +156 -0
  43. package/src/panel/password-reset.cjs +187 -91
  44. package/src/panel/recovery-email.cjs +333 -0
  45. package/src/routes/dashboard.api.esm.js +267 -20
  46. package/src/services/aiAgent.cjs +25 -3
  47. package/src/services/moderationPolicy.cjs +895 -0
  48. package/src/services/settingsTransfer.cjs +4 -2
  49. package/src/utils/linkedCreds.cjs +22 -0
  50. package/src/utils/logger.cjs +5 -0
  51. package/src/utils/moderationAction.cjs +637 -0
  52. package/src/utils/moderationSummary.cjs +225 -0
  53. package/src/utils/permissions.cjs +70 -0
  54. package/src/utils/permissions.esm.js +48 -8
  55. package/src/utils/storage.cjs +8 -0
  56. package/src/utils/storage.esm.js +4 -0
  57. package/views/login.ejs +100 -28
  58. package/public/dashboard/assets/index-B8E5IYlB.js +0 -540
  59. package/public/dashboard/assets/index-C5D4wzm4.css +0 -2
  60. package/src/commands/group/antiSpam.cjs +0 -97
@@ -0,0 +1,225 @@
1
+ // One builder for the "Active moderation" block. !rules, welcome, and the
2
+ // panel preview all call this so the wording cannot drift.
3
+
4
+ const { tr, withLang } = require("./i18n.cjs");
5
+ const { resolveModerationPolicy, policyFieldVisibility } = require("../services/moderationPolicy.cjs");
6
+
7
+ const MEDIA_TYPES = ["image", "video", "sticker", "audio"];
8
+ const DELETE_WARN_KICK = ["DELETE", "WARN", "KICK"];
9
+
10
+ function mediaLabel(type) {
11
+ switch (type) {
12
+ case "image":
13
+ return tr("photos", "الصور");
14
+ case "video":
15
+ return tr("videos", "الفيديو");
16
+ case "audio":
17
+ return tr("voice notes", "الصوتيات");
18
+ case "sticker":
19
+ return tr("stickers", "الملصقات");
20
+ default:
21
+ return type;
22
+ }
23
+ }
24
+
25
+ function linkModeLine(antilink) {
26
+ const mode = String(antilink?.mode || "ALL").toUpperCase();
27
+ const allowed = Array.isArray(antilink?.allowed_domains) ? antilink.allowed_domains.length : 0;
28
+ const blocked = Array.isArray(antilink?.blocked_domains) ? antilink.blocked_domains.length : 0;
29
+ if (mode === "WHITELIST") {
30
+ return tr(
31
+ `allow listed domains only (${allowed})`,
32
+ `السماح بالنطاقات المدرجة فقط (${allowed})`,
33
+ );
34
+ }
35
+ if (mode === "BLACKLIST") {
36
+ return tr(`block listed domains (${blocked})`, `حظر النطاقات المدرجة (${blocked})`);
37
+ }
38
+ return tr("block all links", "حظر كل الروابط");
39
+ }
40
+
41
+ function forbiddenInfo(settings) {
42
+ const nested = settings?.moderation?.forbiddenWords;
43
+ const listed = Array.isArray(nested?.list) ? nested.list.length : null;
44
+ const count =
45
+ listed != null ? listed : Number(settings?.forbidden_words?.count) || 0;
46
+ const enabled = Boolean(nested?.enabled ?? settings?.forbidden_words?.enabled);
47
+ return { enabled, count };
48
+ }
49
+
50
+ // Effective warn limit. A stored moderationPolicy field wins; otherwise the
51
+ // legacy warn_system values apply. Missing / empty / unknown → KICK at 3.
52
+ // Stored "NONE" (pre-v9) and "FLAG" → FLAG.
53
+ function warnConfigOf(settings) {
54
+ const policy = resolveModerationPolicy(settings);
55
+ return {
56
+ max_warnings: policy.limit,
57
+ action: policy.limitAction === "FLAG" ? "FLAG" : "KICK",
58
+ };
59
+ }
60
+
61
+ function normalizeWarnAction(raw) {
62
+ const action = String(raw || "").trim().toUpperCase();
63
+ if (action === "FLAG" || action === "NONE") return "FLAG";
64
+ if (action === "KICK") return "KICK";
65
+ return null;
66
+ }
67
+
68
+ function featureActionOf(settings, feature) {
69
+ const action = resolveModerationPolicy(settings).features?.[feature];
70
+ if (feature === "antispam") return action === "KICK" ? "KICK" : "WARN";
71
+ if (DELETE_WARN_KICK.includes(action)) return action;
72
+ return "WARN";
73
+ }
74
+
75
+ function normalizeFeatureAction(raw, { allowDelete = true } = {}) {
76
+ const action = String(raw || "").trim().toUpperCase();
77
+ if (action === "KICK" || action === "WARN") return action;
78
+ if (allowDelete && action === "DELETE") return "DELETE";
79
+ return null;
80
+ }
81
+
82
+ function policyFromFeatureAction(action) {
83
+ const resolved = String(action || "WARN").toUpperCase();
84
+ if (resolved === "DELETE") {
85
+ return { deleteMessage: true, recordWarning: false, kickImmediately: false };
86
+ }
87
+ if (resolved === "KICK") {
88
+ return { deleteMessage: true, recordWarning: true, kickImmediately: true };
89
+ }
90
+ return { deleteMessage: true, recordWarning: true, kickImmediately: false };
91
+ }
92
+
93
+ function deleteWarnKickLabel(action) {
94
+ if (action === "DELETE") return tr("delete only", "حذف فقط");
95
+ if (action === "KICK") return tr("delete and remove the member", "حذف وطرد العضو");
96
+ return tr("delete and warn", "حذف وإنذار");
97
+ }
98
+
99
+ function renderModerationSummary(settings = {}) {
100
+ const lines = [tr("*Active moderation*", "*الإشراف المفعّل*")];
101
+
102
+ if (settings.antilink?.enabled) {
103
+ const action = deleteWarnKickLabel(featureActionOf(settings, "antilink"));
104
+ lines.push(
105
+ tr(
106
+ `• Anti-link: on — ${linkModeLine(settings.antilink)}. Action: ${action}.`,
107
+ `• منع الروابط: مفعّل — ${linkModeLine(settings.antilink)}. الإجراء: ${action}.`,
108
+ ),
109
+ );
110
+ }
111
+
112
+ if (settings.antispam?.enabled) {
113
+ const windowSec = settings.antispam.time_window ?? 10;
114
+ const count = settings.antispam.message_count ?? 5;
115
+ const action = featureActionOf(settings, "antispam");
116
+ const actionText =
117
+ action === "KICK"
118
+ ? tr("remove the member", "طرد العضو")
119
+ : tr("warn", "إنذار");
120
+ lines.push(
121
+ tr(
122
+ `• Anti-spam: on — ${count} messages / ${windowSec}s. Action: ${actionText}.`,
123
+ `• مكافحة الإزعاج: مفعّلة — ${count} رسائل / ${windowSec}ث. الإجراء: ${actionText}.`,
124
+ ),
125
+ );
126
+ }
127
+
128
+ const blocked = (settings.media_control?.blocked_types || []).filter((type) =>
129
+ MEDIA_TYPES.includes(type),
130
+ );
131
+ if (settings.media_control?.enabled && blocked.length) {
132
+ const names = blocked.map(mediaLabel).join(tr(", ", "، "));
133
+ const action = deleteWarnKickLabel(featureActionOf(settings, "media"));
134
+ lines.push(
135
+ tr(`• Media: ${names}. Action: ${action}.`, `• الوسائط: ${names}. الإجراء: ${action}.`),
136
+ );
137
+ }
138
+
139
+ const words = forbiddenInfo(settings);
140
+ if (words.enabled) {
141
+ const action = deleteWarnKickLabel(featureActionOf(settings, "forbidden"));
142
+ lines.push(
143
+ tr(
144
+ `• Forbidden words: ${words.count}. Action: ${action}.`,
145
+ `• الكلمات الممنوعة: ${words.count}. الإجراء: ${action}.`,
146
+ ),
147
+ );
148
+ }
149
+
150
+ const warn = warnConfigOf(settings);
151
+ const atLimit =
152
+ warn.action === "FLAG"
153
+ ? tr("flag for admin review", "إبلاغ المشرفين للمراجعة")
154
+ : tr("remove the member", "طرد العضو");
155
+ lines.push(
156
+ tr(
157
+ `• Warn limit: ${warn.max_warnings}. At the limit: ${atLimit}.`,
158
+ `• حد الإنذارات: ${warn.max_warnings}. عند بلوغ الحد: ${atLimit}.`,
159
+ ),
160
+ );
161
+
162
+ const policy = resolveModerationPolicy(settings);
163
+ const visibility = policyFieldVisibility(policy);
164
+ if (policy.decay.mode === "expire") {
165
+ lines.push(
166
+ tr(
167
+ `• Warnings drop after ${policy.decay.days} days.`,
168
+ `• تسقط الإنذارات بعد ${policy.decay.days} يومًا.`,
169
+ ),
170
+ );
171
+ } else if (policy.decay.mode === "step") {
172
+ lines.push(
173
+ tr(
174
+ `• Warnings lose one point every ${policy.decay.days} days.`,
175
+ `• تفقد الإنذارات نقطة كل ${policy.decay.days} يومًا.`,
176
+ ),
177
+ );
178
+ }
179
+ if (visibility["flag.notify"]) {
180
+ const notify =
181
+ policy.flag.notify === "silent"
182
+ ? tr("silent", "بصمت")
183
+ : tr("in the group", "في المجموعة");
184
+ lines.push(
185
+ tr(`• Flag notice: ${notify}.`, `• إشعار الإبلاغ: ${notify}.`),
186
+ );
187
+ }
188
+ lines.push(
189
+ policy.membership === "keep"
190
+ ? tr(
191
+ "• Leaving or being removed keeps warnings.",
192
+ "• المغادرة أو الإزالة تبقي الإنذارات.",
193
+ )
194
+ : tr(
195
+ "• Leaving or being removed clears warnings.",
196
+ "• المغادرة أو الإزالة تمسح الإنذارات.",
197
+ ),
198
+ );
199
+
200
+ return lines.join("\n");
201
+ }
202
+
203
+ function buildModerationSummary(settings, lang) {
204
+ if (lang) return withLang(lang, () => renderModerationSummary(settings));
205
+ return renderModerationSummary(settings);
206
+ }
207
+
208
+ function buildModerationSummaryBoth(settings) {
209
+ return {
210
+ en: buildModerationSummary(settings, "en"),
211
+ ar: buildModerationSummary(settings, "ar"),
212
+ };
213
+ }
214
+
215
+ module.exports = {
216
+ buildModerationSummary,
217
+ buildModerationSummaryBoth,
218
+ mediaLabel,
219
+ warnConfigOf,
220
+ normalizeWarnAction,
221
+ featureActionOf,
222
+ normalizeFeatureAction,
223
+ policyFromFeatureAction,
224
+ forbiddenInfo,
225
+ };
@@ -12,6 +12,7 @@
12
12
  // permission we can't verify.
13
13
 
14
14
  const logger = require("./logger.cjs");
15
+ const normalizeJidCjs = require("./normalizeJid.cjs");
15
16
 
16
17
  let mod = null;
17
18
 
@@ -89,6 +90,72 @@ function sameUserSync(a, b) {
89
90
  }
90
91
  }
91
92
 
93
+ function collectNormalized(values) {
94
+ const seen = new Set();
95
+ const out = [];
96
+ for (const value of values || []) {
97
+ const norm = normalizeJidCjs(value);
98
+ if (norm && !seen.has(norm)) {
99
+ seen.add(norm);
100
+ out.push(norm);
101
+ }
102
+ }
103
+ return out;
104
+ }
105
+
106
+ function getSenderCandidatesSync(msg, sock) {
107
+ if (mod?.getSenderCandidates) {
108
+ try {
109
+ return mod.getSenderCandidates(msg, sock);
110
+ } catch (err) {
111
+ logger.error({ err }, "[permissions.cjs] getSenderCandidatesSync failed");
112
+ }
113
+ }
114
+ if (!msg) return [];
115
+ const key = msg.key || {};
116
+ let raw;
117
+ if (key.fromMe) raw = [sock?.user?.id, sock?.user?.lid];
118
+ else if (key.remoteJid?.endsWith("@g.us")) {
119
+ raw = [key.participant, key.participantAlt, key.participantPn, key.senderPn];
120
+ } else {
121
+ raw = [key.remoteJid, key.remoteJidAlt, key.senderPn];
122
+ }
123
+ return collectNormalized(raw);
124
+ }
125
+
126
+ function findGroupParticipantSync(groupMetadata, jidOrList) {
127
+ if (mod?.findGroupParticipant) {
128
+ try {
129
+ return mod.findGroupParticipant(groupMetadata, jidOrList);
130
+ } catch (err) {
131
+ logger.error({ err }, "[permissions.cjs] findGroupParticipantSync failed");
132
+ }
133
+ }
134
+ const targets = collectNormalized(Array.isArray(jidOrList) ? jidOrList : [jidOrList]);
135
+ if (!groupMetadata?.participants || !targets.length) return null;
136
+ return (
137
+ groupMetadata.participants.find((p) =>
138
+ [p.id, p.lid, p.phoneNumber, p.jid]
139
+ .filter(Boolean)
140
+ .some((pid) => targets.includes(normalizeJidCjs(pid))),
141
+ ) || null
142
+ );
143
+ }
144
+
145
+ function rosterJidForSync(groupMetadata, jidOrList) {
146
+ if (mod?.rosterJidFor) {
147
+ try {
148
+ return mod.rosterJidFor(groupMetadata, jidOrList);
149
+ } catch (err) {
150
+ logger.error({ err }, "[permissions.cjs] rosterJidForSync failed");
151
+ }
152
+ }
153
+ const found = findGroupParticipantSync(groupMetadata, jidOrList);
154
+ if (found?.id) return found.id;
155
+ const list = Array.isArray(jidOrList) ? jidOrList : [jidOrList];
156
+ return collectNormalized(list)[0] || list.find(Boolean) || null;
157
+ }
158
+
92
159
  async function isOwnerJid(jid) {
93
160
  const m = await getMod();
94
161
  return m.isOwnerJid(jid);
@@ -151,4 +218,7 @@ module.exports = {
151
218
  isAdminInGroupSync,
152
219
  isBotAdminInGroupSync,
153
220
  sameUserSync,
221
+ getSenderCandidatesSync,
222
+ findGroupParticipantSync,
223
+ rosterJidForSync,
154
224
  };
@@ -299,27 +299,67 @@ export function sameUser(a, b) {
299
299
  * match `jid` against ALL of them so admin detection works whether the caller
300
300
  * hands us a LID or a PN, even before the lid_mapping table is populated.
301
301
  */
302
+ export function participantIds(participant) {
303
+ if (!participant) return [];
304
+ return [participant.id, participant.lid, participant.phoneNumber, participant.jid].filter(
305
+ Boolean,
306
+ );
307
+ }
308
+
302
309
  export function isAdminInGroup(groupMetadata, jid) {
303
310
  if (!groupMetadata?.participants || !jid) return false;
304
311
  const target = normalizeJid(jid);
305
312
  return groupMetadata.participants.some((p) => {
306
313
  if (!["admin", "superadmin"].includes(p.admin)) return false;
307
- const participantIds = [p.id, p.lid, p.phoneNumber, p.jid].filter(Boolean);
308
- return participantIds.some((pid) => normalizeJid(pid) === target || sameUser(pid, jid));
314
+ return participantIds(p).some((pid) => normalizeJid(pid) === target || sameUser(pid, jid));
309
315
  });
310
316
  }
311
317
 
318
+ /**
319
+ * The group-roster row for this person, matching LID / PN / phone across
320
+ * `id`, `lid`, `phoneNumber` and `jid`.
321
+ */
322
+ export function findGroupParticipant(groupMetadata, jidOrList) {
323
+ const targets = (Array.isArray(jidOrList) ? jidOrList : [jidOrList]).filter(Boolean);
324
+ if (!groupMetadata?.participants || !targets.length) return null;
325
+ return (
326
+ groupMetadata.participants.find((p) =>
327
+ participantIds(p).some((pid) => targets.some((target) => sameUser(pid, target))),
328
+ ) || null
329
+ );
330
+ }
331
+
332
+ /**
333
+ * The JID WhatsApp expects in `groupParticipantsUpdate` — the roster `id`,
334
+ * not the mention / sender form which may be the other of LID vs PN.
335
+ */
336
+ export function rosterJidFor(groupMetadata, jidOrList) {
337
+ const found = findGroupParticipant(groupMetadata, jidOrList);
338
+ if (found?.id) return found.id;
339
+ const targets = (Array.isArray(jidOrList) ? jidOrList : [jidOrList]).filter(Boolean);
340
+ return normalizeJid(targets[0]) || targets[0] || null;
341
+ }
342
+
343
+ /** Every identifier we know for the linked WhatsApp account. */
344
+ export function botIdentityCandidates(sock) {
345
+ const raw = [sock?.user?.id, sock?.user?.lid].filter(Boolean);
346
+ const out = [];
347
+ for (const value of raw) {
348
+ for (const form of identityForms(value)) {
349
+ if (!out.includes(form)) out.push(form);
350
+ }
351
+ }
352
+ return out;
353
+ }
354
+
312
355
  /**
313
356
  * Check whether the bot itself is admin in the group. We check both the
314
- * bot's PN and its LID since either form may be stored on the participant.
357
+ * bot's PN and its LID (and lid_mapping aliases) since either form may be
358
+ * stored on the participant.
315
359
  */
316
360
  export function isBotAdminInGroup(groupMetadata, sock) {
317
361
  if (!groupMetadata?.participants || !sock) return false;
318
- const candidates = [sock.user?.id, sock.user?.lid].filter(Boolean);
319
- for (const candidate of candidates) {
320
- if (isAdminInGroup(groupMetadata, candidate)) return true;
321
- }
322
- return false;
362
+ return botIdentityCandidates(sock).some((candidate) => isAdminInGroup(groupMetadata, candidate));
323
363
  }
324
364
 
325
365
  /**
@@ -29,6 +29,14 @@ module.exports = {
29
29
  saveUserWarnings: store.saveUserWarnings,
30
30
  clearUserWarnings: store.clearUserWarnings,
31
31
  getAllWarnings: store.getAllWarnings,
32
+ getModerationFlag: store.getModerationFlag,
33
+ upsertModerationFlag: store.upsertModerationFlag,
34
+ clearModerationFlag: store.clearModerationFlag,
35
+ listModerationFlags: store.listModerationFlags,
36
+ getModerationApplied: store.getModerationApplied,
37
+ commitModerationDecision: store.commitModerationDecision,
38
+ markModerationNotice: store.markModerationNotice,
39
+ markModerationKicked: store.markModerationKicked,
32
40
  // Todos
33
41
  getUserTodos: store.getUserTodos,
34
42
  saveUserTodos: store.saveUserTodos,
@@ -29,6 +29,10 @@ export const getUserWarnings = store.getUserWarnings;
29
29
  export const saveUserWarnings = store.saveUserWarnings;
30
30
  export const clearUserWarnings = store.clearUserWarnings;
31
31
  export const getAllWarnings = store.getAllWarnings;
32
+ export const getModerationFlag = store.getModerationFlag;
33
+ export const upsertModerationFlag = store.upsertModerationFlag;
34
+ export const clearModerationFlag = store.clearModerationFlag;
35
+ export const listModerationFlags = store.listModerationFlags;
32
36
 
33
37
  // ===== Todos =====
34
38
  export const getUserTodos = store.getUserTodos;
package/views/login.ejs CHANGED
@@ -85,16 +85,34 @@
85
85
  <div class="auth-head">
86
86
  <span class="eyebrow" data-i18n="resetEyebrow">Password reset</span>
87
87
  <h1 data-i18n="resetTitle">Reset your password</h1>
88
+ <% if (recoveryEmailVerified && recoveryEmail) { %>
89
+ <p class="sub" data-i18n="resetSubtitleChannels">
90
+ Levix can send a one-time code to WhatsApp, or to your recovery email. The code works for 10 minutes.
91
+ </p>
92
+ <% } else { %>
88
93
  <p class="sub" data-i18n="resetSubtitle">
89
94
  Levix sends a one-time code to your WhatsApp — the linked account's own chat.
90
95
  The code works for 10 minutes.
91
96
  </p>
97
+ <% } %>
92
98
  </div>
93
99
 
94
- <button type="button" class="btn btn-primary auth-submit" id="reset-send">
95
- <span data-i18n="resetSend">Send code to WhatsApp</span>
96
- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
97
- </button>
100
+ <div id="reset-channels" class="reset-channels">
101
+ <button type="button" class="btn btn-primary auth-submit" id="reset-send" data-channel="whatsapp">
102
+ <span data-i18n="resetSend">Send code to WhatsApp</span>
103
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
104
+ </button>
105
+ <% if (recoveryEmailVerified && recoveryEmail) { %>
106
+ <button type="button" class="btn auth-submit" id="reset-send-email" data-channel="email">
107
+ <span data-i18n="resetSendEmail">Send code to email</span>
108
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
109
+ </button>
110
+ <p class="sub reset-email-hint">
111
+ <span data-i18n="resetEmailHint">The code goes to</span>
112
+ <strong dir="ltr"><%= recoveryEmail %></strong>
113
+ </p>
114
+ <% } %>
115
+ </div>
98
116
 
99
117
  <form id="reset-form" hidden>
100
118
  <label class="field">
@@ -154,6 +172,7 @@
154
172
  <span data-i18n="resetSubmit">Set new password</span>
155
173
  <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
156
174
  </button>
175
+ <button type="button" class="link-btn" id="reset-choose-channel" data-i18n="resetChooseChannel">Choose another recovery method</button>
157
176
  </form>
158
177
 
159
178
  <div class="error" id="reset-error" role="alert" hidden></div>
@@ -184,7 +203,7 @@
184
203
 
185
204
  var loginCard = document.getElementById("login-card");
186
205
  var resetCard = document.getElementById("reset-card");
187
- var sendBtn = document.getElementById("reset-send");
206
+ var channels = document.getElementById("reset-channels");
188
207
  var form = document.getElementById("reset-form");
189
208
  var errorBox = document.getElementById("reset-error");
190
209
 
@@ -244,16 +263,19 @@
244
263
  });
245
264
 
246
265
  async function postJson(url, body) {
247
- const response = await fetch(url, {
248
- method: "POST",
249
- headers: { "Content-Type": "application/json" },
250
- body: JSON.stringify(body || {}),
251
- });
252
- let data = {};
266
+ const controller = new AbortController();
267
+ const timer = setTimeout(function () { controller.abort(); }, 20000);
253
268
  try {
254
- data = await response.json();
255
- } catch {}
256
- return data;
269
+ const response = await fetch(url, {
270
+ method: "POST",
271
+ headers: { "Content-Type": "application/json" },
272
+ body: JSON.stringify(body || {}),
273
+ signal: controller.signal,
274
+ });
275
+ return await response.json();
276
+ } finally {
277
+ clearTimeout(timer);
278
+ }
257
279
  }
258
280
 
259
281
  document.getElementById("forgot-link").addEventListener("click", showReset);
@@ -265,32 +287,72 @@
265
287
  }
266
288
  });
267
289
 
268
- sendBtn.addEventListener("click", async function () {
269
- sendBtn.disabled = true;
290
+ function setChannelBusy(busy) {
291
+ var buttons = channels.querySelectorAll("[data-channel]");
292
+ for (var i = 0; i < buttons.length; i += 1) buttons[i].disabled = busy;
293
+ }
294
+
295
+ function showSendError(result) {
296
+ if (result.reason === "throttled") {
297
+ showErrorKey("resetErrThrottled", { n: String(result.retryAfter || 60) });
298
+ } else if (result.reason === "no_session") {
299
+ showErrorKey("resetErrNoSession");
300
+ } else if (result.reason === "send_failed") {
301
+ showErrorKey("resetErrSendFailed");
302
+ } else if (result.reason === "no_email") {
303
+ showErrorKey("resetErrNoEmail");
304
+ } else if (result.reason === "unverified") {
305
+ showErrorKey("resetErrUnverified");
306
+ } else if (result.reason === "locked") {
307
+ showErrorKey("resetErrLocked");
308
+ } else if (result.reason === "rate_limited") {
309
+ if (result.retryAfter) showErrorKey("resetErrThrottled", { n: String(result.retryAfter) });
310
+ else showErrorKey("resetErrRateLimited");
311
+ } else if (result.reason === "unavailable") {
312
+ showErrorKey("resetErrUnavailable");
313
+ } else if (result.reason === "invalid") {
314
+ showErrorKey("resetErrInvalid");
315
+ } else {
316
+ showErrorKey("resetErrStart");
317
+ }
318
+ }
319
+
320
+ channels.addEventListener("click", async function (event) {
321
+ var button = event.target.closest("[data-channel]");
322
+ if (!button || button.disabled) return;
323
+ var channel = button.getAttribute("data-channel");
324
+ var lang = window.LevixGatewayI18n && window.LevixGatewayI18n.lang === "ar" ? "ar" : "en";
325
+ setChannelBusy(true);
270
326
  hideError();
271
327
  try {
272
- const result = await postJson("/reset/request");
328
+ const result = await postJson("/reset/request", { channel: channel, lang: lang });
273
329
  if (result.ok) {
274
- sendBtn.hidden = true;
330
+ channels.hidden = true;
275
331
  form.hidden = false;
276
332
  document.getElementById("reset-code").focus();
277
- } else if (result.reason === "throttled") {
278
- showErrorKey("resetErrThrottled", { n: String(result.retryAfter || 60) });
279
- } else if (result.reason === "no_session") {
280
- showErrorKey("resetErrNoSession");
281
- } else if (result.reason === "send_failed") {
282
- showErrorKey("resetErrSendFailed");
283
333
  } else {
284
- showErrorKey("resetErrStart");
334
+ showSendError(result);
285
335
  }
286
336
  } catch {
287
337
  showErrorKey("resetErrServer");
288
338
  }
289
- sendBtn.disabled = false;
339
+ setChannelBusy(false);
290
340
  });
291
341
 
342
+ var confirming = false;
343
+ document.getElementById("reset-choose-channel").addEventListener("click", function () {
344
+ if (confirming) return;
345
+ form.hidden = true;
346
+ channels.hidden = false;
347
+ document.getElementById("reset-code").value = "";
348
+ hideError();
349
+ });
292
350
  form.addEventListener("submit", async function (event) {
293
351
  event.preventDefault();
352
+ if (confirming) return;
353
+ confirming = true;
354
+ var submit = form.querySelector('[type="submit"]');
355
+ submit.disabled = true;
294
356
  hideError();
295
357
  try {
296
358
  const result = await postJson("/reset/confirm", {
@@ -300,7 +362,7 @@
300
362
  });
301
363
  if (result.ok) {
302
364
  form.hidden = true;
303
- sendBtn.hidden = true;
365
+ channels.hidden = true;
304
366
  showErrorKey("resetDone");
305
367
  setTimeout(function () {
306
368
  window.location.href = "/";
@@ -311,13 +373,20 @@
311
373
  currentErrorState = { type: "wrong_code", attemptsLeft: result.attemptsLeft };
312
374
  renderCurrentError();
313
375
  } else if (
376
+ result.reason === "address_changed" ||
314
377
  result.reason === "expired" ||
315
378
  result.reason === "no_pending" ||
316
379
  result.reason === "too_many_attempts"
317
380
  ) {
318
381
  showErrorKey("resetErrExpired");
319
382
  form.hidden = true;
320
- sendBtn.hidden = false;
383
+ channels.hidden = false;
384
+ } else if (result.reason === "locked") {
385
+ showErrorKey("resetErrLocked");
386
+ form.hidden = true;
387
+ channels.hidden = false;
388
+ } else if (result.reason === "throttled") {
389
+ showErrorKey("resetErrThrottled", { n: String(result.retryAfter || 60) });
321
390
  } else if (result.reason === "mismatch") {
322
391
  showErrorKey("resetErrMismatch");
323
392
  } else if (result.reason === "invalid_password") {
@@ -328,6 +397,9 @@
328
397
  }
329
398
  } catch {
330
399
  showErrorKey("resetErrServer");
400
+ } finally {
401
+ confirming = false;
402
+ submit.disabled = false;
331
403
  }
332
404
  });
333
405
  })();