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,200 @@
1
+ // `levix terms`: read and accept the Terms from a terminal (ADR-006, Q-04).
2
+ //
3
+ // levix terms print, then ask the operator to type "accept"
4
+ // levix terms show [--lang l] print the documents, the version and the hash
5
+ // levix terms status exit 0 when accepted, 2 when not
6
+ // levix terms accept --terms-version <v> --sha256 <hash> [--lang l]
7
+ // unattended installs: record only an exact match
8
+ // levix terms revoke delete the acceptance
9
+ //
10
+ // The interactive form refuses without a terminal on both ends, so a pipe or a
11
+ // script can never type the confirmation. The provisioning form needs the
12
+ // version and the hash the operator read with `show`. There is no start flag
13
+ // and no environment variable that accepts.
14
+
15
+ const consent = require("./consent.cjs");
16
+ const terms = require("./terms.cjs");
17
+
18
+ const WIDTH = 78;
19
+ const EXIT = Object.freeze({ OK: 0, REFUSED: 1, REQUIRED: 2 });
20
+
21
+ function wrap(text, indent) {
22
+ const lines = [];
23
+ let current = "";
24
+ for (const word of text.split(/\s+/)) {
25
+ if (current && indent.length + current.length + 1 + word.length > WIDTH) {
26
+ lines.push(indent + current);
27
+ current = word;
28
+ } else {
29
+ current = current ? `${current} ${word}` : word;
30
+ }
31
+ }
32
+ if (current) lines.push(indent + current);
33
+ return lines;
34
+ }
35
+
36
+ function renderPart(part) {
37
+ const lines = [part.title, "=".repeat(Math.min(part.title.length, WIDTH)), ""];
38
+ for (const section of part.sections) {
39
+ lines.push(section.heading);
40
+ for (const paragraph of section.paragraphs) lines.push(...wrap(paragraph, " "), "");
41
+ }
42
+ return lines;
43
+ }
44
+
45
+ /** The two documents, then what identifies them and the links that belong to them. */
46
+ function renderDocument(entry) {
47
+ return [
48
+ "",
49
+ ...renderPart(entry.document.terms),
50
+ ...renderPart(entry.document.privacy),
51
+ `Version: ${entry.version}`,
52
+ `Language: ${entry.locale}`,
53
+ `SHA-256: ${entry.sha256}`,
54
+ "",
55
+ `Full Privacy Policy: ${terms.LINKS.privacyPolicy}`,
56
+ `License: ${terms.LINKS.license}`,
57
+ `Website: ${terms.LINKS.website}`,
58
+ "",
59
+ ];
60
+ }
61
+
62
+ function pickDocument(values, io) {
63
+ const requested = values.get("--lang");
64
+ const locale = requested ?? terms.DEFAULT_LOCALE;
65
+ const entry = terms.documentFor(locale);
66
+ if (!entry) {
67
+ io.error(`No Terms in "${locale}". Available: ${terms.availableLocales().join(", ")}.`);
68
+ return null;
69
+ }
70
+ return entry;
71
+ }
72
+
73
+ function statusLine(status) {
74
+ if (status.ok) {
75
+ const a = status.accepted;
76
+ return `Accepted: Terms ${a.termsVersion} (${a.locale}) on ${a.acceptedAt}, with Levix ${a.appVersion}.`;
77
+ }
78
+ return `Not accepted: ${consent.describeReason(status.reason)}`;
79
+ }
80
+
81
+ const AFTER_ACCEPT =
82
+ "Accepted. Levix connects to WhatsApp on its next start; a running Levix continues within a few seconds.";
83
+
84
+ /**
85
+ * Run one `levix terms` subcommand.
86
+ *
87
+ * `io`: `{ out(line), error(line), isInteractive, ask(question) -> Promise<string> }`.
88
+ * `asDataOwner` wraps every database write (sudo runs as the data directory owner).
89
+ */
90
+ async function runTerms({ positional = [], values = new Map(), io, asDataOwner = (fn) => fn() }) {
91
+ const sub = positional[1] ?? null;
92
+ const print = (lines) => {
93
+ for (const line of lines) io.out(line);
94
+ };
95
+
96
+ try {
97
+ terms.currentRelease();
98
+ } catch (error) {
99
+ io.error(`The bundled Terms are not usable: ${error.message}`);
100
+ return EXIT.REFUSED;
101
+ }
102
+
103
+ switch (sub) {
104
+ case "show": {
105
+ const entry = pickDocument(values, io);
106
+ if (!entry) return EXIT.REFUSED;
107
+ print(renderDocument(entry));
108
+ print([
109
+ "To accept this exact text on an unattended install, run:",
110
+ ` levix terms accept --terms-version ${entry.version} --sha256 ${entry.sha256}` +
111
+ (entry.locale === terms.DEFAULT_LOCALE ? "" : ` --lang ${entry.locale}`),
112
+ "",
113
+ ]);
114
+ return EXIT.OK;
115
+ }
116
+
117
+ case "status": {
118
+ const status = await asDataOwner(() => consent.consentStatus());
119
+ io.out(statusLine(status));
120
+ return status.ok ? EXIT.OK : EXIT.REQUIRED;
121
+ }
122
+
123
+ case "accept": {
124
+ const version = values.get("--terms-version");
125
+ const sha256 = values.get("--sha256");
126
+ if (!version || !sha256) {
127
+ io.error("Usage: levix terms accept --terms-version <version> --sha256 <hash> [--lang <language>]");
128
+ io.error('Read the Terms and get both values with "levix terms show".');
129
+ return EXIT.REFUSED;
130
+ }
131
+ const entry = pickDocument(values, io);
132
+ if (!entry) return EXIT.REFUSED;
133
+ try {
134
+ await asDataOwner(() =>
135
+ consent.recordAcceptance({ version, sha256: sha256.toLowerCase(), locale: entry.locale, via: "provision" }),
136
+ );
137
+ } catch (error) {
138
+ if (error.code !== "TERMS_MISMATCH") throw error;
139
+ io.error("Not accepted: that version and SHA-256 do not match the current Terms.");
140
+ io.error(`Read the current text with "levix terms show${entry.locale === terms.DEFAULT_LOCALE ? "" : ` --lang ${entry.locale}`}".`);
141
+ return EXIT.REFUSED;
142
+ }
143
+ io.out(AFTER_ACCEPT);
144
+ return EXIT.OK;
145
+ }
146
+
147
+ case "revoke": {
148
+ await asDataOwner(() => consent.revokeAcceptance());
149
+ io.out("Acceptance removed. A live WhatsApp connection stays up; Levix asks again before it next connects.");
150
+ return EXIT.OK;
151
+ }
152
+
153
+ case null: {
154
+ if (!io.isInteractive) {
155
+ io.error('"levix terms" needs a terminal to ask for your confirmation.');
156
+ io.error('On an unattended install, run "levix terms show", then "levix terms accept".');
157
+ return EXIT.REFUSED;
158
+ }
159
+ const entry = pickDocument(values, io);
160
+ if (!entry) return EXIT.REFUSED;
161
+ print(renderDocument(entry));
162
+ const answer = await io.ask(
163
+ 'Type "accept" to accept the Terms of Use and the Privacy Notice for this installation.\nAnything else cancels: ',
164
+ );
165
+ if (String(answer ?? "").trim().toLowerCase() !== "accept") {
166
+ io.out("Not accepted. Levix will not connect to WhatsApp until the Terms are accepted.");
167
+ return EXIT.REFUSED;
168
+ }
169
+ await asDataOwner(() =>
170
+ consent.recordAcceptance({ version: entry.version, sha256: entry.sha256, locale: entry.locale, via: "cli" }),
171
+ );
172
+ io.out(AFTER_ACCEPT);
173
+ return EXIT.OK;
174
+ }
175
+
176
+ default:
177
+ io.error(`Unknown terms command: ${sub}. Use show, status, accept or revoke.`);
178
+ return EXIT.REFUSED;
179
+ }
180
+ }
181
+
182
+ /** The real terminal. */
183
+ function terminalIo({ stdin = process.stdin, stdout = process.stdout, stderr = process.stderr } = {}) {
184
+ return {
185
+ out: (line) => stdout.write(`${line}\n`),
186
+ error: (line) => stderr.write(`${line}\n`),
187
+ isInteractive: Boolean(stdin.isTTY && stdout.isTTY),
188
+ async ask(question) {
189
+ const readline = require("node:readline/promises");
190
+ const rl = readline.createInterface({ input: stdin, output: stdout });
191
+ try {
192
+ return await rl.question(question);
193
+ } finally {
194
+ rl.close();
195
+ }
196
+ },
197
+ };
198
+ }
199
+
200
+ module.exports = { EXIT, runTerms, terminalIo, renderDocument };
@@ -0,0 +1,187 @@
1
+ // The installation's Terms acceptance (ADR-020).
2
+ //
3
+ // One `bot_settings` row, `legal:acceptance`, outside the `setting:*`
4
+ // namespace: settings export reads only `setting:*`, and backups carry only
5
+ // RESTORABLE_BOT_KEYS, so the record never leaves this device. It holds no
6
+ // identifier of a person, a device or a WhatsApp account.
7
+ //
8
+ // The session asks consentStatus() before every socket it builds
9
+ // (src/core/session.js). Anything that cannot be read counts as "not
10
+ // accepted": the gate fails closed. That includes the release identity
11
+ // (src/config/release.cjs): a build file that exists but cannot be read
12
+ // is not a reason to keep an old acceptance.
13
+
14
+ const { releaseIdentity } = require("../config/release.cjs");
15
+ const { HASH_RE, parseVersion } = require("./document.cjs");
16
+ const terms = require("./terms.cjs");
17
+
18
+ const KEY = "legal:acceptance";
19
+ const RECORD_SCHEMA = 1;
20
+ const RECORD_KEYS = Object.freeze([
21
+ "schema",
22
+ "appVersion",
23
+ "termsVersion",
24
+ "sha256",
25
+ "locale",
26
+ "acceptedAt",
27
+ "via",
28
+ ]);
29
+ const VIA = Object.freeze(["panel", "cli", "provision"]);
30
+
31
+ const REASONS = Object.freeze({
32
+ NOT_ACCEPTED: "terms_not_accepted",
33
+ CHANGED: "terms_changed",
34
+ APP_UPDATED: "app_updated",
35
+ UNREADABLE: "consent_unreadable",
36
+ });
37
+
38
+ const DESCRIPTIONS = Object.freeze({
39
+ [REASONS.NOT_ACCEPTED]: "The Terms of Use and the Privacy Notice have not been accepted on this installation.",
40
+ [REASONS.CHANGED]: "The Terms of Use or the Privacy Notice changed since they were accepted.",
41
+ [REASONS.APP_UPDATED]: "Levix was updated since the Terms of Use were accepted.",
42
+ [REASONS.UNREADABLE]: "The Terms acceptance record could not be read.",
43
+ });
44
+
45
+ class ConsentError extends Error {
46
+ constructor(code, message) {
47
+ super(message);
48
+ this.name = "ConsentError";
49
+ this.code = code;
50
+ }
51
+ }
52
+
53
+ let cachedAppVersion = null;
54
+ // Tests only. A string stands in for releaseIdentity(); undefined uses it.
55
+ let appVersionOverride;
56
+
57
+ /** The release identity an acceptance is bound to. The export name stays appVersion. */
58
+ function appVersion() {
59
+ if (appVersionOverride !== undefined) return appVersionOverride;
60
+ if (cachedAppVersion === null) cachedAppVersion = releaseIdentity();
61
+ return cachedAppVersion;
62
+ }
63
+
64
+ /** Test seam. Pass a release-identity string, or undefined to use releaseIdentity(). */
65
+ function _setAppVersionForTests(identity) {
66
+ appVersionOverride = identity;
67
+ }
68
+
69
+ // Required lazily: `levix terms show` and the tests of the document format
70
+ // must not open a database just by loading this module.
71
+ function store() {
72
+ return require("../db/store.cjs");
73
+ }
74
+
75
+ function isIsoUtcTimestamp(value) {
76
+ if (typeof value !== "string") return false;
77
+ const date = new Date(value);
78
+ return !Number.isNaN(date.getTime()) && date.toISOString() === value;
79
+ }
80
+
81
+ function isRecord(value) {
82
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
83
+ const keys = Object.keys(value);
84
+ return (
85
+ keys.length === RECORD_KEYS.length &&
86
+ RECORD_KEYS.every((key) => Object.hasOwn(value, key)) &&
87
+ value.schema === RECORD_SCHEMA &&
88
+ typeof value.appVersion === "string" &&
89
+ value.appVersion.length > 0 &&
90
+ value.appVersion.length <= 64 &&
91
+ parseVersion(value.termsVersion) !== null &&
92
+ typeof value.sha256 === "string" &&
93
+ HASH_RE.test(value.sha256) &&
94
+ terms.LOCALES.includes(value.locale) &&
95
+ isIsoUtcTimestamp(value.acceptedAt) &&
96
+ VIA.includes(value.via)
97
+ );
98
+ }
99
+
100
+ /** The stored record, or null when there is none or it is malformed. Throws on a database error. */
101
+ function readAcceptance() {
102
+ const value = store().getBotSetting(KEY, null);
103
+ return isRecord(value) ? value : null;
104
+ }
105
+
106
+ /**
107
+ * Whether this installation may connect to WhatsApp.
108
+ *
109
+ * `{ ok, reason, current, accepted }`. `reason` is null when ok, otherwise one
110
+ * of REASONS. Never throws.
111
+ */
112
+ function consentStatus() {
113
+ let release;
114
+ let accepted;
115
+ let identity;
116
+ try {
117
+ release = terms.currentRelease();
118
+ accepted = readAcceptance();
119
+ identity = appVersion();
120
+ } catch {
121
+ return { ok: false, reason: REASONS.UNREADABLE, current: null, accepted: null };
122
+ }
123
+ const current = { version: release.version, locales: Object.keys(release.documents), appVersion: identity };
124
+ const result = (ok, reason) => ({ ok, reason, current, accepted });
125
+
126
+ if (!accepted) return result(false, REASONS.NOT_ACCEPTED);
127
+ const document = terms.documentFor(accepted.locale);
128
+ if (!document || accepted.termsVersion !== document.version || accepted.sha256 !== document.sha256) {
129
+ return result(false, REASONS.CHANGED);
130
+ }
131
+ if (accepted.appVersion !== identity) return result(false, REASONS.APP_UPDATED);
132
+ return result(true, null);
133
+ }
134
+
135
+ /**
136
+ * Record an acceptance of the document the operator was shown.
137
+ *
138
+ * `version` and `sha256` must equal the current document for `locale`; any
139
+ * difference means the operator saw something else, and nothing is written.
140
+ */
141
+ function recordAcceptance({ version, sha256, locale, via, now = new Date() } = {}) {
142
+ if (!VIA.includes(via)) throw new ConsentError("CONSENT_BAD_REQUEST", "Unknown acceptance channel");
143
+ // This process may have shown an older memo while the bot cached a newer release.
144
+ terms.invalidate();
145
+ const document = typeof locale === "string" ? terms.documentFor(locale) : null;
146
+ if (!document) throw new ConsentError("CONSENT_BAD_LOCALE", "No Terms document in that language");
147
+ if (version !== document.version || sha256 !== document.sha256) {
148
+ throw new ConsentError("TERMS_MISMATCH", "The Terms version or SHA-256 does not match the current document");
149
+ }
150
+ // A broken release identity throws here, before the write.
151
+ const identity = appVersion();
152
+ const record = {
153
+ schema: RECORD_SCHEMA,
154
+ appVersion: identity,
155
+ termsVersion: document.version,
156
+ sha256: document.sha256,
157
+ locale: document.locale,
158
+ acceptedAt: now.toISOString(),
159
+ via,
160
+ };
161
+ store().saveBotSetting(KEY, record);
162
+ return record;
163
+ }
164
+
165
+ /** Remove the acceptance. A live connection stays; the next start asks again. */
166
+ function revokeAcceptance() {
167
+ store().deleteBotSetting(KEY);
168
+ }
169
+
170
+ /** One English sentence per reason, for logs, the CLI and the session detail. */
171
+ function describeReason(reason) {
172
+ return DESCRIPTIONS[reason] || DESCRIPTIONS[REASONS.NOT_ACCEPTED];
173
+ }
174
+
175
+ module.exports = {
176
+ KEY,
177
+ REASONS,
178
+ VIA,
179
+ ConsentError,
180
+ appVersion,
181
+ _setAppVersionForTests,
182
+ readAcceptance,
183
+ consentStatus,
184
+ recordAcceptance,
185
+ revokeAcceptance,
186
+ describeReason,
187
+ };
@@ -0,0 +1,156 @@
1
+ // The Terms and Privacy document format: validation, canonical bytes, hash.
2
+ //
3
+ // One shape for the bundled release and for a remote one (Phase 04c), so the
4
+ // same checks decide what the operator is shown and what their acceptance is
5
+ // bound to. The rules are in docs/plans/v5/LEGAL_CONSENT_CONTRACT.md section 1.
6
+ //
7
+ // Every string is rendered as text by every client. That is why the checks
8
+ // refuse URLs and bidi overrides instead of trying to sanitize them: a
9
+ // document is not allowed to point anywhere or to reorder what it says.
10
+
11
+ const crypto = require("node:crypto");
12
+
13
+ const SCHEMA = 1;
14
+ const LOCALES = Object.freeze(["ar", "en", "pt-BR", "es-419"]);
15
+ const VERSION_RE = /^(\d{4})-(\d{2})-(\d{2})(?:\.([1-9]\d{0,2}))?$/;
16
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
17
+ const HASH_RE = /^[0-9a-f]{64}$/;
18
+
19
+ const LIMITS = Object.freeze({
20
+ maxBytes: 65536,
21
+ maxTitle: 160,
22
+ maxSections: 30,
23
+ maxParagraphs: 20,
24
+ maxParagraph: 2000,
25
+ });
26
+
27
+ // C0 and C1 controls, bidi embeddings and overrides (U+202A..U+202E) and bidi
28
+ // isolates (U+2066..U+2069).
29
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: these are exactly the characters refused
30
+ const FORBIDDEN_CHARS_RE = /[\u0000-\u001f\u007f-\u009f‪-‮⁦-⁩]/;
31
+ const LINK_RE = /:\/\/|www\./i;
32
+
33
+ class LegalDocumentError extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "LegalDocumentError";
37
+ this.code = "LEGAL_DOCUMENT_INVALID";
38
+ }
39
+ }
40
+
41
+ function fail(message) {
42
+ throw new LegalDocumentError(message);
43
+ }
44
+
45
+ function exactKeys(value, keys, where) {
46
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail(`${where} must be an object`);
47
+ const actual = Object.keys(value).sort();
48
+ const expected = [...keys].sort();
49
+ if (actual.length !== expected.length || actual.some((key, i) => key !== expected[i])) {
50
+ fail(`${where} must have exactly the keys ${expected.join(", ")}`);
51
+ }
52
+ }
53
+
54
+ function text(value, max, where) {
55
+ if (typeof value !== "string") fail(`${where} must be a string`);
56
+ if (value.length < 1 || value.length > max) fail(`${where} must be 1 to ${max} characters`);
57
+ if (value.trim() !== value || value.trim().length === 0) fail(`${where} has leading or trailing space`);
58
+ if (value.normalize("NFC") !== value) fail(`${where} must be NFC`);
59
+ if (FORBIDDEN_CHARS_RE.test(value)) fail(`${where} has a control or bidi override character`);
60
+ if (LINK_RE.test(value)) fail(`${where} must not contain a link`);
61
+ }
62
+
63
+ function part(value, where) {
64
+ exactKeys(value, ["title", "sections"], where);
65
+ text(value.title, LIMITS.maxTitle, `${where}.title`);
66
+ const { sections } = value;
67
+ if (!Array.isArray(sections) || sections.length < 1 || sections.length > LIMITS.maxSections) {
68
+ fail(`${where}.sections must hold 1 to ${LIMITS.maxSections} sections`);
69
+ }
70
+ for (const [i, section] of sections.entries()) {
71
+ const at = `${where}.sections[${i}]`;
72
+ exactKeys(section, ["heading", "paragraphs"], at);
73
+ text(section.heading, LIMITS.maxTitle, `${at}.heading`);
74
+ const { paragraphs } = section;
75
+ if (!Array.isArray(paragraphs) || paragraphs.length < 1 || paragraphs.length > LIMITS.maxParagraphs) {
76
+ fail(`${at}.paragraphs must hold 1 to ${LIMITS.maxParagraphs} paragraphs`);
77
+ }
78
+ for (const [j, paragraph] of paragraphs.entries()) {
79
+ text(paragraph, LIMITS.maxParagraph, `${at}.paragraphs[${j}]`);
80
+ }
81
+ }
82
+ }
83
+
84
+ function validDate(value) {
85
+ if (!DATE_RE.test(value)) return false;
86
+ const date = new Date(`${value}T00:00:00Z`);
87
+ return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
88
+ }
89
+
90
+ function parseVersion(version) {
91
+ const match = typeof version === "string" ? VERSION_RE.exec(version) : null;
92
+ if (!match || !validDate(version.slice(0, 10))) return null;
93
+ return { date: version.slice(0, 10), revision: match[4] ? Number(match[4]) : 0 };
94
+ }
95
+
96
+ /** Negative when a is older than b, zero when equal, positive when newer. */
97
+ function compareVersions(a, b) {
98
+ const left = parseVersion(a);
99
+ const right = parseVersion(b);
100
+ if (!left || !right) throw new LegalDocumentError("Cannot compare an invalid version");
101
+ if (left.date !== right.date) return left.date < right.date ? -1 : 1;
102
+ return left.revision - right.revision;
103
+ }
104
+
105
+ /** Keys sorted, no whitespace. Only plain JSON values reach here. */
106
+ function canonicalJson(value) {
107
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
108
+ if (value && typeof value === "object") {
109
+ return `{${Object.keys(value)
110
+ .sort()
111
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
112
+ .join(",")}}`;
113
+ }
114
+ return JSON.stringify(value);
115
+ }
116
+
117
+ /** Throws LegalDocumentError unless `doc` follows the contract. Returns it frozen. */
118
+ function validateDocument(doc) {
119
+ exactKeys(doc, ["schema", "version", "locale", "effective", "terms", "privacy"], "document");
120
+ if (doc.schema !== SCHEMA) fail(`document.schema must be ${SCHEMA}`);
121
+ if (!parseVersion(doc.version)) fail("document.version must be YYYY-MM-DD or YYYY-MM-DD.N");
122
+ if (!LOCALES.includes(doc.locale)) fail(`document.locale must be one of ${LOCALES.join(", ")}`);
123
+ if (typeof doc.effective !== "string" || !validDate(doc.effective)) fail("document.effective must be YYYY-MM-DD");
124
+ part(doc.terms, "document.terms");
125
+ part(doc.privacy, "document.privacy");
126
+ if (Buffer.byteLength(canonicalJson(doc), "utf8") > LIMITS.maxBytes) {
127
+ fail(`document is larger than ${LIMITS.maxBytes} bytes`);
128
+ }
129
+ return deepFreeze(doc);
130
+ }
131
+
132
+ function deepFreeze(value) {
133
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
134
+ Object.freeze(value);
135
+ for (const child of Object.values(value)) deepFreeze(child);
136
+ }
137
+ return value;
138
+ }
139
+
140
+ /** Lowercase hex sha256 of the document's canonical UTF-8 bytes. */
141
+ function documentHash(doc) {
142
+ return crypto.createHash("sha256").update(canonicalJson(doc), "utf8").digest("hex");
143
+ }
144
+
145
+ module.exports = {
146
+ SCHEMA,
147
+ LOCALES,
148
+ LIMITS,
149
+ HASH_RE,
150
+ LegalDocumentError,
151
+ validateDocument,
152
+ canonicalJson,
153
+ documentHash,
154
+ parseVersion,
155
+ compareVersions,
156
+ };
@@ -0,0 +1,100 @@
1
+ // The public keys that may sign a remote Terms release (ADR-019).
2
+ //
3
+ // The private key never lives here. The owner generates it outside this
4
+ // repository (`scripts/legal-release.mjs keygen`) and adds only the public
5
+ // half. Remote fetching has a separate activation gate in remote.cjs.
6
+ //
7
+ // Callers read `TRUSTED_KEYS` from this module at the moment they verify, not
8
+ // a copy taken when they were loaded.
9
+
10
+ const crypto = require("node:crypto");
11
+
12
+ // Ed25519 SubjectPublicKeyInfo: algorithm OID 1.3.101.112, then the 32 raw bytes.
13
+ const SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
14
+
15
+ class LegalKeyError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "LegalKeyError";
19
+ this.code = "LEGAL_KEY_INVALID";
20
+ }
21
+ }
22
+
23
+ function keyIdForRaw(raw) {
24
+ return crypto.createHash("sha256").update(raw).digest("hex").slice(0, 16);
25
+ }
26
+
27
+ function rawPublicKeyFromBase64(value) {
28
+ const alphabet = typeof value === "string" && /^[A-Za-z0-9+/]*={0,2}$/.test(value);
29
+ if (!alphabet || value.length % 4 !== 0) {
30
+ throw new LegalKeyError("publicKey must be strict base64");
31
+ }
32
+ const raw = Buffer.from(value, "base64");
33
+ if (raw.toString("base64") !== value || raw.length !== 32) {
34
+ throw new LegalKeyError("publicKey must be 32 bytes of strict base64");
35
+ }
36
+ return raw;
37
+ }
38
+
39
+ function publicKeyObjectFromRaw(raw) {
40
+ if (!Buffer.isBuffer(raw) || raw.length !== 32) {
41
+ throw new LegalKeyError("public key must be 32 bytes");
42
+ }
43
+ return crypto.createPublicKey({
44
+ key: Buffer.concat([SPKI_PREFIX, raw]),
45
+ format: "der",
46
+ type: "spki",
47
+ });
48
+ }
49
+
50
+ function rawFromKeyObject(publicKey) {
51
+ const der = publicKey.export({ format: "der", type: "spki" });
52
+ const prefix = der.subarray(0, SPKI_PREFIX.length);
53
+ const prefixOk = der.length === SPKI_PREFIX.length + 32 && prefix.equals(SPKI_PREFIX);
54
+ if (!prefixOk) throw new LegalKeyError("key is not an Ed25519 public key");
55
+ return Buffer.from(der.subarray(SPKI_PREFIX.length));
56
+ }
57
+
58
+ /** Throws LegalKeyError when an entry is not `{ keyId, publicKey }` for its own raw key. */
59
+ function assertTrustedKeys(entries) {
60
+ if (!Array.isArray(entries)) throw new LegalKeyError("TRUSTED_KEYS must be an array");
61
+ const seen = new Set();
62
+ for (const [index, entry] of entries.entries()) {
63
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
64
+ throw new LegalKeyError(`trusted key ${index} must be an object`);
65
+ }
66
+ const names = Object.keys(entry);
67
+ const hasId = Object.hasOwn(entry, "keyId");
68
+ const hasKey = Object.hasOwn(entry, "publicKey");
69
+ if (names.length !== 2 || !hasId || !hasKey) {
70
+ throw new LegalKeyError(`trusted key ${index} must have exactly keyId and publicKey`);
71
+ }
72
+ const raw = rawPublicKeyFromBase64(entry.publicKey);
73
+ const derived = keyIdForRaw(raw);
74
+ if (entry.keyId !== derived) {
75
+ throw new LegalKeyError(`trusted key ${index} keyId does not match the public key`);
76
+ }
77
+ if (seen.has(derived)) throw new LegalKeyError(`trusted key ${index} repeats a keyId`);
78
+ seen.add(derived);
79
+ publicKeyObjectFromRaw(raw);
80
+ }
81
+ }
82
+
83
+ // The public half supplied by the owner; the private key stays outside the repository.
84
+ const TRUSTED_KEYS = Object.freeze([
85
+ Object.freeze({
86
+ keyId: "8aa0176930c8d7f8",
87
+ publicKey: "VRvBOTkLFIYuPaTKVAKMdCxMpWBKXV00bCSGdMpQENY=",
88
+ }),
89
+ ]);
90
+ assertTrustedKeys(TRUSTED_KEYS);
91
+
92
+ module.exports = {
93
+ TRUSTED_KEYS,
94
+ LegalKeyError,
95
+ assertTrustedKeys,
96
+ keyIdForRaw,
97
+ rawPublicKeyFromBase64,
98
+ publicKeyObjectFromRaw,
99
+ rawFromKeyObject,
100
+ };