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,41 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const { dataPath, ensureDataDir } = require("../config/paths.cjs");
4
+ const { fsyncDirectory } = require("../db/db.cjs");
5
+
6
+ const root = () => {
7
+ const folder = ensureDataDir("restore");
8
+ if (process.platform !== "win32") fs.chmodSync(folder, 0o700);
9
+ return folder;
10
+ };
11
+ const journalPath = () => dataPath("restore", "journal.json");
12
+
13
+ function atomicJson(file, value) {
14
+ const folder = path.dirname(file);
15
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
16
+ const temp = `${file}.${require("node:crypto").randomBytes(8).toString("hex")}.part`;
17
+ try {
18
+ fs.writeFileSync(temp, JSON.stringify(value), { flag: "wx", mode: 0o600 });
19
+ const fd = fs.openSync(temp, "r");
20
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
21
+ fs.renameSync(temp, file);
22
+ fsyncDirectory(folder);
23
+ } finally { fs.rmSync(temp, { force: true }); }
24
+ }
25
+
26
+ function writeJournal(value) { atomicJson(path.join(root(), "journal.json"), value); }
27
+ function readJournal() {
28
+ try { return JSON.parse(fs.readFileSync(journalPath(), "utf8")); }
29
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
30
+ }
31
+ function clearJournal() {
32
+ fs.rmSync(journalPath(), { force: true });
33
+ fsyncDirectory(root());
34
+ }
35
+ function writeOutcome(value) { atomicJson(dataPath("restore", "last-outcome.json"), value); }
36
+ function readOutcome() {
37
+ try { return JSON.parse(fs.readFileSync(dataPath("restore", "last-outcome.json"), "utf8")); }
38
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
39
+ }
40
+
41
+ module.exports = { writeJournal, readJournal, clearJournal, writeOutcome, readOutcome, atomicJson };
@@ -0,0 +1,223 @@
1
+ // What a restore changes on this install. The preview builds the plan from the
2
+ // digests in the backup manifest; the restore job builds it again from the
3
+ // staged rows, so a crafted manifest cannot hide a change. Both use buildPlan.
4
+ //
5
+ // A restore only adds and replaces. A setting, an API key or the persona that
6
+ // the backup does not contain keeps its current value here. A change that
7
+ // overwrites a value this install already has is destructive and needs an
8
+ // explicit confirmation from the operator.
9
+ const crypto = require("node:crypto");
10
+ const fs = require("node:fs");
11
+ const path = require("node:path");
12
+ const { db } = require("../db/db.cjs");
13
+ const settings = require("../config/settings.cjs");
14
+ const { dataPath } = require("../config/paths.cjs");
15
+ const { ACCOUNT_TABLES, RESTORABLE_BOT_KEYS, RESTORABLE_SETTING_KEYS } = require("./content.cjs");
16
+ const { readPairedAccount, maskAccount, accountsMatch } = require("./account.cjs");
17
+ const extensions = require("./extensions.cjs");
18
+
19
+ const digest = (text) => crypto.createHash("sha256").update(String(text)).digest("hex");
20
+
21
+ /**
22
+ * Digests of the restorable bot_settings rows and of the plain API key values.
23
+ * `plus` (Plus config and account rows, keyed `cfg:<name>` / `acct:<name>`) is
24
+ * present only when there is at least one, so an install without Plus data
25
+ * produces the same digests as before.
26
+ */
27
+ function digestsFrom(rows, secretValues = {}) {
28
+ const result = { settings: {}, apiKeys: {} };
29
+ const plus = {};
30
+ for (const { key, value } of rows) {
31
+ if (RESTORABLE_BOT_KEYS.includes(key)) result.settings[key] = digest(value);
32
+ else if (extensions.isRestorableExtKey(key)) plus[extensions.shortName(key)] = digest(extensions.canonicalValue(value));
33
+ }
34
+ if (Object.keys(plus).length) result.plus = plus;
35
+ for (const [name, value] of Object.entries(secretValues)) {
36
+ if (settings.SECRET_SETTING_KEYS.includes(name)) result.apiKeys[name] = digest(value);
37
+ }
38
+ return result;
39
+ }
40
+
41
+ function restorableRows(database) {
42
+ const keys = RESTORABLE_BOT_KEYS;
43
+ const rows = database.prepare(
44
+ `SELECT key, value FROM bot_settings WHERE key IN (${keys.map(() => "?").join(",")})`,
45
+ ).all(...keys);
46
+ return [...rows, ...extensions.validRows(database).map(({ key, value }) => ({ key, value }))];
47
+ }
48
+
49
+ function currentDigests() {
50
+ const apiKeys = {};
51
+ for (const name of settings.SECRET_SETTING_KEYS) {
52
+ if (settings.sourceOf(name) !== "dashboard") continue;
53
+ const value = settings.get(name);
54
+ if (value) apiKeys[name] = digest(value);
55
+ }
56
+ // Effective values include the defaults, so a side effect on a setting that
57
+ // has no stored row still shows up.
58
+ const effective = {};
59
+ for (const key of RESTORABLE_SETTING_KEYS) effective[`setting:${key}`] = digest(JSON.stringify(settings.get(key)));
60
+ const rows = digestsFrom(restorableRows(db));
61
+ return { settings: rows.settings, apiKeys, effective, plus: rows.plus ?? {} };
62
+ }
63
+
64
+ // Command permissions decide who may run what, so even adding overrides to an
65
+ // install that has none needs the operator's confirmation.
66
+ const ACCESS_KEYS = Object.freeze(["command_permissions"]);
67
+ const changesAccess = (part) => part.added.some((key) => ACCESS_KEYS.includes(key));
68
+
69
+ function compare(source, target) {
70
+ const result = { added: [], replaced: [], removed: [], unchanged: [], kept: [] };
71
+ for (const [key, hash] of Object.entries(source)) {
72
+ if (!Object.hasOwn(target, key)) result.added.push(key);
73
+ else if (target[key] === hash) result.unchanged.push(key);
74
+ else result.replaced.push(key);
75
+ }
76
+ for (const key of Object.keys(target)) if (!Object.hasOwn(source, key)) result.kept.push(key);
77
+ for (const list of Object.values(result)) list.sort();
78
+ return result;
79
+ }
80
+
81
+ const emptyPlus = () => ({ messages: { total: 0, added: 0, replaced: 0, unchanged: 0 },
82
+ presets: "none", visibility: "none", autoReply: "none", autoReplyWaits: false });
83
+
84
+ /**
85
+ * What the backup's Plus data does here. Message overrides are counted; presets,
86
+ * visibility and Auto Reply are each added, replaced, unchanged or none (the
87
+ * backup lacks it, so the current value stays). Auto Reply is account data: it
88
+ * waits for the matching account to pair and is never written by the restore.
89
+ */
90
+ function plusPlan(source = {}, current = {}) {
91
+ const result = emptyPlus();
92
+ const status = (name) => !Object.hasOwn(source, name) ? "none" : !Object.hasOwn(current, name) ? "added" :
93
+ source[name] === current[name] ? "unchanged" : "replaced";
94
+ for (const name of Object.keys(source)) {
95
+ if (!name.startsWith("cfg:") || ["cfg:presets", "cfg:visibility"].includes(name)) continue;
96
+ const state = status(name);
97
+ result.messages.total += 1;
98
+ result.messages[state] += 1;
99
+ }
100
+ result.presets = status("cfg:presets");
101
+ result.visibility = status("cfg:visibility");
102
+ result.autoReply = status("acct:autoReply");
103
+ result.autoReplyWaits = result.autoReply !== "none";
104
+ return result;
105
+ }
106
+ // Replacing a message override, the presets or the visibility overwrites a value this install has.
107
+ const plusReplaces = (plus) => plus.messages.replaced > 0 || plus.presets === "replaced" || plus.visibility === "replaced";
108
+
109
+ function personaChange(backupSha) {
110
+ let current = null;
111
+ try { current = digest(fs.readFileSync(dataPath("ai-persona.md"))); }
112
+ catch (error) { if (error.code !== "ENOENT") throw error; }
113
+ if (!backupSha) return current ? "kept" : "none";
114
+ if (!current) return "added";
115
+ return current === backupSha ? "unchanged" : "replaced";
116
+ }
117
+
118
+ function hasAccountData() {
119
+ for (const table of ACCOUNT_TABLES) {
120
+ if (db.prepare(`SELECT 1 AS x FROM "${table}" LIMIT 1`).get()) return true;
121
+ }
122
+ const memoryRoot = dataPath("memory");
123
+ const walk = (folder) => {
124
+ let entries;
125
+ try { entries = fs.readdirSync(folder, { withFileTypes: true }); }
126
+ catch (error) { if (error.code === "ENOENT") return false; throw error; }
127
+ return entries.some((entry) => entry.isDirectory()
128
+ ? walk(path.join(folder, entry.name)) : entry.name.endsWith(".md"));
129
+ };
130
+ return walk(memoryRoot);
131
+ }
132
+
133
+ function waitingAccount() {
134
+ try {
135
+ return JSON.parse(fs.readFileSync(dataPath("restore", "pending", "pending.json"), "utf8")).account ?? null;
136
+ } catch (error) {
137
+ if (error.code === "ENOENT") return null;
138
+ throw error;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * @param {object} input
144
+ * @param {{settings: object, apiKeys: object} | null} input.digests source digests, null when unknown
145
+ * @param {string[]} input.apiKeyNames names of the API keys in the backup
146
+ * @param {string | null} input.personaSha sha256 of the backup's persona.md, null when absent
147
+ * @param {{lid: string|null, pn: string|null} | null} input.account the backup's WhatsApp account
148
+ */
149
+ function buildPlan({ digests, apiKeyNames = [], personaSha = null, account = null }) {
150
+ const current = currentDigests();
151
+ const exact = Boolean(digests);
152
+ const settingsPlan = exact ? compare(digests.settings, current.settings)
153
+ : { added: [], replaced: [], removed: [], unchanged: [], kept: [] };
154
+ const apiKeySource = exact ? digests.apiKeys
155
+ : Object.fromEntries(apiKeyNames.map((name) => [name, null]));
156
+ const apiKeys = compare(apiKeySource, current.apiKeys);
157
+ const persona = personaChange(personaSha);
158
+ let accountData = null;
159
+ if (account) {
160
+ const paired = readPairedAccount();
161
+ const waiting = waitingAccount();
162
+ accountData = {
163
+ replacesCurrent: Boolean(paired && accountsMatch(account, paired) && hasAccountData()),
164
+ replacesWaiting: waiting ? maskAccount(waiting) : null,
165
+ };
166
+ }
167
+ const plus = plusPlan(exact ? digests.plus : {}, current.plus);
168
+ const destructive = !exact || settingsPlan.replaced.length > 0 || apiKeys.replaced.length > 0 || plusReplaces(plus) ||
169
+ settingsPlan.removed.length > 0 || apiKeys.removed.length > 0 || changesAccess(settingsPlan) ||
170
+ persona === "replaced" || Boolean(accountData?.replacesCurrent || accountData?.replacesWaiting);
171
+ return { exact, destructive, settings: settingsPlan, apiKeys, persona, accountData, plus };
172
+ }
173
+
174
+ /**
175
+ * The plan of a restore that has run inside an open transaction: before and
176
+ * after are currentDigests() on each side of it, source the backup's digests.
177
+ * A value that changed only as a side effect (a capability guard that turns
178
+ * speech or vision off) counts as replaced, so it needs confirmation too.
179
+ */
180
+ function appliedPlan({ before, after, source, base }) {
181
+ const section = (was, now, from, effectiveWas = {}, effectiveNow = {}) => {
182
+ const result = { added: [], replaced: [], removed: [], unchanged: [], kept: [] };
183
+ const keys = new Set([...Object.keys(was), ...Object.keys(now), ...Object.keys(effectiveWas)]);
184
+ for (const key of keys) {
185
+ const had = Object.hasOwn(was, key);
186
+ const has = Object.hasOwn(now, key);
187
+ if (!Object.hasOwn(from, key)) {
188
+ // Not in the backup: any change is a side effect and replaces a value.
189
+ const moved = had !== has || was[key] !== now[key] ||
190
+ (Object.hasOwn(effectiveWas, key) && effectiveWas[key] !== effectiveNow[key]);
191
+ if (moved) (has || !had ? result.replaced : result.removed).push(key);
192
+ else if (had) result.kept.push(key);
193
+ continue;
194
+ }
195
+ if (!had) result.added.push(key);
196
+ else if (!has) result.removed.push(key);
197
+ else if (was[key] !== now[key]) result.replaced.push(key);
198
+ else result.unchanged.push(key);
199
+ }
200
+ for (const list of Object.values(result)) list.sort();
201
+ return result;
202
+ };
203
+ const settingsPlan = section(before.settings, after.settings, source.settings, before.effective, after.effective);
204
+ const apiKeys = section(before.apiKeys, after.apiKeys, source.apiKeys);
205
+ const plus = plusPlan(source.plus, before.plus);
206
+ const destructive = [settingsPlan, apiKeys].some((part) => part.replaced.length + part.removed.length > 0) ||
207
+ changesAccess(settingsPlan) || plusReplaces(plus) ||
208
+ base.persona === "replaced" || Boolean(base.accountData?.replacesCurrent || base.accountData?.replacesWaiting);
209
+ return { exact: true, destructive, settings: settingsPlan, apiKeys, persona: base.persona,
210
+ accountData: base.accountData, plus };
211
+ }
212
+
213
+ /** The plan as the panel sees it: names only, never a value or a digest. */
214
+ function publicPlan(plan) {
215
+ const names = (list) => list.map((key) => key.startsWith("setting:") ? key.slice(8) : key);
216
+ const section = (part) => ({ added: names(part.added), replaced: names(part.replaced),
217
+ removed: names(part.removed), unchanged: part.unchanged.length, kept: names(part.kept) });
218
+ return { exact: plan.exact, destructive: plan.destructive, settings: section(plan.settings),
219
+ apiKeys: section(plan.apiKeys), persona: plan.persona, accountData: plan.accountData,
220
+ plus: plan.plus ?? emptyPlus() };
221
+ }
222
+
223
+ module.exports = { digest, digestsFrom, restorableRows, currentDigests, buildPlan, appliedPlan, publicPlan };
@@ -0,0 +1,110 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const { ensureDataDir, dataPath } = require("../config/paths.cjs");
4
+ const { atomicJson, readJournal, writeJournal, clearJournal, writeOutcome } = require("./journal.cjs");
5
+ const uploads = require("./uploads.cjs");
6
+ const logger = require("../utils/logger.cjs");
7
+ const { fsyncDirectory } = require("../db/db.cjs");
8
+
9
+ function cleanupOrphans() {
10
+ const root = ensureDataDir("restore");
11
+ for (const name of fs.readdirSync(root)) {
12
+ if (/^[0-9a-f]{32}(?:\.trash)?$/.test(name))
13
+ fs.rmSync(path.join(root, name), { recursive: true, force: true });
14
+ }
15
+ fs.rmSync(dataPath("restore", "pending.next"), { recursive: true, force: true });
16
+ uploads.sweepUploads(true);
17
+ }
18
+
19
+ function recordOutcome(id, outcome) {
20
+ try { writeOutcome({ id, outcome, at: new Date().toISOString() }); }
21
+ catch { logger.error("[Backup] Could not record restore recovery outcome"); }
22
+ }
23
+
24
+ function quarantineJournal() {
25
+ try {
26
+ const folder = ensureDataDir("restore");
27
+ let timestamp = Date.now();
28
+ while (fs.existsSync(path.join(folder, `journal.invalid-${timestamp}.json`))) timestamp += 1;
29
+ fs.renameSync(dataPath("restore", "journal.json"), path.join(folder, `journal.invalid-${timestamp}.json`));
30
+ fsyncDirectory(folder);
31
+ } catch { logger.error("[Backup] Could not quarantine invalid restore journal"); }
32
+ logger.error("[Backup] Invalid restore journal");
33
+ recordOutcome(null, "journal-invalid");
34
+ }
35
+
36
+ function recover(journal) {
37
+ const restore = require("./restore.cjs");
38
+ const { id } = journal;
39
+ if (journal.step === "stage" || restore.marker() !== id) {
40
+ const pending = dataPath("restore", "pending");
41
+ const replaced = path.join(restore.stageRoot(id), "replaced");
42
+ try {
43
+ const pendingId = JSON.parse(fs.readFileSync(path.join(pending, "pending.json"), "utf8")).id;
44
+ if (pendingId === id) fs.renameSync(pending, path.join(restore.stageRoot(id), "abandoned"));
45
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
46
+ if (fs.existsSync(replaced) && !fs.existsSync(pending)) fs.renameSync(replaced, pending);
47
+ fsyncDirectory(dataPath("restore"));
48
+ fs.rmSync(restore.stageRoot(id), { recursive: true, force: true });
49
+ fs.rmSync(dataPath("restore", "pending.next"), { recursive: true, force: true });
50
+ fsyncDirectory(dataPath("restore"));
51
+ writeOutcome({ id, outcome: "interrupted-unchanged", at: new Date().toISOString() });
52
+ clearJournal();
53
+ return;
54
+ }
55
+ if (journal.step === "apply" || journal.step === "persona") {
56
+ restore.validateBeforePersona(id);
57
+ writeJournal({ op: "restore", id, step: "persona" });
58
+ restore.installPersona(id);
59
+ writeJournal({ op: "restore", id, step: "pending" });
60
+ }
61
+ restore.installPending(id);
62
+ restore.finish(id, "completed-after-restart");
63
+ }
64
+
65
+ function activationRecoveryFailure(id) {
66
+ try {
67
+ atomicJson(dataPath("restore", "last-activation.json"),
68
+ { id, status: "failed", code: "ACTIVATION_RECOVERY_FAILED", at: new Date().toISOString() });
69
+ } catch {}
70
+ logger.error("[Backup] Account activation recovery failed; refusing startup");
71
+ const error = new Error("Account activation recovery failed");
72
+ error.code = "ACTIVATION_RECOVERY_FAILED";
73
+ return error;
74
+ }
75
+
76
+ function runRestoreRecovery() {
77
+ let journal;
78
+ try { journal = readJournal(); }
79
+ catch { quarantineJournal(); return; }
80
+ const validRestore = journal?.op === "restore" &&
81
+ ["stage", "apply", "persona", "pending"].includes(journal.step);
82
+ const validActivate = journal?.op === "activate" &&
83
+ ["migrate", "files", "db", "cleanup"].includes(journal.step) &&
84
+ Array.isArray(journal.moved) && journal.moved.length <= 6 &&
85
+ journal.moved.every((entry) => entry && typeof entry === "object" &&
86
+ ["memory", "stickers", path.join("media", "schedules")].some((name) =>
87
+ (entry.from === name && entry.to === path.join("restore", journal.id, "previous", name)) ||
88
+ (entry.from === path.join("restore", "pending", "files", name) && entry.to === name)));
89
+ if (journal && (!/^[0-9a-f]{32}$/.test(journal.id) || !(validRestore || validActivate))) {
90
+ if (journal.op === "activate") throw activationRecoveryFailure(journal.id);
91
+ quarantineJournal();
92
+ return;
93
+ }
94
+ if (journal) {
95
+ try {
96
+ if (journal.op === "activate") require("./activation.cjs").recoverActivation(journal);
97
+ else recover(journal);
98
+ }
99
+ catch {
100
+ if (journal.op === "activate") throw activationRecoveryFailure(journal.id);
101
+ logger.error("[Backup] Restore recovery failed; will retry on next start");
102
+ recordOutcome(journal.id, "recovery-failed");
103
+ return;
104
+ }
105
+ }
106
+ try { cleanupOrphans(); }
107
+ catch { logger.error("[Backup] Restore cleanup failed"); }
108
+ }
109
+
110
+ module.exports = { runRestoreRecovery };