levix-bot 4.5.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/app.cjs +32 -7
  2. package/package.json +2 -2
  3. package/public/dashboard/assets/index-RnT7DAde.js +540 -0
  4. package/public/dashboard/assets/index-UcqCdCvG.css +2 -0
  5. package/public/dashboard/index.html +4 -3
  6. package/public/dashboard.css +123 -53
  7. package/public/gateway-i18n.js +295 -0
  8. package/public/gateway.js +30 -1
  9. package/public/ui-boot.js +71 -0
  10. package/src/bootstrap/core.js +9 -0
  11. package/src/commands/autodelete.cjs +213 -0
  12. package/src/commands/pack.cjs +46 -25
  13. package/src/commands/packs.cjs +4 -1
  14. package/src/commands/shortlink.cjs +273 -66
  15. package/src/commands/stickers.cjs +26 -8
  16. package/src/config/defaults.cjs +1 -0
  17. package/src/config/settings.cjs +10 -0
  18. package/src/core/session.js +9 -1
  19. package/src/db/db.cjs +57 -0
  20. package/src/db/store.cjs +250 -0
  21. package/src/diagnostics/crashReports.cjs +491 -0
  22. package/src/diagnostics/device.cjs +119 -0
  23. package/src/diagnostics/sanitize.cjs +90 -0
  24. package/src/handlers/command.handler.js +1 -0
  25. package/src/handlers/message.handler.js +15 -0
  26. package/src/index.js +9 -1
  27. package/src/panel/feedback.cjs +13 -1
  28. package/src/routes/dashboard.api.esm.js +188 -4
  29. package/src/services/autoDelete.cjs +578 -0
  30. package/src/stickers/errors.cjs +7 -6
  31. package/src/stickers/library.cjs +118 -13
  32. package/src/utils/bidi.cjs +21 -0
  33. package/src/utils/storage.cjs +14 -0
  34. package/src/utils/storage.esm.js +15 -0
  35. package/views/dashboard.ejs +2 -1
  36. package/views/login.ejs +102 -71
  37. package/views/qr.ejs +59 -30
  38. package/views/setup.ejs +34 -30
  39. package/public/dashboard/assets/index-COI8zgqa.css +0 -2
  40. package/public/dashboard/assets/index-IZMBuNAZ.js +0 -505
@@ -3,6 +3,7 @@ import { handleAntiSpam } from "../middleware/antispam.middleware.js";
3
3
  import { checkBlacklist } from "../middleware/blacklist.middleware.js";
4
4
  import { trackForwardedMessage } from "../middleware/forward-tracking.middleware.js";
5
5
  import normalizeJid from "../utils/normalizeJid.esm.js";
6
+ import { getSenderCandidates, isBotAdminInGroup, sameUser } from "../utils/permissions.esm.js";
6
7
  import { rememberMessage } from "../utils/recentMessageCache.esm.js";
7
8
  import { saveUserMetadata, updateUserLastSeen } from "../utils/storage.esm.js";
8
9
  import { handleCommand } from "./command.handler.js";
@@ -11,6 +12,7 @@ const require = createRequire(import.meta.url);
11
12
  const logger = require("../utils/logger.cjs");
12
13
  const { visibleText } = require("../utils/messageContent.cjs");
13
14
  const { detectLang, withLang } = require("../utils/i18n.cjs");
15
+ const autoDelete = require("../services/autoDelete.cjs");
14
16
 
15
17
  // Envelopes that carry no user-visible content: message revokes and edits
16
18
  // (protocolMessage), reactions, poll votes, the undecrypted edit envelope, and
@@ -78,6 +80,19 @@ export async function handleIncomingMessage(sock, m) {
78
80
  // to the command handler and the user sees nothing happen.
79
81
  const body = visibleText(msg.message);
80
82
 
83
+ // Keyword auto-delete: after content/status skip, before blacklist/commands
84
+ // /moderation. A successful delete stops the rest of the pipeline.
85
+ try {
86
+ const deleted = await autoDelete.handleIncoming(sock, msg, body, {
87
+ sameUser,
88
+ getSenderCandidates,
89
+ isBotAdminInGroup,
90
+ });
91
+ if (deleted) return;
92
+ } catch (error) {
93
+ logger.error({ err: error }, "auto-delete hook failed");
94
+ }
95
+
81
96
  // Everything the bot says about this message — a moderation warning, a
82
97
  // command's reply — goes out in one language (see utils/i18n.cjs). A
83
98
  // command narrows this down to its own arguments.
package/src/index.js CHANGED
@@ -265,12 +265,20 @@ async function startWithPanel({ open }) {
265
265
  // living and dying
266
266
  // ---------------------------------------------------------------------------
267
267
 
268
- function installShutdownHandlers() {
268
+ export function installShutdownHandlers() {
269
269
  // After an uncaughtException the process state is unknown (a half-held lock,
270
270
  // a half-written auth row). Log and exit rather than keep working on top of
271
271
  // it. Run the bot under a supervisor (systemd / pm2 / docker restart) so it
272
272
  // comes back on its own — without one, this exit means the bot is down.
273
273
  const fatal = (error, label) => {
274
+ // One last local crash report, written synchronously before we die. It is
275
+ // never sent from here — the operator sends it from the panel later. The
276
+ // write is wrapped again here so a store failure cannot turn one fatal
277
+ // error into two.
278
+ try {
279
+ const category = label.startsWith("Unhandled Rejection") ? "node-rejection" : "node-uncaught";
280
+ require("./diagnostics/crashReports.cjs").captureNodeFatal(category, error);
281
+ } catch {}
274
282
  logger.error(error, `${label} exiting — restart is up to the supervisor`);
275
283
  console.error(label, error);
276
284
  // Half a second so pino can drain its worker before we die.
@@ -20,6 +20,7 @@
20
20
  const fs = require("node:fs");
21
21
  const logger = require("../utils/logger.cjs");
22
22
  const settings = require("../config/settings.cjs");
23
+ const { buildDiagnostics } = require("../diagnostics/device.cjs");
23
24
 
24
25
  const DEFAULT_ENDPOINT = "https://levix.leviro.net/api/feedback";
25
26
 
@@ -158,11 +159,18 @@ function safeRemoteError(value) {
158
159
  * "payload" part and the file as "file", and the endpoint delivers it to
159
160
  * Telegram as a document instead of a message.
160
161
  *
162
+ * `diagnosticsClient` is the raw section 1 client object, present only when the
163
+ * operator ticked the diagnostics box. When present the server rebuilds it with
164
+ * the same builder the preview route uses (so preview and send cannot diverge)
165
+ * and adds it to the envelope as `diagnostics`. When it is undefined the
166
+ * envelope has no `diagnostics` key at all.
167
+ *
161
168
  * @param {{ message: string, topic: string, rating: number|null, contact: string|null }} feedback
162
169
  * @param {{ buffer: Buffer, name: string, type: string, size: number } | null} attachment
170
+ * @param {object} [diagnosticsClient]
163
171
  * @returns {Promise<{ ok: true } | { ok: false, status: number, error: string }>}
164
172
  */
165
- async function submitFeedback(feedback, attachment = null) {
173
+ async function submitFeedback(feedback, attachment = null, diagnosticsClient = undefined) {
166
174
  const endpoint = process.env.LEVIX_FEEDBACK_URL || DEFAULT_ENDPOINT;
167
175
  const runtime = describeRuntime();
168
176
 
@@ -174,6 +182,10 @@ async function submitFeedback(feedback, attachment = null) {
174
182
  app: { version: runtime.version, platform: runtime.platform, locale: runtime.locale },
175
183
  };
176
184
 
185
+ if (diagnosticsClient !== undefined && diagnosticsClient !== null) {
186
+ envelope.diagnostics = buildDiagnostics(diagnosticsClient);
187
+ }
188
+
177
189
  let response;
178
190
  let data = null;
179
191
  try {
@@ -18,6 +18,8 @@ import { Router } from "express";
18
18
  import { createRequire } from "module";
19
19
  import { groupMetadataCache } from "../core/socket.js";
20
20
  import { getCommandCatalog, rebuildCommandIndex } from "../handlers/command.handler.js";
21
+ import { fileToBuffer, MultipartError, readMultipartForm } from "../utils/multipart.esm.js";
22
+ import normalizeJid, { isLidJid } from "../utils/normalizeJid.esm.js";
21
23
  import { grantRole, listRoles, revokeRole } from "../utils/permissions.esm.js";
22
24
  import {
23
25
  countDebts,
@@ -41,8 +43,6 @@ import {
41
43
  resolveUserPhone,
42
44
  saveGroupSettings,
43
45
  } from "../utils/storage.esm.js";
44
- import normalizeJid, { isLidJid } from "../utils/normalizeJid.esm.js";
45
- import { fileToBuffer, MultipartError, readMultipartForm } from "../utils/multipart.esm.js";
46
46
 
47
47
  const require = createRequire(import.meta.url);
48
48
  const logger = require("../utils/logger.cjs");
@@ -64,6 +64,8 @@ const {
64
64
  } = require("../panel/feedback.cjs");
65
65
  const { stampPanelSession } = require("../panel/session-auth.cjs");
66
66
  const { DATA_DIR } = require("../config/paths.cjs");
67
+ const { buildDiagnostics } = require("../diagnostics/device.cjs");
68
+ const crashReports = require("../diagnostics/crashReports.cjs");
67
69
  const { PERSONA_FILE, activeProviderKeySetting } = require("../services/aiAgent.cjs");
68
70
  const {
69
71
  SCHEDULE_MEDIA_MAX_BYTES,
@@ -80,6 +82,7 @@ const {
80
82
  } = require("../utils/recurrence.cjs");
81
83
  const { discoverProviderModels, DiscoveryError } = require("../services/llmDiscovery.cjs");
82
84
  const settingsTransfer = require("../services/settingsTransfer.cjs");
85
+ const autoDelete = require("../services/autoDelete.cjs");
83
86
  const cron = require("node-cron");
84
87
 
85
88
  const router = Router();
@@ -151,6 +154,28 @@ function asyncRoute(handler) {
151
154
  };
152
155
  }
153
156
 
157
+ /**
158
+ * The feedback `diagnostics` field arrives as a JSON object (JSON body) or as a
159
+ * JSON string (a multipart field). Both are normalized here; a present but
160
+ * broken value is a caller mistake, not something to silently drop.
161
+ *
162
+ * @returns {{ present: boolean, value: object|null, error?: string }}
163
+ */
164
+ function parseDiagnosticsInput(raw) {
165
+ if (raw === undefined || raw === null) return { present: false, value: null };
166
+ if (typeof raw === "string") {
167
+ const text = raw.trim();
168
+ if (!text) return { present: false, value: null };
169
+ try {
170
+ return { present: true, value: JSON.parse(text) };
171
+ } catch {
172
+ return { present: false, value: null, error: "diagnostics is not valid JSON" };
173
+ }
174
+ }
175
+ if (typeof raw === "object" && !Array.isArray(raw)) return { present: true, value: raw };
176
+ return { present: false, value: null, error: "diagnostics must be an object" };
177
+ }
178
+
154
179
  // ===========================================================================
155
180
  // Overview
156
181
  // ===========================================================================
@@ -1308,10 +1333,22 @@ router.get("/feedback/meta", (req, res) => {
1308
1333
  });
1309
1334
  });
1310
1335
 
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.
1339
+ router.post("/feedback/diagnostics-preview", (req, res) => {
1340
+ const parsed = parseDiagnosticsInput(req.body?.client);
1341
+ if (parsed.error) return badRequest(res, parsed.error);
1342
+ res.json({ success: true, diagnostics: buildDiagnostics(parsed.present ? parsed.value : {}) });
1343
+ });
1344
+
1311
1345
  // Leaves this machine only when the operator presses Send, and carries nothing
1312
1346
  // but the form's own fields plus the version and platform — see feedback.cjs.
1313
1347
  // An optional attachment (a screenshot, a log) rides along as multipart and is
1314
- // forwarded to the same endpoint, which delivers it to Telegram as a file.
1348
+ // forwarded to the same endpoint, which delivers it to Telegram as a file. An
1349
+ // optional `diagnostics` object (the preview's client object) is rebuilt by the
1350
+ // same sanitizer and attached to the envelope; without it there is no
1351
+ // `diagnostics` key on the wire.
1315
1352
  router.post(
1316
1353
  "/feedback",
1317
1354
  asyncRoute(async (req, res) => {
@@ -1342,6 +1379,9 @@ router.post(
1342
1379
  const parsed = validateFeedback(body);
1343
1380
  if (!parsed.ok) return badRequest(res, parsed.error);
1344
1381
 
1382
+ const diagnostics = parseDiagnosticsInput(body.diagnostics);
1383
+ if (diagnostics.error) return badRequest(res, diagnostics.error);
1384
+
1345
1385
  const retryAfter = feedbackRetryAfter();
1346
1386
  if (retryAfter) {
1347
1387
  res.set("Retry-After", String(retryAfter));
@@ -1351,7 +1391,11 @@ router.post(
1351
1391
  });
1352
1392
  }
1353
1393
 
1354
- const result = await submitFeedback(parsed.value, attachment);
1394
+ const result = await submitFeedback(
1395
+ parsed.value,
1396
+ attachment,
1397
+ diagnostics.present ? diagnostics.value : undefined,
1398
+ );
1355
1399
  if (!result.ok) {
1356
1400
  return res.status(result.status).json({ success: false, error: result.error });
1357
1401
  }
@@ -1542,4 +1586,144 @@ router.post("/session/restart", (req, res, next) => {
1542
1586
  router.handle(req, res, next);
1543
1587
  });
1544
1588
 
1589
+ // ===========================================================================
1590
+ // Keyword auto-delete
1591
+ // ===========================================================================
1592
+
1593
+ function autoDeleteFail(res, error, label) {
1594
+ if (error?.status === 400 || error?.status === 404 || error?.name === "AutoDeleteError") {
1595
+ return res.status(error.status || 400).json({ success: false, error: error.message });
1596
+ }
1597
+ return fail(res, error, label);
1598
+ }
1599
+
1600
+ router.get("/auto-delete/rules", (_req, res) => {
1601
+ try {
1602
+ res.json({ success: true, rules: autoDelete.listRules() });
1603
+ } catch (error) {
1604
+ autoDeleteFail(res, error, "Error listing auto-delete rules");
1605
+ }
1606
+ });
1607
+
1608
+ router.post("/auto-delete/rules", (req, res) => {
1609
+ try {
1610
+ const rule = autoDelete.createRule(req.body || {});
1611
+ res.json({ success: true, rule });
1612
+ } catch (error) {
1613
+ autoDeleteFail(res, error, "Error creating an auto-delete rule");
1614
+ }
1615
+ });
1616
+
1617
+ router.patch("/auto-delete/rules/:id", (req, res) => {
1618
+ try {
1619
+ const rule = autoDelete.updateRule(req.params.id, req.body || {});
1620
+ res.json({ success: true, rule });
1621
+ } catch (error) {
1622
+ autoDeleteFail(res, error, "Error updating an auto-delete rule");
1623
+ }
1624
+ });
1625
+
1626
+ router.delete("/auto-delete/rules/:id", (req, res) => {
1627
+ try {
1628
+ autoDelete.deleteRule(req.params.id);
1629
+ res.json({ success: true });
1630
+ } catch (error) {
1631
+ autoDeleteFail(res, error, "Error deleting an auto-delete rule");
1632
+ }
1633
+ });
1634
+
1635
+ router.post("/auto-delete/rules/:id/reset", (req, res) => {
1636
+ try {
1637
+ const rule = autoDelete.resetCounter(req.params.id);
1638
+ res.json({ success: true, rule });
1639
+ } catch (error) {
1640
+ autoDeleteFail(res, error, "Error resetting an auto-delete counter");
1641
+ }
1642
+ });
1643
+
1644
+ router.get("/auto-delete/log", (req, res) => {
1645
+ try {
1646
+ const { log, total } = autoDelete.listLog({
1647
+ ruleId: req.query.ruleId,
1648
+ limit: req.query.limit,
1649
+ offset: req.query.offset,
1650
+ });
1651
+ res.json({ success: true, log, total });
1652
+ } catch (error) {
1653
+ autoDeleteFail(res, error, "Error listing auto-delete copies");
1654
+ }
1655
+ });
1656
+
1657
+ router.delete("/auto-delete/log", (req, res) => {
1658
+ try {
1659
+ const cleared = autoDelete.clearLog(req.query.ruleId);
1660
+ res.json({ success: true, cleared });
1661
+ } catch (error) {
1662
+ autoDeleteFail(res, error, "Error clearing auto-delete copies");
1663
+ }
1664
+ });
1665
+
1666
+ // ===========================================================================
1667
+ // Crash reports — local, and sent only when the operator presses Send
1668
+ // ===========================================================================
1669
+
1670
+ // Every pending report, as the exact upload object (plus the local status), and
1671
+ // the last 20 ids that went out. Listing sweeps expired reports first.
1672
+ router.get("/crash-reports", (_req, res) => {
1673
+ try {
1674
+ const { reports, sent } = crashReports.list();
1675
+ res.json({ success: true, reports, sent });
1676
+ } catch (error) {
1677
+ fail(res, error, "Error listing crash reports");
1678
+ }
1679
+ });
1680
+
1681
+ // The panel's own error hooks post here. Rate-limited because a render loop can
1682
+ // fire many times a second; the report itself is stored, nothing is sent.
1683
+ router.post("/crash-reports", (req, res) => {
1684
+ const retryAfter = crashReports.crashReportRetryAfter();
1685
+ if (retryAfter) {
1686
+ res.set("Retry-After", String(retryAfter));
1687
+ return res.status(429).json({
1688
+ success: false,
1689
+ error: "Too many crash reports for now. Try again in a little while.",
1690
+ });
1691
+ }
1692
+ crashReports.recordCrashReportAttempt();
1693
+ try {
1694
+ const report = crashReports.createReport(req.body || {});
1695
+ res.json({ success: true, id: report.id });
1696
+ } catch (error) {
1697
+ if (error?.status === 400) return badRequest(res, error.message);
1698
+ fail(res, error, "Error storing a crash report");
1699
+ }
1700
+ });
1701
+
1702
+ // One report out, by an explicit operator action. It never retries by itself.
1703
+ router.post(
1704
+ "/crash-reports/:id/send",
1705
+ asyncRoute(async (req, res) => {
1706
+ const result = await crashReports.sendReport(req.params.id);
1707
+ if (!result.ok) {
1708
+ return res.status(result.status || 502).json({ success: false, error: result.error });
1709
+ }
1710
+ res.json({ success: true });
1711
+ }),
1712
+ );
1713
+
1714
+ router.delete("/crash-reports/:id", (req, res) => {
1715
+ if (!crashReports.deleteReport(req.params.id)) {
1716
+ return res.status(404).json({ success: false, error: "Crash report not found" });
1717
+ }
1718
+ res.json({ success: true });
1719
+ });
1720
+
1721
+ router.delete("/crash-reports", (_req, res) => {
1722
+ try {
1723
+ res.json({ success: true, removed: crashReports.deleteAllReports() });
1724
+ } catch (error) {
1725
+ fail(res, error, "Error deleting crash reports");
1726
+ }
1727
+ });
1728
+
1545
1729
  export default router;