levix-bot 4.9.2 → 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 (242) 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 +46 -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 +1 -1
  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 +182 -10
  138. package/src/core/connection.js +37 -8
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +525 -82
  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/debugLog.cjs +16 -4
  147. package/src/diagnostics/device.cjs +4 -2
  148. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  149. package/src/domain/command.js +24 -22
  150. package/src/extensions/autoReply.cjs +521 -0
  151. package/src/extensions/context.cjs +73 -0
  152. package/src/extensions/contract.cjs +69 -0
  153. package/src/extensions/entitlement/client.cjs +381 -0
  154. package/src/extensions/entitlement/index.cjs +629 -0
  155. package/src/extensions/entitlement/installation.cjs +117 -0
  156. package/src/extensions/entitlement/keys.cjs +72 -0
  157. package/src/extensions/entitlement/state.cjs +201 -0
  158. package/src/extensions/entitlement/target.cjs +7 -0
  159. package/src/extensions/entitlement/token.cjs +225 -0
  160. package/src/extensions/host.cjs +519 -0
  161. package/src/extensions/templateKeys.cjs +81 -0
  162. package/src/handlers/command.handler.js +191 -64
  163. package/src/handlers/group.handler.js +78 -18
  164. package/src/handlers/message.handler.js +56 -25
  165. package/src/i18n/catalog.generated.cjs +3537 -0
  166. package/src/index.js +51 -12
  167. package/src/legal/bundled/ar.json +102 -0
  168. package/src/legal/bundled/en.json +102 -0
  169. package/src/legal/bundled/es-419.json +102 -0
  170. package/src/legal/bundled/pt-BR.json +102 -0
  171. package/src/legal/cli.cjs +200 -0
  172. package/src/legal/consent.cjs +187 -0
  173. package/src/legal/document.cjs +156 -0
  174. package/src/legal/keys.cjs +100 -0
  175. package/src/legal/release.cjs +226 -0
  176. package/src/legal/remote.cjs +419 -0
  177. package/src/legal/terms.cjs +142 -0
  178. package/src/messaging/escape.cjs +31 -0
  179. package/src/messaging/health.cjs +65 -0
  180. package/src/messaging/identity.cjs +42 -0
  181. package/src/messaging/message.cjs +136 -0
  182. package/src/messaging/parser.cjs +88 -0
  183. package/src/messaging/router.cjs +217 -0
  184. package/src/middleware/permissions.middleware.js +34 -2
  185. package/src/panel/account-profile.cjs +489 -0
  186. package/src/panel/fallback-page.cjs +177 -0
  187. package/src/panel/password-reset.cjs +13 -14
  188. package/src/panel/recovery-email.cjs +3 -1
  189. package/src/routes/backup.api.esm.js +175 -0
  190. package/src/routes/dashboard.api.esm.js +183 -7
  191. package/src/routes/plus.api.esm.js +172 -0
  192. package/src/routes/reactions.api.esm.js +60 -0
  193. package/src/services/aiAgent.cjs +56 -43
  194. package/src/services/aiDocs.cjs +187 -0
  195. package/src/services/aiImage.cjs +183 -0
  196. package/src/services/aiMedia.cjs +146 -0
  197. package/src/services/aiProviders.cjs +76 -80
  198. package/src/services/aiRouter.cjs +2 -2
  199. package/src/services/aiToolAuth.cjs +76 -4
  200. package/src/services/aiTools.cjs +431 -105
  201. package/src/services/autoDelete.cjs +9 -1
  202. package/src/services/levix-docs.generated.json +2623 -0
  203. package/src/services/memoryPolicy.cjs +56 -0
  204. package/src/services/updateCheck.cjs +362 -0
  205. package/src/stickers/errors.cjs +53 -97
  206. package/src/stickers/library.cjs +13 -6
  207. package/src/stickers/owner.cjs +1 -1
  208. package/src/utils/commandContext.cjs +13 -0
  209. package/src/utils/commandDocs.cjs +42 -20
  210. package/src/utils/geminiHttpOptions.cjs +56 -0
  211. package/src/utils/geminiMedia.cjs +28 -3
  212. package/src/utils/groupMetadataCache.cjs +386 -21
  213. package/src/utils/httpsFetch.cjs +113 -0
  214. package/src/utils/i18n.cjs +117 -7
  215. package/src/utils/linkPreview.cjs +90 -0
  216. package/src/utils/markdownParser.cjs +3 -3
  217. package/src/utils/memory.cjs +375 -28
  218. package/src/utils/messageContent.cjs +7 -1
  219. package/src/utils/moderationAction.cjs +116 -73
  220. package/src/utils/moderationSummary.cjs +32 -56
  221. package/src/utils/permissionLevel.cjs +7 -28
  222. package/src/utils/permissions.cjs +23 -14
  223. package/src/utils/permissions.esm.js +99 -166
  224. package/src/utils/recentMessageCache.esm.js +241 -37
  225. package/src/utils/recurrence.cjs +78 -66
  226. package/src/utils/sendBotMessage.cjs +14 -29
  227. package/src/utils/sendBotMessage.esm.js +28 -13
  228. package/src/utils/statusMessage.cjs +94 -33
  229. package/src/utils/stickerBot.cjs +18 -16
  230. package/src/utils/storage.cjs +2 -0
  231. package/src/utils/storage.esm.js +2 -0
  232. package/src/utils/thumbnail.cjs +5 -21
  233. package/public/dashboard/assets/index-4xhK_Tpl.js +0 -561
  234. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  235. package/public/dashboard.css +0 -3127
  236. package/public/dashboard.js +0 -1981
  237. package/public/gateway-i18n.js +0 -321
  238. package/public/gateway.js +0 -70
  239. package/views/dashboard.ejs +0 -775
  240. package/views/login.ejs +0 -408
  241. package/views/qr.ejs +0 -155
  242. package/views/setup.ejs +0 -118
@@ -0,0 +1,142 @@
1
+ // The current Terms and Privacy release.
2
+ //
3
+ // The bundled release ships inside the app package and is pinned by a test
4
+ // (ADR-019). A verified remote release replaces it only when its version is
5
+ // strictly newer. Equal versions keep the bundle. A broken bundle still fails
6
+ // closed. A cache that cannot be read or verified falls back to the bundle.
7
+ //
8
+ // Validation is lazy and the result is memoized, so a broken bundle never
9
+ // crashes a boot: consent fails closed instead (src/legal/consent.cjs).
10
+
11
+ const brand = require("../config/brand.cjs");
12
+ const {
13
+ LOCALES,
14
+ LegalDocumentError,
15
+ compareVersions,
16
+ documentHash,
17
+ validateDocument,
18
+ } = require("./document.cjs");
19
+
20
+ // Every bundled locale. One `require` per file so the single-executable build
21
+ // bundles them (scripts/build-sea.mjs cannot read a directory at run time).
22
+ const BUNDLED = Object.freeze({
23
+ ar: () => require("./bundled/ar.json"),
24
+ en: () => require("./bundled/en.json"),
25
+ "pt-BR": () => require("./bundled/pt-BR.json"),
26
+ "es-419": () => require("./bundled/es-419.json"),
27
+ });
28
+
29
+ const DEFAULT_LOCALE = "en";
30
+
31
+ // Links shown beside the documents. They come from code, never from a
32
+ // document, so a document cannot send anybody anywhere.
33
+ const LINKS = Object.freeze({
34
+ privacyPolicy: `${brand.repo}/blob/main/PRIVACY.md`,
35
+ license: `${brand.repo}/blob/main/LICENSE`,
36
+ website: "https://levix.leviro.net",
37
+ });
38
+
39
+ let memo = null;
40
+
41
+ function loadBundled() {
42
+ const documents = {};
43
+ let version = null;
44
+ for (const [locale, load] of Object.entries(BUNDLED)) {
45
+ // A deep copy: the validated object is frozen, and require's cache keeps
46
+ // the original untouched for anything else that reads it.
47
+ const document = validateDocument(JSON.parse(JSON.stringify(load())));
48
+ if (document.locale !== locale) {
49
+ throw new LegalDocumentError(`bundled ${locale} declares ${document.locale}`);
50
+ }
51
+ if (version !== null && document.version !== version) {
52
+ throw new LegalDocumentError("bundled documents have different versions");
53
+ }
54
+ version = document.version;
55
+ documents[locale] = Object.freeze({ document, sha256: documentHash(document) });
56
+ }
57
+ if (!documents[DEFAULT_LOCALE]) {
58
+ throw new LegalDocumentError("the bundled release has no English document");
59
+ }
60
+ return Object.freeze({ version, source: "bundled", documents: Object.freeze(documents) });
61
+ }
62
+
63
+ // Remote is loaded lazily so requiring this file does not open the cache, and
64
+ // so remote.cjs can call back into invalidate() without a load cycle.
65
+ function chooseRelease(bundled) {
66
+ let remote = null;
67
+ try {
68
+ remote = require("./remote.cjs").readCachedRelease();
69
+ } catch {
70
+ return bundled;
71
+ }
72
+ if (!remote) return bundled;
73
+ try {
74
+ if (compareVersions(remote.version, bundled.version) > 0) return remote;
75
+ } catch {
76
+ return bundled;
77
+ }
78
+ return bundled;
79
+ }
80
+
81
+ /** The bundled release, ignoring the cache. Throws LegalDocumentError when it is not usable. */
82
+ function bundledRelease() {
83
+ return loadBundled();
84
+ }
85
+
86
+ /** Drop the memo so the next currentRelease() re-reads the bundle and the cache. */
87
+ function invalidate() {
88
+ memo = null;
89
+ }
90
+
91
+ /** The current release. Throws LegalDocumentError when the bundle is not usable. */
92
+ function currentRelease() {
93
+ if (!memo) {
94
+ try {
95
+ memo = { release: chooseRelease(loadBundled()) };
96
+ } catch (error) {
97
+ memo = { error };
98
+ }
99
+ }
100
+ if (memo.error) throw memo.error;
101
+ return memo.release;
102
+ }
103
+
104
+ function availableLocales() {
105
+ return Object.keys(currentRelease().documents);
106
+ }
107
+
108
+ /** The locale itself when the release has it, otherwise English. */
109
+ function resolveLocale(locale) {
110
+ const release = currentRelease();
111
+ if (typeof locale === "string" && Object.hasOwn(release.documents, locale)) return locale;
112
+ return DEFAULT_LOCALE;
113
+ }
114
+
115
+ /**
116
+ * The document for one locale: `{ version, locale, sha256, document, source }`,
117
+ * or null when the release has no document in that locale.
118
+ */
119
+ function documentFor(locale) {
120
+ const release = currentRelease();
121
+ if (typeof locale !== "string" || !Object.hasOwn(release.documents, locale)) return null;
122
+ const entry = release.documents[locale];
123
+ return {
124
+ version: release.version,
125
+ locale,
126
+ sha256: entry.sha256,
127
+ document: entry.document,
128
+ source: release.source,
129
+ };
130
+ }
131
+
132
+ module.exports = {
133
+ DEFAULT_LOCALE,
134
+ LINKS,
135
+ LOCALES,
136
+ bundledRelease,
137
+ invalidate,
138
+ currentRelease,
139
+ availableLocales,
140
+ resolveLocale,
141
+ documentFor,
142
+ };
@@ -0,0 +1,31 @@
1
+ // Strip control and bidi-override characters, and neutralize braces so a
2
+ // parameter cannot invent a catalog placeholder. Used by renderMessage and
3
+ // by the Plus template-override path.
4
+
5
+ function escapeParam(value) {
6
+ let out = "";
7
+ for (const char of String(value ?? "")) {
8
+ const code = char.codePointAt(0);
9
+ const keep = code === 0x09 || code === 0x0a || code === 0x0d;
10
+ const control = code <= 0x1f || code === 0x7f;
11
+ const bidi = (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069);
12
+ if (!keep && (control || bidi)) continue;
13
+ if (char === "{") out += "{";
14
+ else if (char === "}") out += "}";
15
+ else out += char;
16
+ }
17
+ return out;
18
+ }
19
+
20
+ function hasForbiddenChars(text) {
21
+ for (const char of String(text ?? "")) {
22
+ const code = char.codePointAt(0);
23
+ const keep = code === 0x09 || code === 0x0a || code === 0x0d;
24
+ const control = code <= 0x1f || code === 0x7f;
25
+ const bidi = (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069);
26
+ if (!keep && (control || bidi)) return true;
27
+ }
28
+ return false;
29
+ }
30
+
31
+ module.exports = { escapeParam, hasForbiddenChars };
@@ -0,0 +1,65 @@
1
+ // Health report. Pure: the caller gathers probes. This module does not open
2
+ // a socket, a file, or a URL, so a check cannot create the load it measures.
3
+
4
+ const CHECKS = Object.freeze([
5
+ "node",
6
+ "whatsapp",
7
+ "database",
8
+ "scheduler",
9
+ "disk",
10
+ "memory",
11
+ "recovery",
12
+ "media",
13
+ ]);
14
+
15
+ const STATES = new Set(["ok", "degraded", "down", "unknown"]);
16
+
17
+ function stateOf(value) {
18
+ return STATES.has(value) ? value : "unknown";
19
+ }
20
+
21
+ function overallOf(checks) {
22
+ if (checks.some((check) => check.state === "down")) return "down";
23
+ if (checks.some((check) => check.state === "degraded")) return "degraded";
24
+ if (checks.some((check) => check.state === "unknown")) return "unknown";
25
+ return "ok";
26
+ }
27
+
28
+ function line(id, probe) {
29
+ const source = probe && typeof probe === "object" ? probe : {};
30
+ const detail = typeof source.detail === "string" && source.detail ? source.detail : null;
31
+ return {
32
+ id,
33
+ state: stateOf(source.state),
34
+ detail: detail && detail.length <= 80 ? detail : null,
35
+ };
36
+ }
37
+
38
+ /**
39
+ * @param {object} probes one entry per check. Missing entries are `unknown`.
40
+ * @returns {{overall: string, checks: Array<{id: string, state: string, detail: string|null}>}}
41
+ */
42
+ function assessHealth(probes = {}) {
43
+ const checks = CHECKS.map((id) => line(id, probes[id]));
44
+ return { overall: overallOf(checks), checks };
45
+ }
46
+
47
+ function whatsAppProbe(sessionState) {
48
+ if (!sessionState || typeof sessionState !== "object") return { state: "unknown" };
49
+ if (sessionState.connected === true && sessionState.state === "connected") return { state: "ok" };
50
+ if (sessionState.connected === true) return { state: "degraded" };
51
+ const waiting = new Set([
52
+ "idle",
53
+ "starting",
54
+ "waiting_for_qr",
55
+ "linking",
56
+ "reconnecting",
57
+ "consent_required",
58
+ "paused",
59
+ ]);
60
+ if (waiting.has(sessionState.state)) return { state: "degraded" };
61
+ if (sessionState.state) return { state: "down" };
62
+ return { state: "unknown" };
63
+ }
64
+
65
+ module.exports = { CHECKS, assessHealth, whatsAppProbe, overallOf };
@@ -0,0 +1,42 @@
1
+ // Who the linked WhatsApp account is, for routing only.
2
+ //
3
+ // A phone number typed into a setting is not this. The only ids accepted are
4
+ // `creds.me.id` and `creds.me.lid` from the paired session. No creds means
5
+ // there is no owner-private destination, and the router fails closed.
6
+
7
+ const normalizeJid = require("../utils/normalizeJid.cjs");
8
+
9
+ function readCreds() {
10
+ try {
11
+ const storage = require("../db/store.cjs");
12
+ if (!storage.isPairedSession()) return null;
13
+ const creds = JSON.parse(storage.authRead("creds") || "");
14
+ return creds && typeof creds === "object" ? creds : null;
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+
20
+ function asUserJid(value, suffix) {
21
+ const norm = value ? normalizeJid(value) : null;
22
+ if (!norm?.endsWith(suffix)) return null;
23
+ return norm;
24
+ }
25
+
26
+ function linkedIdentity() {
27
+ const me = readCreds()?.me || {};
28
+ const phone = asUserJid(me.id, "@s.whatsapp.net");
29
+ const lid = asUserJid(me.lid, "@lid");
30
+ return {
31
+ phone,
32
+ lid,
33
+ selfJids: [phone, lid].filter(Boolean),
34
+ };
35
+ }
36
+
37
+ function isLinkedSelf(jid, identity = linkedIdentity()) {
38
+ const norm = jid ? normalizeJid(jid) : null;
39
+ return Boolean(norm) && identity.selfJids.includes(norm);
40
+ }
41
+
42
+ module.exports = { linkedIdentity, isLinkedSelf, readCreds };
@@ -0,0 +1,136 @@
1
+ // The one message envelope. Routes, the panel and a future Plus pack address
2
+ // a reply by `messageKey` (the i18n catalog key). They do not pass a finished
3
+ // string through a second interpreter.
4
+ //
5
+ // Sensitivity and category decide what a route is allowed to carry. A render
6
+ // hook may replace eligible text. It cannot change the destination: the
7
+ // router never reads the hook.
8
+
9
+ const settings = require("../config/settings.cjs");
10
+ const { t } = require("../utils/i18n.cjs");
11
+ const { escapeParam } = require("./escape.cjs");
12
+
13
+ const CATEGORIES = Object.freeze(["progress", "result", "error", "security", "system"]);
14
+ const SENSITIVITIES = Object.freeze(["operational", "source", "secret"]);
15
+
16
+ // Exact-output commands must not gain a watermark or a rewritten sentence.
17
+ const EXACT_OUTPUT = new Set([
18
+ "calc",
19
+ "rand",
20
+ "translate",
21
+ "md",
22
+ "digit",
23
+ "qr",
24
+ "loop",
25
+ "poll",
26
+ "ping",
27
+ "stt",
28
+ "send",
29
+ "shortlink",
30
+ ]);
31
+
32
+ const CATEGORY_DEFAULTS = Object.freeze({
33
+ progress: { sensitivity: "operational", hideable: true },
34
+ result: { sensitivity: "source", hideable: false },
35
+ error: { sensitivity: "operational", hideable: false },
36
+ security: { sensitivity: "secret", hideable: false },
37
+ system: { sensitivity: "operational", hideable: false },
38
+ });
39
+
40
+ const WATERMARK_LIMIT = 4096;
41
+ const hooks = { renderText: null };
42
+
43
+ function setRenderHook(fn) {
44
+ hooks.renderText = typeof fn === "function" ? fn : null;
45
+ }
46
+
47
+ /**
48
+ * @param {object} fields
49
+ * @returns {Readonly<object>}
50
+ */
51
+ function createMessage(fields = {}) {
52
+ const category = CATEGORIES.includes(fields.category) ? fields.category : "result";
53
+ const defaults = CATEGORY_DEFAULTS[category];
54
+ const sensitivity = SENSITIVITIES.includes(fields.sensitivity)
55
+ ? fields.sensitivity
56
+ : defaults.sensitivity;
57
+ const context = fields.context || {};
58
+ return Object.freeze({
59
+ messageKey: typeof fields.messageKey === "string" ? fields.messageKey : "",
60
+ category,
61
+ parameters: Object.freeze({ ...(fields.parameters || {}) }),
62
+ context: Object.freeze({
63
+ sourceChat: context.sourceChat || null,
64
+ requester: context.requester || null,
65
+ command: context.command || null,
66
+ }),
67
+ sensitivity,
68
+ deliveryPolicy: Object.freeze({
69
+ hideable: fields.deliveryPolicy?.hideable === true && defaults.hideable,
70
+ terminal: fields.deliveryPolicy?.terminal === true,
71
+ exact: fields.deliveryPolicy?.exact === true,
72
+ exception: fields.deliveryPolicy?.exception || null,
73
+ }),
74
+ });
75
+ }
76
+
77
+ function renderMessage(message) {
78
+ const params = {};
79
+ for (const [key, value] of Object.entries(message?.parameters || {})) {
80
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
81
+ params[key] = escapeParam(value);
82
+ }
83
+ let text = t(message.messageKey, params);
84
+ if (hooks.renderText) {
85
+ try {
86
+ const next = hooks.renderText(message, text);
87
+ if (typeof next === "string" && next.length <= WATERMARK_LIMIT) text = next;
88
+ } catch {
89
+ // A hook that throws leaves the catalog text in place.
90
+ }
91
+ }
92
+ return stampWatermark(text, {
93
+ commandName: message.context?.command,
94
+ category: message.category,
95
+ exact: message.deliveryPolicy?.exact === true || message.sensitivity === "secret",
96
+ });
97
+ }
98
+
99
+ /**
100
+ * The only watermark call site. Eligible result text gains one short line
101
+ * when the operator turns `message_watermark` on. Security, errors, files
102
+ * and exact-output commands stay as they are.
103
+ */
104
+ function stampWatermark(text, { commandName, category = "result", exact = false } = {}) {
105
+ if (typeof text !== "string" || !text) return text;
106
+ if (exact || category !== "result") return text;
107
+ if (commandName && EXACT_OUTPUT.has(commandName)) return text;
108
+ try {
109
+ if (require("../extensions/host.cjs").host.hideWatermark({ command: commandName, category })) {
110
+ return text;
111
+ }
112
+ } catch {}
113
+ if (!settings.get("message_watermark")) return text;
114
+ const mark = t("bot.core.message.watermark");
115
+ if (!mark || text.includes(mark)) return text;
116
+ const next = `${text}\n${mark}`;
117
+ if (next.length > WATERMARK_LIMIT) return text;
118
+ return next;
119
+ }
120
+
121
+ function categoryDefaults(category) {
122
+ return CATEGORY_DEFAULTS[category] || CATEGORY_DEFAULTS.result;
123
+ }
124
+
125
+ module.exports = {
126
+ CATEGORIES,
127
+ SENSITIVITIES,
128
+ EXACT_OUTPUT,
129
+ CATEGORY_DEFAULTS,
130
+ createMessage,
131
+ renderMessage,
132
+ stampWatermark,
133
+ escapeParam,
134
+ setRenderHook,
135
+ categoryDefaults,
136
+ };
@@ -0,0 +1,88 @@
1
+ // Command Engine v2 parser.
2
+ //
3
+ // One pure function turns the text of a message into a command invocation.
4
+ // It does not load commands, check permissions, or send anything. The
5
+ // dispatcher does that, so a new command such as `!update` (Phase 09) needs
6
+ // no parser change: a well-formed name comes out and the registry decides.
7
+ //
8
+ // v1 is the previous split, kept behind the `command_parser` setting for one
9
+ // release. Rollback switches the setting. It does not grow a second sender.
10
+
11
+ const NAME_MAX = 32;
12
+
13
+ function hasDisallowedChar(token) {
14
+ for (const char of token) {
15
+ const code = char.codePointAt(0);
16
+ if (code <= 0x1f || code === 0x7f) return true;
17
+ if (code >= 0x202a && code <= 0x202e) return true;
18
+ if (code >= 0x2066 && code <= 0x2069) return true;
19
+ if (char === "\\" || char === "/" || char === "." || char === ":" || char === "`") return true;
20
+ }
21
+ return false;
22
+ }
23
+
24
+ /**
25
+ * A token that can be a command name or an alias.
26
+ * Letters (any language), digits, `_` and `-`, plus the one shipped alias `=`.
27
+ * Slashes, dots and colons are rejected so a URL or a path after the prefix
28
+ * is ordinary text, not a command.
29
+ * @param {string} token
30
+ */
31
+ function isCommandName(token) {
32
+ if (!token || token.length > NAME_MAX) return false;
33
+ if (hasDisallowedChar(token)) return false;
34
+ if (token === "=") return true;
35
+ return /^[\p{L}\p{N}_-]+$/u.test(token);
36
+ }
37
+
38
+ /**
39
+ * @param {string} body
40
+ * @param {string} prefix
41
+ * @returns {{kind: "not-command"}|{kind: "empty"}|{kind: "command", name: string, args: string[], rawRemainder: string}}
42
+ */
43
+ function parseCommandText(body, { prefix = "!" } = {}) {
44
+ if (typeof body !== "string" || !prefix || !body.startsWith(prefix)) {
45
+ return { kind: "not-command" };
46
+ }
47
+
48
+ const rest = body.slice(prefix.length);
49
+ // A newline between the command and the next word is a separator, the same
50
+ // way a space is. Leading whitespace after the prefix is that separator.
51
+ const trimmed = rest.replace(/^\s+/, "");
52
+ if (!trimmed) return { kind: "empty" };
53
+
54
+ const nameMatch = /^\S+/.exec(trimmed);
55
+ const rawName = nameMatch ? nameMatch[0] : "";
56
+ if (!isCommandName(rawName)) return { kind: "not-command" };
57
+
58
+ const afterName = trimmed.slice(rawName.length);
59
+ // Drop only the separator before the arguments. Newlines inside the
60
+ // arguments stay in rawRemainder so a command can keep a paragraph.
61
+ const rawRemainder = afterName.replace(/^[ \t\r\n]+/, "");
62
+ const args = rawRemainder ? rawRemainder.split(/\s+/).filter(Boolean) : [];
63
+
64
+ return {
65
+ kind: "command",
66
+ name: rawName.toLowerCase(),
67
+ args,
68
+ rawRemainder,
69
+ };
70
+ }
71
+
72
+ /** The v4 splitter: any first token, unknown names included. */
73
+ function parseCommandTextV1(body, { prefix = "!" } = {}) {
74
+ if (typeof body !== "string" || !prefix || !body.startsWith(prefix)) {
75
+ return { kind: "not-command" };
76
+ }
77
+ const parts = body.slice(prefix.length).trim().split(/\s+/).filter(Boolean);
78
+ if (!parts.length) return { kind: "empty" };
79
+ const rawName = parts.shift();
80
+ return {
81
+ kind: "command",
82
+ name: String(rawName).toLowerCase(),
83
+ args: parts,
84
+ rawRemainder: parts.join(" "),
85
+ };
86
+ }
87
+
88
+ module.exports = { isCommandName, parseCommandText, parseCommandTextV1 };