levix-bot 4.9.1 → 5.0.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 (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -0,0 +1,113 @@
1
+ // Untrusted page/media URLs must never fall through to a library's automatic
2
+ // redirects. Reuse the provider boundary for DNS validation and socket pinning.
3
+ const provider = require("./providerUrl.cjs");
4
+
5
+ function httpsUrl(raw, base) {
6
+ const url = new URL(raw, base);
7
+ if (url.protocol !== "https:") throw new Error("Remote URLs must use HTTPS");
8
+ url.hash = ""; // fragments are local to a document, not part of a request
9
+ provider.assertProviderBaseUrl(url.href, { allowLoopback: false, allowQuery: true });
10
+ return url;
11
+ }
12
+
13
+ async function cancelBody(response) {
14
+ try {
15
+ await response.body?.cancel();
16
+ } catch {
17
+ // Cleanup must not hide the original transport error.
18
+ }
19
+ }
20
+
21
+ // DNS lookup in the shared provider boundary is not itself abortable. Bound the
22
+ // whole wait, and release a response if it arrives after the caller timed out.
23
+ function beforeDeadline(request, signal) {
24
+ return new Promise((resolve, reject) => {
25
+ let aborted = signal.aborted;
26
+ const onAbort = () => {
27
+ aborted = true;
28
+ reject(signal.reason);
29
+ };
30
+ if (aborted) reject(signal.reason);
31
+ else signal.addEventListener("abort", onAbort, { once: true });
32
+ request.then(
33
+ (response) => {
34
+ signal.removeEventListener("abort", onAbort);
35
+ if (aborted) void cancelBody(response);
36
+ else resolve(response);
37
+ },
38
+ (error) => {
39
+ signal.removeEventListener("abort", onAbort);
40
+ reject(error);
41
+ },
42
+ );
43
+ });
44
+ }
45
+
46
+ async function readLimited(response, maxBytes) {
47
+ if (Number(response.headers.get("content-length")) > maxBytes) {
48
+ await cancelBody(response);
49
+ throw new Error("Remote response exceeds the size limit");
50
+ }
51
+ if (!response.body) return Buffer.alloc(0);
52
+ const reader = response.body.getReader();
53
+ const chunks = [];
54
+ let bytes = 0;
55
+ let complete = false;
56
+ try {
57
+ for (;;) {
58
+ const { value, done } = await reader.read();
59
+ if (done) {
60
+ complete = true;
61
+ return Buffer.concat(chunks, bytes);
62
+ }
63
+ bytes += value.byteLength;
64
+ if (bytes > maxBytes) throw new Error("Remote response exceeds the size limit");
65
+ chunks.push(Buffer.from(value));
66
+ }
67
+ } finally {
68
+ if (!complete) await reader.cancel().catch(() => {});
69
+ reader.releaseLock();
70
+ }
71
+ }
72
+
73
+ async function requestHttps(url, signal, dispatcher) {
74
+ const init = { signal, redirect: "manual", headers: { Accept: "*/*" } };
75
+ if (!dispatcher) return provider.safeProviderFetch(url.href, init, { allowLoopback: false });
76
+ // The dispatcher belongs to a live WhatsApp socket. Validate every hop, use
77
+ // that transport, and never close it or fall back to a direct connection.
78
+ await provider.assertProviderRequestUrl(url.href, { allowLoopback: false });
79
+ const { fetch } = require("undici");
80
+ return fetch(url.href, { ...init, dispatcher });
81
+ }
82
+
83
+ async function fetchHttpsBuffer(
84
+ raw,
85
+ { maxBytes = 20 * 1024 * 1024, timeoutMs = 20_000, dispatcher } = {},
86
+ ) {
87
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new Error("Invalid byte limit");
88
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new Error("Invalid timeout");
89
+ let url = httpsUrl(raw);
90
+ const signal = AbortSignal.timeout(timeoutMs);
91
+ for (let hop = 0; ; hop += 1) {
92
+ signal.throwIfAborted();
93
+ const response = await beforeDeadline(requestHttps(url, signal, dispatcher), signal);
94
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
95
+ await cancelBody(response);
96
+ const location = response.headers.get("location");
97
+ if (!location || hop >= 4) throw new Error("Remote redirect limit or missing location");
98
+ url = httpsUrl(location, url);
99
+ continue;
100
+ }
101
+ if (!response.ok) {
102
+ await cancelBody(response);
103
+ throw new Error(`Remote request failed (${response.status})`);
104
+ }
105
+ return {
106
+ buffer: await readLimited(response, maxBytes),
107
+ url: url.href,
108
+ contentType: response.headers.get("content-type") || "",
109
+ };
110
+ }
111
+ }
112
+
113
+ module.exports = { fetchHttpsBuffer, httpsUrl };
@@ -1,13 +1,13 @@
1
1
  // The language the bot answers in.
2
2
  //
3
- // Every reply is written in both languages where it is sent —
4
- // `tr("Done.", "تم.")` — and tr() picks one for the message being answered.
3
+ // New replies use keyed catalog messages through t(). Older replies use
4
+ // `tr("Done.", "تم.")`, which answers in English for pt-BR and es-419.
5
5
  // The choice is made once per incoming message, before any handler runs, and
6
6
  // AsyncLocalStorage carries it through everything that message causes: the
7
7
  // helpers deep inside a command, the status line it edits, a timer it starts.
8
8
  // Nothing has to pass a `lang` argument around.
9
9
  //
10
- // bot_language = ar | en that language, always
10
+ // bot_language = ar | en | pt-BR | es-419 that language, always
11
11
  // bot_language = auto the language the message is written in:
12
12
  // Arabic letters -> Arabic
13
13
  // English words, other than the command's own
@@ -22,8 +22,74 @@
22
22
 
23
23
  const { AsyncLocalStorage } = require("node:async_hooks");
24
24
  const settings = require("../config/settings.cjs");
25
+ const { escapeParam } = require("../messaging/escape.cjs");
26
+ const { validateOverride } = require("../extensions/templateKeys.cjs");
25
27
 
26
28
  const scope = new AsyncLocalStorage();
29
+ const FIXED_LANGUAGES = new Set(["ar", "en", "pt-BR", "es-419"]);
30
+
31
+ function normalizeLocale(value) {
32
+ if (typeof value !== "string") return null;
33
+ const language = value.trim().replaceAll("_", "-").split("-")[0].toLowerCase();
34
+ if (language === "ar") return "ar";
35
+ if (language === "pt") return "pt-BR";
36
+ if (language === "es") return "es-419";
37
+ if (language === "en") return "en";
38
+ return null;
39
+ }
40
+
41
+ let templateOverride = null;
42
+
43
+ function setTemplateOverride(fn) {
44
+ templateOverride = typeof fn === "function" ? fn : null;
45
+ }
46
+
47
+ function createTranslator(catalog, { getLocale, warn } = {}) {
48
+ const pluralRules = new Map();
49
+ const warned = new Set();
50
+ return (key, params = {}) => {
51
+ const locale = getLocale?.() || "en";
52
+ const messages = catalog.messages || {};
53
+ let value = messages[locale]?.[key] ?? messages.en?.[key];
54
+ let escapeParams = false;
55
+ if (
56
+ templateOverride &&
57
+ typeof key === "string" &&
58
+ key.startsWith("bot.") &&
59
+ typeof value === "string"
60
+ ) {
61
+ try {
62
+ const next = templateOverride(key, locale);
63
+ if (typeof next === "string" && validateOverride(key, next).ok) {
64
+ value = next;
65
+ escapeParams = true;
66
+ }
67
+ } catch {
68
+ // A hook that throws leaves the catalog text in place.
69
+ }
70
+ }
71
+ if (value === undefined) {
72
+ if (!warned.has(key)) {
73
+ warned.add(key);
74
+ warn?.(key);
75
+ }
76
+ return key;
77
+ }
78
+ if (value && typeof value === "object") {
79
+ let rules = pluralRules.get(locale);
80
+ if (!rules) {
81
+ rules = new Intl.PluralRules(locale);
82
+ pluralRules.set(locale, rules);
83
+ }
84
+ value = value[rules.select(Number(params.count))] ?? value.other;
85
+ }
86
+ return String(value).replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (token, name) => {
87
+ if (!Object.hasOwn(params, name)) return token;
88
+ const raw = String(params[name]);
89
+ return escapeParams ? escapeParam(raw) : raw;
90
+ });
91
+ };
92
+ }
27
93
 
28
94
  const ARABIC_LETTERS = /[\u0621-\u064A\u0671-\u06D3\u06FA-\u06FF]/;
29
95
  const LATIN_WORD = /[a-z][a-z'’-]*/gi;
@@ -37,7 +103,7 @@ const NOT_WORDS = /(?:https?:\/\/|www\.)\S+|\S+@\S+|@\S+/gi;
37
103
  /** The configured language, or null for "auto". */
38
104
  function configuredLang() {
39
105
  const setting = settings.get("bot_language");
40
- return setting === "ar" || setting === "en" ? setting : null;
106
+ return FIXED_LANGUAGES.has(setting) ? setting : null;
41
107
  }
42
108
 
43
109
  /**
@@ -97,7 +163,7 @@ function langForCommand(command, args = [], aliases = command?.aliases || []) {
97
163
 
98
164
  /** Run `fn` with replies in `lang`. Returns what `fn` returns. */
99
165
  function withLang(lang, fn) {
100
- return scope.run(lang === "en" ? "en" : "ar", fn);
166
+ return scope.run(FIXED_LANGUAGES.has(lang) ? lang : "ar", fn);
101
167
  }
102
168
 
103
169
  /** The language of the message being answered right now. */
@@ -105,9 +171,53 @@ function currentLang() {
105
171
  return scope.getStore() || configuredLang() || "ar";
106
172
  }
107
173
 
174
+ // ar and en keep the tags listschedules and warns already passed to Intl.
175
+ const INTL_TAGS = {
176
+ ar: "ar-EG",
177
+ en: "en-GB",
178
+ "pt-BR": "pt-BR",
179
+ "es-419": "es-419",
180
+ };
181
+
182
+ /**
183
+ * Intl locale for a reply language.
184
+ * With no argument, this follows the current reply language.
185
+ */
186
+ function intlTag(lang) {
187
+ let code;
188
+ if (lang === undefined) code = currentLang();
189
+ else if (FIXED_LANGUAGES.has(lang)) code = lang;
190
+ else code = normalizeLocale(lang) || "en";
191
+ return INTL_TAGS[code] || "en-GB";
192
+ }
193
+
108
194
  /** Pick the reply for the current message. */
109
195
  function tr(en, ar) {
110
- return currentLang() === "en" ? en : ar;
196
+ return currentLang() === "ar" ? ar : en;
111
197
  }
112
198
 
113
- module.exports = { detectLang, syntaxWords, langForCommand, withLang, currentLang, tr };
199
+ const t = createTranslator(require("../i18n/catalog.generated.cjs"), {
200
+ getLocale: currentLang,
201
+ warn: (key) => {
202
+ try {
203
+ require("./logger.cjs").warn({ key }, "Missing bot translation");
204
+ } catch {
205
+ // Translation lookup must still work during early startup.
206
+ }
207
+ },
208
+ });
209
+
210
+ module.exports = {
211
+ normalizeLocale,
212
+ createTranslator,
213
+ setTemplateOverride,
214
+ t,
215
+ configuredLang,
216
+ detectLang,
217
+ syntaxWords,
218
+ langForCommand,
219
+ withLang,
220
+ currentLang,
221
+ intlTag,
222
+ tr,
223
+ };
@@ -0,0 +1,90 @@
1
+ // Baileys rc14 fetches preview pages/images through separate, unrestricted
2
+ // clients. Override its getUrlInfo hook instead of merely checking the first URL.
3
+ const settings = require("../config/settings.cjs");
4
+ const { fetchHttpsBuffer, httpsUrl } = require("./httpsFetch.cjs");
5
+ const { decodeBuffer, decodeText } = require("./textDecode.cjs");
6
+ const { withMediaThumbnail } = require("./thumbnail.cjs");
7
+ const logger = require("./logger.cjs");
8
+
9
+ function pageMetadata(html) {
10
+ const meta = new Map();
11
+ // Only read metadata; never render HTML, run scripts, or follow refresh/base
12
+ // tags. Bound the input at the transport and each attribute at extraction.
13
+ const head = html
14
+ .slice(0, 128 * 1024)
15
+ .split(/<\/head\s*>/i, 1)[0]
16
+ .replace(/<!--[\s\S]*?-->/g, "");
17
+ // Bounded tag scans also bound work on malformed, attacker-controlled HTML.
18
+ for (const tag of head.match(/<meta\b[^>]{0,8192}>/gi) || []) {
19
+ const attrs = new Map();
20
+ for (const match of tag.matchAll(/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) {
21
+ attrs.set(
22
+ match[1].toLowerCase(),
23
+ decodeText((match[2] ?? match[3] ?? match[4]).slice(0, 4096)),
24
+ );
25
+ }
26
+ const key = (attrs.get("property") || attrs.get("name") || "").toLowerCase();
27
+ if (!meta.has(key)) meta.set(key, attrs.get("content") || "");
28
+ }
29
+ const titleStart = /<title\b[^>]{0,512}>/i.exec(head);
30
+ const titleText = titleStart
31
+ ? head
32
+ .slice(
33
+ titleStart.index + titleStart[0].length,
34
+ titleStart.index + titleStart[0].length + 4096,
35
+ )
36
+ .split(/<\/title\s*>/i, 1)[0]
37
+ : "";
38
+ const title = meta.get("og:title") || meta.get("twitter:title") || decodeText(titleText);
39
+ return {
40
+ title: title
41
+ .replace(/<[^>]*>/g, "")
42
+ .trim()
43
+ .slice(0, 512),
44
+ description: (meta.get("og:description") || meta.get("description") || "").slice(0, 2048),
45
+ image: meta.get("og:image:secure_url") || meta.get("og:image") || meta.get("twitter:image"),
46
+ };
47
+ }
48
+
49
+ async function getHttpsUrlInfo(text, { dispatcher } = {}) {
50
+ if (!settings.get("link_previews_enabled")) return undefined;
51
+ try {
52
+ const url = httpsUrl(/^[\w+.-]+:\/\//.test(text) ? text : `https://${text}`);
53
+ const page = await fetchHttpsBuffer(url.href, {
54
+ maxBytes: 1024 * 1024,
55
+ timeoutMs: 3000,
56
+ dispatcher,
57
+ });
58
+ if (!/^(text\/html|application\/xhtml\+xml)\b/i.test(page.contentType)) return undefined;
59
+ const metadata = pageMetadata(decodeBuffer(page.buffer, page.contentType));
60
+ if (!metadata.title) return undefined;
61
+ const info = {
62
+ "canonical-url": page.url,
63
+ "matched-text": text,
64
+ title: metadata.title,
65
+ description: metadata.description,
66
+ };
67
+ if (metadata.image) {
68
+ try {
69
+ const imageUrl = httpsUrl(metadata.image, page.url);
70
+ const image = await fetchHttpsBuffer(imageUrl.href, {
71
+ maxBytes: 2 * 1024 * 1024,
72
+ timeoutMs: 3000,
73
+ dispatcher,
74
+ });
75
+ if (/^image\//i.test(image.contentType)) {
76
+ const content = await withMediaThumbnail({ image: image.buffer });
77
+ info.jpegThumbnail = content.jpegThumbnail;
78
+ }
79
+ } catch {
80
+ // A refused or failed image must not discard safe page metadata.
81
+ }
82
+ }
83
+ return info;
84
+ } catch (err) {
85
+ logger.debug({ err: err?.message }, "[linkPreview] preview skipped");
86
+ return undefined; // Baileys sends the text without an unsafe fallback
87
+ }
88
+ }
89
+
90
+ module.exports = { getHttpsUrlInfo };
@@ -65,6 +65,12 @@ const logger = pino(
65
65
  ]),
66
66
  );
67
67
 
68
+ // Writes only to the sanitized debug log: never combined.log, error.log or the
69
+ // console. For detail that matters only when diagnosing (Baileys, Node's
70
+ // network layer), and that leaves the device only inside an operator-sent
71
+ // crash report or feedback with diagnostics ticked.
72
+ logger.debugOnly = pino(base, debugLog.stream);
73
+
68
74
  const MAX_READ_BYTES = 256 * 1024;
69
75
 
70
76
  /** Read only the bounded tail of the operational log, never arbitrary files. */
@@ -1,6 +1,6 @@
1
1
  // Markdown from any provider -> WhatsApp text. This is a display boundary:
2
2
  // stored AI history, code contents, identifiers and URLs remain untouched.
3
- const { tr } = require("./i18n.cjs");
3
+ const { t } = require("./i18n.cjs");
4
4
 
5
5
  /** Split table cells without splitting escaped pipes or pipes inside code. */
6
6
  function tableCells(line) {
@@ -57,10 +57,10 @@ function tableText({ headers, rows }) {
57
57
  }
58
58
  return rows
59
59
  .map((row, index) => {
60
- const title = row[0] || tr(`Item ${index + 1}`, `عنصر ${index + 1}`);
60
+ const title = row[0] || t("bot.core.markdownParser.item", { number: index + 1 });
61
61
  const fields = [];
62
62
  for (let c = 1; c < Math.max(headers.length, row.length); c++) {
63
- const header = headers[c] || tr(`Column ${c + 1}`, `عمود ${c + 1}`);
63
+ const header = headers[c] || t("bot.core.markdownParser.column", { number: c + 1 });
64
64
  const label = header.replace(/^\*([^*]+)\*$/, "$1");
65
65
  const value = (row[c] || "—").replace(/<br\s*\/?>/gi, "\n");
66
66
  fields.push(` • ${bold(`${label}:`)} ${value.replace(/\n/g, "\n ")}`);