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
package/src/db/store.cjs CHANGED
@@ -226,29 +226,106 @@ function clearWhatsAppDirectory() {
226
226
  clearGroupSettings();
227
227
  clearUserMetadata();
228
228
  clearLidMappings();
229
+ clearAllModerationFlags();
229
230
  }
230
231
 
231
232
  // ===================================================================
232
233
  // --- Warnings ---
233
234
  // ===================================================================
235
+ //
236
+ // Rows are keyed by (group_id, user_id). Baileys v7 names the same person as a
237
+ // LID on one message and a phone JID on the next, so every read/write walks
238
+ // the known aliases (the stored id plus lid_mapping) and collapses them onto
239
+ // one canonical row — the phone JID when we have it, otherwise the LID.
240
+
241
+ function warningUserIds(userId) {
242
+ const ids = [];
243
+ const add = (value) => {
244
+ const norm = normalizeJid(value);
245
+ if (norm && !ids.includes(norm)) ids.push(norm);
246
+ };
247
+ add(userId);
248
+ const norm = normalizeJid(userId);
249
+ if (!norm) return ids;
250
+ // A LID resolves to a phone, then that phone expands to every LID stored
251
+ // for it. Otherwise a second LID of the same number misses the first ledger.
252
+ const phones = [];
253
+ const addPhone = (value) => {
254
+ const phone = normalizeJid(value);
255
+ if (!phone || isLidJid(phone) || phones.includes(phone)) return;
256
+ phones.push(phone);
257
+ };
258
+ if (isLidJid(norm)) {
259
+ addPhone(getPnForLid(norm));
260
+ if (norm !== userId) addPhone(getPnForLid(userId));
261
+ } else {
262
+ addPhone(norm);
263
+ if (norm !== userId) addPhone(userId);
264
+ }
265
+ for (const phone of phones) {
266
+ add(phone);
267
+ add(getLidForPn(phone));
268
+ for (const lid of getLidsForPn(phone)) add(lid);
269
+ }
270
+ return ids;
271
+ }
272
+
273
+ function canonicalWarningUserId(userId) {
274
+ const ids = warningUserIds(userId);
275
+ const pn = ids.find((id) => String(id).includes("@s.whatsapp.net"));
276
+ return pn || ids[0] || userId;
277
+ }
278
+
279
+ function readWarningRows(groupId, userIds) {
280
+ const merged = [];
281
+ const seen = new Set();
282
+ const seenIds = new Set();
283
+ for (const id of userIds) {
284
+ const row = q("SELECT warnings FROM warnings WHERE group_id = ? AND user_id = ?").get(
285
+ groupId,
286
+ id,
287
+ );
288
+ const list = row ? parseJson(row.warnings, []) : [];
289
+ for (const warning of list) {
290
+ const messageId = warning?.messageId;
291
+ if (messageId) {
292
+ if (seenIds.has(messageId)) continue;
293
+ seenIds.add(messageId);
294
+ merged.push(warning);
295
+ continue;
296
+ }
297
+ const key = `${warning?.date || ""}|${warning?.reason || ""}|${warning?.by || ""}`;
298
+ if (seen.has(key)) continue;
299
+ seen.add(key);
300
+ merged.push(warning);
301
+ }
302
+ }
303
+ merged.sort((a, b) => String(a?.date || "").localeCompare(String(b?.date || "")));
304
+ return merged;
305
+ }
234
306
 
235
307
  function getUserWarnings(groupId, userId) {
236
- const row = q("SELECT warnings FROM warnings WHERE group_id = ? AND user_id = ?").get(
237
- groupId,
238
- userId,
239
- );
240
- return row ? parseJson(row.warnings, []) : [];
308
+ return readWarningRows(groupId, warningUserIds(userId));
241
309
  }
242
310
 
243
311
  function saveUserWarnings(groupId, userId, warningsArray) {
312
+ const canonical = canonicalWarningUserId(userId);
313
+ const aliases = warningUserIds(userId);
244
314
  q(
245
315
  `INSERT INTO warnings (group_id, user_id, warnings) VALUES (?, ?, ?)
246
316
  ON CONFLICT(group_id, user_id) DO UPDATE SET warnings = excluded.warnings`,
247
- ).run(groupId, userId, JSON.stringify(warningsArray || []));
317
+ ).run(groupId, canonical, JSON.stringify(warningsArray || []));
318
+ for (const id of aliases) {
319
+ if (id !== canonical) {
320
+ q("DELETE FROM warnings WHERE group_id = ? AND user_id = ?").run(groupId, id);
321
+ }
322
+ }
248
323
  }
249
324
 
250
325
  function clearUserWarnings(groupId, userId) {
251
- q("DELETE FROM warnings WHERE group_id = ? AND user_id = ?").run(groupId, userId);
326
+ for (const id of warningUserIds(userId)) {
327
+ q("DELETE FROM warnings WHERE group_id = ? AND user_id = ?").run(groupId, id);
328
+ }
252
329
  }
253
330
 
254
331
  function getAllWarnings() {
@@ -265,6 +342,175 @@ function countWarnings() {
265
342
  return q("SELECT COUNT(*) AS n FROM warnings").get().n;
266
343
  }
267
344
 
345
+ // ===================================================================
346
+ // --- Moderation flags ---
347
+ // ===================================================================
348
+ //
349
+ // One row per (group, canonical member). Same LID/PN alias collapse as
350
+ // warnings: the phone JID when we have it, otherwise the LID.
351
+
352
+ const FLAG_COLUMNS =
353
+ "group_id, user_id, warn_count, last_rule, flagged_at, reasons, last_notified_at, repeat_points";
354
+
355
+ function parseFlagRow(row) {
356
+ if (!row) return null;
357
+ return {
358
+ group_id: row.group_id,
359
+ user_id: row.user_id,
360
+ warn_count: Number(row.warn_count) || 0,
361
+ last_rule: row.last_rule || "",
362
+ flagged_at: Number(row.flagged_at) || 0,
363
+ reasons: parseJson(row.reasons, []),
364
+ last_notified_at: row.last_notified_at == null ? null : Number(row.last_notified_at),
365
+ repeat_points: Number(row.repeat_points) || 0,
366
+ };
367
+ }
368
+
369
+ function getModerationFlag(groupId, userId) {
370
+ for (const id of warningUserIds(userId)) {
371
+ const row = q(
372
+ `SELECT ${FLAG_COLUMNS}
373
+ FROM moderation_flags WHERE group_id = ? AND user_id = ?`,
374
+ ).get(groupId, id);
375
+ if (row) return parseFlagRow(row);
376
+ }
377
+ return null;
378
+ }
379
+
380
+ function upsertModerationFlag(groupId, userId, payload = {}) {
381
+ const canonical = canonicalWarningUserId(userId);
382
+ const existing = getModerationFlag(groupId, userId);
383
+ const incoming = Array.isArray(payload.reasons) ? payload.reasons : [];
384
+ const reasons = [];
385
+ const seen = new Set();
386
+ for (const item of [...(existing?.reasons || []), ...incoming]) {
387
+ const text = String(item || "").slice(0, 200);
388
+ if (!text || seen.has(text)) continue;
389
+ seen.add(text);
390
+ reasons.push(text);
391
+ if (reasons.length >= 20) break;
392
+ }
393
+ const warnCount =
394
+ payload.warnCount != null ? Number(payload.warnCount) : existing?.warn_count || 0;
395
+ const lastRule =
396
+ payload.lastRule != null ? String(payload.lastRule).slice(0, 80) : existing?.last_rule || "";
397
+ const flaggedAt = Number(payload.flaggedAt) || Date.now();
398
+ const repeatPoints =
399
+ payload.repeatPoints != null ? Number(payload.repeatPoints) : existing?.repeat_points || 0;
400
+ const lastNotifiedAt =
401
+ "lastNotifiedAt" in payload ? payload.lastNotifiedAt : (existing?.last_notified_at ?? null);
402
+ q(
403
+ `INSERT INTO moderation_flags (
404
+ group_id, user_id, warn_count, last_rule, flagged_at, reasons, last_notified_at, repeat_points
405
+ )
406
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
407
+ ON CONFLICT(group_id, user_id) DO UPDATE SET
408
+ warn_count = excluded.warn_count,
409
+ last_rule = excluded.last_rule,
410
+ flagged_at = excluded.flagged_at,
411
+ reasons = excluded.reasons,
412
+ last_notified_at = excluded.last_notified_at,
413
+ repeat_points = excluded.repeat_points`,
414
+ ).run(
415
+ groupId,
416
+ canonical,
417
+ warnCount,
418
+ lastRule,
419
+ flaggedAt,
420
+ JSON.stringify(reasons),
421
+ lastNotifiedAt == null ? null : Number(lastNotifiedAt),
422
+ Number.isFinite(repeatPoints) ? repeatPoints : 0,
423
+ );
424
+ for (const id of warningUserIds(userId)) {
425
+ if (id !== canonical) {
426
+ q("DELETE FROM moderation_flags WHERE group_id = ? AND user_id = ?").run(groupId, id);
427
+ }
428
+ }
429
+ return getModerationFlag(groupId, canonical);
430
+ }
431
+
432
+ function clearModerationFlag(groupId, userId) {
433
+ for (const id of warningUserIds(userId)) {
434
+ q("DELETE FROM moderation_flags WHERE group_id = ? AND user_id = ?").run(groupId, id);
435
+ }
436
+ }
437
+
438
+ function listModerationFlags(groupId) {
439
+ return q(
440
+ `SELECT ${FLAG_COLUMNS}
441
+ FROM moderation_flags WHERE group_id = ? ORDER BY flagged_at DESC`,
442
+ )
443
+ .all(groupId)
444
+ .map(parseFlagRow);
445
+ }
446
+
447
+ function clearAllModerationFlags() {
448
+ q("DELETE FROM moderation_flags").run();
449
+ q("DELETE FROM moderation_applied").run();
450
+ }
451
+
452
+ function getModerationApplied(groupId, messageId) {
453
+ if (!groupId || !messageId) return null;
454
+ const row = q(
455
+ `SELECT outcome, kicked, notified FROM moderation_applied
456
+ WHERE group_id = ? AND message_id = ?`,
457
+ ).get(groupId, messageId);
458
+ if (!row) return null;
459
+ return { outcome: row.outcome, kicked: row.kicked === 1, notified: row.notified === 1 };
460
+ }
461
+
462
+ // One moderated message is claimed once. The callback reads and writes the
463
+ // ledger; side effects (delete, notice, kick) happen after this commits.
464
+ function commitModerationDecision(groupId, messageId, fn) {
465
+ return withImmediateTransaction(() => {
466
+ if (messageId) {
467
+ const existing = getModerationApplied(groupId, messageId);
468
+ if (existing) return { duplicate: true, ...existing };
469
+ }
470
+ const result = fn();
471
+ if (messageId && result && !result.duplicate) {
472
+ q(
473
+ `INSERT INTO moderation_applied
474
+ (group_id, message_id, outcome, kicked, notified, applied_at)
475
+ VALUES (?, ?, ?, 0, 0, ?)`,
476
+ ).run(groupId, messageId, result.outcome || "none", Date.now());
477
+ }
478
+ return result;
479
+ });
480
+ }
481
+
482
+ function markModerationNotice(
483
+ groupId,
484
+ messageId,
485
+ userId,
486
+ { flagNotice = false, at = Date.now() } = {},
487
+ ) {
488
+ if (!messageId) return;
489
+ withImmediateTransaction(() => {
490
+ q(`UPDATE moderation_applied SET notified = 1 WHERE group_id = ? AND message_id = ?`).run(
491
+ groupId,
492
+ messageId,
493
+ );
494
+ if (flagNotice && userId) {
495
+ q(`UPDATE moderation_flags SET last_notified_at = ? WHERE group_id = ? AND user_id = ?`).run(
496
+ at,
497
+ groupId,
498
+ canonicalWarningUserId(userId),
499
+ );
500
+ }
501
+ });
502
+ }
503
+
504
+ function markModerationKicked(groupId, messageId) {
505
+ if (!messageId) return;
506
+ withImmediateTransaction(() => {
507
+ q(`UPDATE moderation_applied SET kicked = 1 WHERE group_id = ? AND message_id = ?`).run(
508
+ groupId,
509
+ messageId,
510
+ );
511
+ });
512
+ }
513
+
268
514
  // ===================================================================
269
515
  // --- Todos ---
270
516
  // ===================================================================
@@ -1052,19 +1298,12 @@ function hasCredentials() {
1052
1298
  return !!q("SELECT 1 AS x FROM baileys_auth WHERE key = 'creds'").get();
1053
1299
  }
1054
1300
 
1055
- /**
1056
- * A finished pairing — not merely that a creds row exists. Baileys writes
1057
- * creds on the first socket, and requestPairingCode fills me.id before the
1058
- * phone accepts, so only `registered !== false` plus a me.id is proof.
1059
- */
1301
+ /** A finished pairing, not merely that a creds row exists. See linkedCreds.cjs. */
1060
1302
  function isPairedSession() {
1061
1303
  const text = authRead("creds");
1062
1304
  if (!text) return false;
1063
1305
  try {
1064
- const creds = JSON.parse(text);
1065
- const meId = creds?.me?.id;
1066
- if (!meId) return false;
1067
- return creds.registered !== false;
1306
+ return require("../utils/linkedCreds.cjs").isLinkedCreds(JSON.parse(text));
1068
1307
  } catch {
1069
1308
  return false;
1070
1309
  }
@@ -1862,6 +2101,15 @@ module.exports = {
1862
2101
  clearUserWarnings,
1863
2102
  getAllWarnings,
1864
2103
  countWarnings,
2104
+ getModerationFlag,
2105
+ upsertModerationFlag,
2106
+ clearModerationFlag,
2107
+ listModerationFlags,
2108
+ clearAllModerationFlags,
2109
+ getModerationApplied,
2110
+ commitModerationDecision,
2111
+ markModerationNotice,
2112
+ markModerationKicked,
1865
2113
  // Todos
1866
2114
  getUserTodos,
1867
2115
  saveUserTodos,
@@ -16,6 +16,7 @@ const path = require("node:path");
16
16
  const { dataPath } = require("../config/paths.cjs");
17
17
  const { sanitizeText } = require("./sanitize.cjs");
18
18
  const { sanitizeClientFields } = require("./device.cjs");
19
+ const { readDebugTail, readDebugSnapshot, storeDebugSnapshot } = require("./debugLog.cjs");
19
20
 
20
21
  const CRASH_DIR = dataPath("crash-reports");
21
22
  const SENT_FILE = path.join(CRASH_DIR, "sent.json");
@@ -346,8 +347,10 @@ function createReport(input = {}) {
346
347
  }
347
348
 
348
349
  /**
349
- * The exact object that would be sent: no local-only keys, re-sanitized. This
350
- * is also what GET /crash-reports previews (with status/lastError added back).
350
+ * The report part of the object that would be sent: no local-only keys,
351
+ * re-sanitized. `forwardReport()` adds the technical debug log beside it.
352
+ * This is also what GET /crash-reports previews (with status/lastError added
353
+ * back).
351
354
  */
352
355
  function uploadObject(report) {
353
356
  const errorInput = report?.error && typeof report.error === "object" ? report.error : {};
@@ -374,12 +377,31 @@ function endpoint() {
374
377
  return process.env.LEVIX_CRASH_REPORT_URL || DEFAULT_ENDPOINT;
375
378
  }
376
379
 
380
+ /** The debug tail, or "" when it cannot be read. Never fails a send. */
381
+ function safeDebugLog() {
382
+ try {
383
+ return readDebugTail();
384
+ } catch {
385
+ return "";
386
+ }
387
+ }
388
+
389
+ /**
390
+ * The upload object plus a debug log only when the caller already has the
391
+ * exact string. A missing string omits the key — send must not invent one.
392
+ */
393
+ function uploadWithDebugLog(report, debugLog) {
394
+ if (typeof debugLog !== "string") return uploadObject(report);
395
+ return { ...uploadObject(report), debugLog };
396
+ }
397
+
377
398
  /**
378
- * Forward one report. Never retried here; the caller decides. Resolves with
379
- * `{ ok: true }` or `{ ok: false, status, error }`.
399
+ * Forward one report. Never retried here; the caller decides. `debugLogId` is
400
+ * the snapshot `list()` returned. Missing or expired attaches no debug log.
401
+ * Resolves with `{ ok: true }` or `{ ok: false, status, error }`.
380
402
  */
381
- async function forwardReport(report) {
382
- const payload = uploadObject(report);
403
+ async function forwardReport(report, debugLogId) {
404
+ const payload = uploadWithDebugLog(report, readDebugSnapshot(debugLogId));
383
405
  const runtime = runtimeFacts();
384
406
  let response;
385
407
  let data = null;
@@ -414,11 +436,11 @@ async function forwardReport(report) {
414
436
  }
415
437
 
416
438
  /** Send one stored report. Success deletes it and records the send. */
417
- async function sendReport(id) {
439
+ async function sendReport(id, debugLogId) {
418
440
  const report = readReport(id);
419
441
  if (!report) return { ok: false, status: 404, error: "Crash report not found" };
420
442
 
421
- const result = await forwardReport(report);
443
+ const result = await forwardReport(report, debugLogId);
422
444
  if (result.ok) {
423
445
  deleteReport(report.id);
424
446
  recordSent({
@@ -440,8 +462,12 @@ async function sendReport(id) {
440
462
 
441
463
  /** What GET /crash-reports returns: previews plus the send history. */
442
464
  function list() {
465
+ // One frozen tail for every report in this response. Send redeems the id.
466
+ const debugLog = safeDebugLog();
467
+ const debugLogId = storeDebugSnapshot(debugLog);
443
468
  const reports = listReports().map((report) => ({
444
- ...uploadObject(report),
469
+ ...uploadWithDebugLog(report, debugLog),
470
+ debugLogId,
445
471
  status: report.status || "pending",
446
472
  lastError: report.lastError ?? null,
447
473
  }));