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,247 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const { DatabaseSync } = require("node:sqlite");
4
+ const { dataPath } = require("../config/paths.cjs");
5
+ const { db, migrate, fsyncDirectory } = require("../db/db.cjs");
6
+ const { markLegacyMemoryHandled } = require("../utils/memory.cjs");
7
+ const logger = require("../utils/logger.cjs");
8
+ const { readPairedAccount, accountsMatch } = require("./account.cjs");
9
+ const { ACCOUNT_TABLES, classifyTables } = require("./content.cjs");
10
+ const { atomicJson, readJournal, writeJournal, clearJournal } = require("./journal.cjs");
11
+ const extensions = require("./extensions.cjs");
12
+
13
+ const pendingRoot = () => dataPath("restore", "pending");
14
+ const outcomePath = () => dataPath("restore", "last-activation.json");
15
+ const marker = () => {
16
+ try { return JSON.parse(db.prepare("SELECT value FROM bot_settings WHERE key = 'restore:activated'").get()?.value || "null")?.id; }
17
+ catch { return null; }
18
+ };
19
+ let faultHook = null;
20
+ let faultIsCrash = true;
21
+ function setFaultHookForTest(fn, { crash = true } = {}) { faultHook = fn; faultIsCrash = crash; }
22
+ function fault(step) {
23
+ if (!faultHook) return;
24
+ try { faultHook(step); }
25
+ catch (error) { if (faultIsCrash) error.activationTestCrash = true; throw error; }
26
+ }
27
+ function outcome(id, status, code) {
28
+ atomicJson(outcomePath(), { id, status, ...(code ? { code } : {}), at: new Date().toISOString() });
29
+ }
30
+ function readLastActivation() {
31
+ try {
32
+ const { status, at } = JSON.parse(fs.readFileSync(outcomePath(), "utf8"));
33
+ return { status, at };
34
+ } catch (error) { if (error.code === "ENOENT") return null; throw error; }
35
+ }
36
+ function pending() {
37
+ try {
38
+ const value = JSON.parse(fs.readFileSync(path.join(pendingRoot(), "pending.json"), "utf8"));
39
+ if (!/^[0-9a-f]{32}$/.test(value.id)) throw new Error("Invalid pending activation id");
40
+ return value;
41
+ } catch (error) { if (error.code === "ENOENT") return null; throw error; }
42
+ }
43
+ function journal(id, step, moved) { writeJournal({ op: "activate", id, step, moved }); }
44
+ function ensureDurableDirectory(folder, filesystem = fs) {
45
+ const root = dataPath();
46
+ const relative = path.relative(root, folder);
47
+ if (path.isAbsolute(relative) || relative.split(path.sep).includes(".."))
48
+ throw new Error("Activation directory is outside the data directory");
49
+ let parent = root;
50
+ for (const part of relative.split(path.sep).filter(Boolean)) {
51
+ const next = path.join(parent, part);
52
+ if (!filesystem.existsSync(next)) {
53
+ filesystem.mkdirSync(next, { mode: 0o700 });
54
+ fsyncDirectory(parent, filesystem);
55
+ }
56
+ parent = next;
57
+ }
58
+ }
59
+ function unsafeActivationError() {
60
+ const error = new Error("Account activation needs recovery before WhatsApp can run");
61
+ error.code = "ACTIVATION_UNSAFE";
62
+ return error;
63
+ }
64
+ function move(id, step, moved, from, to) {
65
+ // An intent is durable before rename. Recovery checks which side exists.
66
+ moved.push({ from: path.relative(dataPath(), from), to: path.relative(dataPath(), to) });
67
+ journal(id, step, moved);
68
+ ensureDurableDirectory(path.dirname(to));
69
+ fs.renameSync(from, to);
70
+ fsyncDirectory(path.dirname(from));
71
+ fsyncDirectory(path.dirname(to));
72
+ }
73
+ function undoMoves(moved) {
74
+ for (const entry of [...moved].reverse()) {
75
+ const from = dataPath(entry.from);
76
+ const to = dataPath(entry.to);
77
+ if (fs.existsSync(to) && !fs.existsSync(from)) {
78
+ ensureDurableDirectory(path.dirname(from));
79
+ fault("undo-rename");
80
+ fs.renameSync(to, from);
81
+ fsyncDirectory(path.dirname(to));
82
+ fsyncDirectory(path.dirname(from));
83
+ }
84
+ }
85
+ }
86
+ function finishActivation(id) {
87
+ // A committed marker makes cleanup safe to repeat after a crash.
88
+ fs.rmSync(dataPath("restore", id, "previous"), { recursive: true, force: true });
89
+ fs.rmSync(pendingRoot(), { recursive: true, force: true });
90
+ fs.rmSync(dataPath("restore", id), { recursive: true, force: true });
91
+ clearJournal();
92
+ outcome(id, "activated");
93
+ }
94
+ function recoverActivation(journalValue) {
95
+ if (marker() === journalValue.id) {
96
+ finishActivation(journalValue.id);
97
+ } else {
98
+ undoMoves(journalValue.moved);
99
+ clearJournal();
100
+ outcome(journalValue.id, "failed", "interrupted");
101
+ }
102
+ }
103
+ function columns(database, schema, table) {
104
+ return database.prepare(`PRAGMA ${schema}.table_info("${table}")`).all()
105
+ .map(({ name, type, notnull, dflt_value, pk }) => ({ name, type, notnull, dflt_value, pk }));
106
+ }
107
+ function replaceTables(id) {
108
+ db.prepare("ATTACH DATABASE ? AS pending").run(path.join(pendingRoot(), "levix.db"));
109
+ let begun = false;
110
+ try {
111
+ for (const table of ACCOUNT_TABLES) {
112
+ if (JSON.stringify(columns(db, "main", table)) !== JSON.stringify(columns(db, "pending", table)))
113
+ throw new Error(`Activation schema mismatch: ${table}`);
114
+ }
115
+ db.exec("PRAGMA synchronous = FULL");
116
+ db.exec("BEGIN IMMEDIATE");
117
+ begun = true;
118
+ db.exec("PRAGMA defer_foreign_keys = ON");
119
+ // Before the first account-table write, so in-flight work from the previous
120
+ // account cannot commit into the rows this transaction is about to replace.
121
+ require("../db/store.cjs").advanceAccountEpoch();
122
+ // accountReset wipes the extension's account rows. The ones this install holds are put back below
123
+ // when the backup has no value for them: a restore never deletes what the backup lacks.
124
+ const heldAccount = extensions.validRows(db).filter((row) => extensions.kindOf(row.key) === "acct");
125
+ require("../extensions/host.cjs").host.accountReset("restore");
126
+ // Delete children first, then insert parents first. Deferred constraints
127
+ // cover references between account tables until COMMIT.
128
+ for (const table of [...ACCOUNT_TABLES].reverse()) db.exec(`DELETE FROM main."${table}"`);
129
+ for (const table of ACCOUNT_TABLES) {
130
+ const names = columns(db, "main", table).map(({ name }) => `"${name.replaceAll('"', '""')}"`).join(", ");
131
+ db.exec(`INSERT INTO main."${table}" (${names}) SELECT ${names} FROM pending."${table}"`);
132
+ }
133
+ // Plus account data: only the allowlisted keys, never plus:*, never a delete.
134
+ const upsert = db.prepare(
135
+ "INSERT INTO main.bot_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
136
+ const incoming = extensions.validRows(db, "pending").filter((row) => extensions.kindOf(row.key) === "acct");
137
+ for (const row of incoming) upsert.run(row.key, JSON.stringify(row.parsed));
138
+ for (const row of heldAccount) if (!incoming.some((item) => item.key === row.key)) upsert.run(row.key, row.value);
139
+ // Replay metadata is not in backups. Require fresh operator opt-in after restore.
140
+ db.exec("UPDATE reaction_rules SET enabled = 0");
141
+ db.prepare("INSERT OR REPLACE INTO bot_settings(key,value) VALUES('reaction:enabled','false')").run();
142
+ // JSON text, same as saveBotSetting, so a later read is a plain string.
143
+ db.prepare(
144
+ "INSERT OR REPLACE INTO bot_settings(key,value) VALUES('reaction:automation-revision',?)",
145
+ ).run(JSON.stringify(require("node:crypto").randomUUID()));
146
+ for (const table of ["reaction_events", "reaction_state", "reaction_invalidations", "reaction_executions", "reaction_budgets"])
147
+ db.exec(`DELETE FROM ${table}`);
148
+ db.prepare("INSERT OR REPLACE INTO bot_settings (key, value) VALUES ('restore:activated', ?)")
149
+ .run(JSON.stringify({ id }));
150
+ fault("db-before-commit");
151
+ db.exec("COMMIT");
152
+ begun = false;
153
+ } catch (error) {
154
+ if (begun) { try { db.exec("ROLLBACK"); } catch {} }
155
+ throw error;
156
+ } finally {
157
+ try { db.exec("PRAGMA synchronous = NORMAL"); }
158
+ finally { db.exec("DETACH DATABASE pending"); }
159
+ }
160
+ }
161
+ function activatePendingIfMatching(resetAccountCaches = () => {}) {
162
+ try {
163
+ const existing = readJournal();
164
+ if (existing?.op === "activate") throw unsafeActivationError();
165
+ if (existing) return false;
166
+ } catch { throw unsafeActivationError(); }
167
+ let value;
168
+ try { value = pending(); }
169
+ catch { logger.error("[Backup] Invalid pending activation metadata"); return false; }
170
+ if (!value) return false;
171
+ const { id } = value;
172
+ let matches = false;
173
+ try { matches = accountsMatch(value.account, readPairedAccount()); }
174
+ catch {
175
+ logger.error("[Backup] Could not read paired account for activation");
176
+ try { outcome(id, "failed", "IO"); } catch {}
177
+ return false;
178
+ }
179
+ if (!matches) {
180
+ try { outcome(id, "waiting"); }
181
+ catch { logger.error("[Backup] Could not record waiting activation"); }
182
+ return false;
183
+ }
184
+ const moved = [];
185
+ try {
186
+ journal(id, "migrate", moved);
187
+ const copy = new DatabaseSync(path.join(pendingRoot(), "levix.db"));
188
+ try {
189
+ migrate(copy);
190
+ require("./restore.cjs").expectedSchema(copy);
191
+ classifyTables(copy);
192
+ }
193
+ finally { copy.close(); }
194
+ fault("migrate");
195
+ require("../../scheduler.cjs").bumpScheduleGeneration();
196
+ journal(id, "files", moved);
197
+ ensureDurableDirectory(dataPath("restore", id, "previous", "media"));
198
+ for (const name of ["memory", "stickers", "media/schedules"]) {
199
+ const live = dataPath(...name.split("/"));
200
+ const source = path.join(pendingRoot(), "files", name);
201
+ const previous = dataPath("restore", id, "previous", name);
202
+ if (!fs.existsSync(source)) ensureDurableDirectory(source);
203
+ if (fs.existsSync(live)) move(id, "files", moved, live, previous);
204
+ fault(`files:${name}:previous`);
205
+ move(id, "files", moved, source, live);
206
+ fault(`files:${name}:live`);
207
+ }
208
+ markLegacyMemoryHandled(dataPath("memory"));
209
+ fault("files");
210
+ journal(id, "db", moved);
211
+ replaceTables(id);
212
+ fault("db-committed");
213
+ try { resetAccountCaches(); }
214
+ catch { logger.error("[Backup] Could not reset account caches after activation"); }
215
+ extensions.reloadHost();
216
+ journal(id, "cleanup", moved);
217
+ finishActivation(id);
218
+ return true;
219
+ } catch (error) {
220
+ // A test crash models a dead process: startup recovery owns this journal.
221
+ if (error.activationTestCrash) return false;
222
+ if (marker() === id) {
223
+ try { resetAccountCaches(); }
224
+ catch { logger.error("[Backup] Could not reset account caches after activation"); }
225
+ try { recoverActivation({ id, moved }); }
226
+ catch { logger.error("[Backup] Activation cleanup will retry on restart"); }
227
+ return true;
228
+ }
229
+ try { undoMoves(moved); }
230
+ catch {
231
+ try { outcome(id, "failed", "ROLLBACK_FAILED"); } catch {}
232
+ throw unsafeActivationError();
233
+ }
234
+ try { clearJournal(); }
235
+ catch {
236
+ try { outcome(id, "failed", "ROLLBACK_FAILED"); } catch {}
237
+ throw unsafeActivationError();
238
+ }
239
+ try { outcome(id, "failed", error.code || "IO"); }
240
+ catch { logger.error("[Backup] Could not record failed activation outcome"); }
241
+ logger.error({ code: error.code || "IO" }, "[Backup] Account activation failed");
242
+ return false;
243
+ }
244
+ }
245
+
246
+ module.exports = { activatePendingIfMatching, recoverActivation, readLastActivation,
247
+ setFaultHookForTest, ensureDurableDirectory };
@@ -0,0 +1,36 @@
1
+ // Shared creation/restore classification. A new table must be classified before export.
2
+ const { SETTING_KEYS, SECRET_SETTING_KEYS } = require("../config/settings.cjs");
3
+ const { BackupError } = require("./format.cjs");
4
+
5
+ const ACCOUNT_TABLES = Object.freeze([
6
+ "user_metadata", "lid_mapping", "group_directory", "group_settings", "warnings",
7
+ "todos", "notes", "debts", "ai_history", "schedules", "moderation_flags",
8
+ "auto_delete_rules", "auto_delete_log", "sticker_owners", "stickers",
9
+ "sticker_packs", "sticker_pack_items", "reaction_rules",
10
+ ]);
11
+ const EXCLUDED_TABLES = Object.freeze(["baileys_auth", "qr_codes", "moderation_applied", "forward_scores", "reaction_events", "reaction_state", "reaction_invalidations", "reaction_executions", "reaction_budgets"]);
12
+ const DEVICE_SETTING_KEYS = Object.freeze([
13
+ "port", "bind_address", "trust_proxy", "public_domain", "dashboard_origin", "ffmpeg_path",
14
+ ]);
15
+ const COMMAND_TABLE_KEYS = Object.freeze([
16
+ "prefix", "command_permissions", "command_aliases", "disabled_commands",
17
+ ]);
18
+ const RESTORABLE_SETTING_KEYS = Object.freeze(SETTING_KEYS.filter(
19
+ (key) => !SECRET_SETTING_KEYS.includes(key) && !DEVICE_SETTING_KEYS.includes(key),
20
+ ));
21
+ const RESTORABLE_BOT_KEYS = Object.freeze([
22
+ ...RESTORABLE_SETTING_KEYS.map((key) => `setting:${key}`), ...COMMAND_TABLE_KEYS,
23
+ ]);
24
+
25
+ function classifyTables(db) {
26
+ const known = new Set(["bot_settings", ...ACCOUNT_TABLES, ...EXCLUDED_TABLES]);
27
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
28
+ const unknown = tables.map((row) => row.name).filter((name) => !known.has(name));
29
+ if (unknown.length) {
30
+ throw new BackupError("UNCLASSIFIED_TABLE", `Unclassified backup table: ${unknown.join(", ")}`);
31
+ }
32
+ return tables.map((row) => row.name);
33
+ }
34
+
35
+ module.exports = { ACCOUNT_TABLES, EXCLUDED_TABLES, DEVICE_SETTING_KEYS,
36
+ COMMAND_TABLE_KEYS, RESTORABLE_SETTING_KEYS, RESTORABLE_BOT_KEYS, classifyTables };
@@ -0,0 +1,280 @@
1
+ const crypto = require("node:crypto");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const { DatabaseSync } = require("node:sqlite");
5
+ const { db } = require("../db/db.cjs");
6
+ const { writeSecretFreeCopy, verifySecretFreeCopy } = require("../db/copy.cjs");
7
+ const settings = require("../config/settings.cjs");
8
+ const { dataPath, ensureDataDir } = require("../config/paths.cjs");
9
+ const memory = require("../utils/memory.cjs");
10
+ const library = require("../stickers/library.cjs");
11
+ const { scheduleMediaPath } = require("../../scheduler.cjs");
12
+ const { BackupError, writeBackup, validatePassword } = require("./format.cjs");
13
+ const logger = require("../utils/logger.cjs");
14
+ const { readPairedAccount, maskAccount } = require("./account.cjs");
15
+ const { ACCOUNT_TABLES, EXCLUDED_TABLES, RESTORABLE_BOT_KEYS, classifyTables } = require("./content.cjs");
16
+ const { digestsFrom, restorableRows } = require("./plan.cjs");
17
+ const extensions = require("./extensions.cjs");
18
+
19
+ const EXCLUDED_CATEGORIES = Object.freeze([
20
+ "WhatsApp credentials", "panel password and sessions", "recovery email", "device settings",
21
+ "temporary moderation and forwarding data", "device files and logs",
22
+ ]);
23
+ const shaRe = /^[0-9a-f]{64}$/;
24
+ const mediaIdRe = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
25
+ let captureHookForTest;
26
+
27
+ function setCaptureHookForTest(fn) { captureHookForTest = fn; }
28
+
29
+ function countsOf(database, paired, memoryFiles, apiKeys) {
30
+ const count = (sql) => Number(database.prepare(sql).get().n);
31
+ const keys = RESTORABLE_BOT_KEYS;
32
+ const settingsCount = Number(database.prepare(
33
+ `SELECT count(*) AS n FROM bot_settings WHERE key IN (${keys.map(() => "?").join(",")})`,
34
+ ).get(...keys).n);
35
+ return {
36
+ settings: settingsCount, apiKeys,
37
+ schedules: paired ? count("SELECT count(*) AS n FROM schedules") : 0,
38
+ groups: paired ? count("SELECT count(*) AS n FROM group_settings") : 0,
39
+ roles: paired ? count("SELECT count(*) AS n FROM user_metadata WHERE is_owner OR is_admin") : 0,
40
+ conversations: paired ? count("SELECT count(DISTINCT chat_id) AS n FROM ai_history") : 0,
41
+ memoryFiles: paired ? memoryFiles : 0,
42
+ stickers: paired ? count("SELECT count(*) AS n FROM stickers") : 0,
43
+ packs: paired ? count("SELECT count(*) AS n FROM sticker_packs") : 0,
44
+ };
45
+ }
46
+
47
+ function secretValues() {
48
+ const result = {};
49
+ for (const key of settings.SECRET_SETTING_KEYS) {
50
+ if (settings.sourceOf(key) === "dashboard") {
51
+ const value = settings.get(key);
52
+ if (value) result[key] = value;
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+
58
+ function copyPrivate(source, destination, stable) {
59
+ const stat = fs.lstatSync(source);
60
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new BackupError("IO", "Invalid backup source file");
61
+ fs.mkdirSync(path.dirname(destination), { recursive: true, mode: 0o700 });
62
+ // The private staging directory protects linked files. Never chmod a link.
63
+ if (stable) {
64
+ try { fs.linkSync(source, destination); return stat.size; }
65
+ catch { /* Cross-device and restricted filesystems use a private copy. */ }
66
+ }
67
+ fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL);
68
+ fs.chmodSync(destination, 0o600);
69
+ return stat.size;
70
+ }
71
+
72
+ function memorySources() {
73
+ const root = memory.ROOT;
74
+ const result = [];
75
+ const global = path.join(root, "global.md");
76
+ if (fs.existsSync(global)) result.push([global, "memory/global.md"]);
77
+ const chats = path.join(root, "chats");
78
+ if (fs.existsSync(chats)) {
79
+ for (const name of fs.readdirSync(chats).sort()) {
80
+ if (name.startsWith(".") || !name.endsWith(".md")) continue;
81
+ if (!mediaIdRe.test(name)) throw new BackupError("IO", "Invalid memory file name");
82
+ result.push([path.join(chats, name), `memory/chats/${name}`]);
83
+ }
84
+ }
85
+ return result;
86
+ }
87
+
88
+ function referencedFiles(database, paired) {
89
+ if (!paired) return [];
90
+ const files = memorySources().map(([source, entry]) => ({ source, entry, kind: "memory", stable: false }));
91
+ const shas = database.prepare("SELECT DISTINCT sha256 FROM stickers ORDER BY sha256").all();
92
+ for (const { sha256: sha } of shas) {
93
+ if (!shaRe.test(sha)) throw new BackupError("IO", "Invalid sticker reference");
94
+ const webp = library.webpPath(sha);
95
+ if (fs.existsSync(webp)) files.push({ source: webp,
96
+ entry: `stickers/${sha.slice(0, 2)}/${sha}.webp`, kind: "sticker", stable: true });
97
+ const thumb = library.thumbPath(sha);
98
+ if (fs.existsSync(thumb)) files.push({ source: thumb,
99
+ entry: `stickers/${sha.slice(0, 2)}/${sha}.thumb.webp`, kind: "sticker", stable: true });
100
+ }
101
+ for (const { id } of database.prepare("SELECT id FROM schedules WHERE media IS NOT NULL AND media != '' ORDER BY id").all()) {
102
+ if (!mediaIdRe.test(id)) throw new BackupError("IO", "Invalid schedule media reference");
103
+ const media = scheduleMediaPath(id);
104
+ if (fs.existsSync(media)) files.push({ source: media,
105
+ entry: `media/schedules/${id}`, kind: "schedule-media", stable: true });
106
+ }
107
+ return files;
108
+ }
109
+
110
+ function rawForbiddenValues() {
111
+ const keys = ["auth:password", "auth:recovery-email", "secret:session",
112
+ ...settings.SECRET_SETTING_KEYS.map((key) => `setting:${key}`)];
113
+ const found = [];
114
+ const query = db.prepare("SELECT value FROM bot_settings WHERE key = ?");
115
+ for (const key of keys) {
116
+ const value = query.get(key)?.value;
117
+ if (value !== null && value !== undefined && String(value).length)
118
+ found.push({ category: key.startsWith("setting:") ? "secret setting" : key, bytes: Buffer.from(String(value)) });
119
+ }
120
+ const creds = db.prepare("SELECT value FROM baileys_auth WHERE key = 'creds'").get()?.value;
121
+ if (creds) found.push({ category: "pairing credentials", bytes: Buffer.from(String(creds)) });
122
+ return found;
123
+ }
124
+
125
+ function rejectForbidden(bytes, forbidden) {
126
+ for (const item of forbidden) {
127
+ if (bytes.includes(item.bytes)) {
128
+ logger.warn({ category: item.category }, "[Backup] excluded value found in backup content");
129
+ throw new BackupError("SECRET_FOUND", `Backup contains ${item.category}`);
130
+ }
131
+ }
132
+ }
133
+
134
+ async function scanTextFile(file, forbidden) {
135
+ if (!forbidden.length) return;
136
+ const overlap = Math.max(...forbidden.map((item) => item.bytes.length)) - 1;
137
+ let tail = Buffer.alloc(0);
138
+ for await (const chunk of fs.createReadStream(file, { highWaterMark: 65536 })) {
139
+ const bytes = Buffer.concat([tail, chunk]);
140
+ rejectForbidden(bytes, forbidden);
141
+ tail = bytes.subarray(Math.max(0, bytes.length - overlap));
142
+ }
143
+ }
144
+
145
+ async function scanSecrets(filtered, files, stage, forbidden) {
146
+ if (!forbidden.length) return;
147
+ const database = new DatabaseSync(filtered, { readOnly: true });
148
+ try {
149
+ let rows = 0;
150
+ for (const table of classifyTables(database)) {
151
+ // classifyTables restricts names to code-owned table names.
152
+ for (const row of database.prepare(`SELECT * FROM "${table}"`).iterate()) {
153
+ for (const value of Object.values(row)) {
154
+ if (typeof value === "string") rejectForbidden(Buffer.from(value), forbidden);
155
+ else if (value instanceof Uint8Array) rejectForbidden(Buffer.from(value), forbidden);
156
+ }
157
+ if (++rows % 128 === 0) await new Promise((resolve) => setImmediate(resolve));
158
+ }
159
+ }
160
+ } finally { database.close(); }
161
+ for (const file of files) {
162
+ if (file.kind === "persona" || file.kind === "memory")
163
+ await scanTextFile(path.join(stage, file.entry), forbidden);
164
+ }
165
+ }
166
+
167
+ async function entryFor(source, entry, kind) {
168
+ const hash = crypto.createHash("sha256");
169
+ if (Buffer.isBuffer(source)) return { path: entry, kind, size: source.length,
170
+ sha256: hash.update(source).digest("hex"), source };
171
+ let size = 0;
172
+ for await (const chunk of fs.createReadStream(source, { highWaterMark: 65536 })) {
173
+ hash.update(chunk);
174
+ size += chunk.length;
175
+ }
176
+ return { path: entry, kind, size, sha256: hash.digest("hex"), source };
177
+ }
178
+
179
+ // No await: the DB snapshot and every source file are captured in one event-loop turn.
180
+ function capture(stage, statfs = fs.statfsSync) {
181
+ const paired = readPairedAccount();
182
+ classifyTables(db);
183
+ const files = referencedFiles(db, Boolean(paired));
184
+ const persona = dataPath("ai-persona.md");
185
+ if (fs.existsSync(persona)) files.unshift({ source: persona, entry: "persona.md", kind: "persona", stable: false });
186
+ const sourceBytes = files.reduce((sum, item) => sum + fs.statSync(item.source).size, 0);
187
+ const secrets = secretValues();
188
+ const secretsBytes = Object.keys(secrets).length ? Buffer.byteLength(JSON.stringify({ settings: secrets })) : 0;
189
+ const databaseBytes = fs.statSync(dataPath("levix.db")).size +
190
+ (fs.statSync(dataPath("levix.db-wal"), { throwIfNoEntry: false })?.size || 0);
191
+ const space = statfs(dataPath());
192
+ const outputBytes = Math.ceil((databaseBytes + sourceBytes + secretsBytes) * 1.01);
193
+ const needed = databaseBytes + sourceBytes + outputBytes + 64 * 1024 * 1024;
194
+ if (Number(space.bavail) * Number(space.bsize) < needed) throw new BackupError("NO_SPACE", "Not enough space for backup");
195
+ fs.mkdirSync(stage, { recursive: true, mode: 0o700 });
196
+ const filtered = path.join(stage, "filtered.db");
197
+ const omitTables = [...EXCLUDED_TABLES, ...(paired ? [] : ACCOUNT_TABLES)];
198
+ // Plus config always; Plus account data only with the account it belongs to.
199
+ // Values that would fail validation on restore stay out instead of poisoning the file.
200
+ const plusKeys = new Set(extensions.validRows(db).map((row) => row.key)
201
+ .filter((key) => extensions.kindOf(key) === "cfg" || paired));
202
+ const keepBotKey = (key) => RESTORABLE_BOT_KEYS.includes(key) || plusKeys.has(key);
203
+ const allowBotKey = (key) => plusKeys.has(key);
204
+ try {
205
+ writeSecretFreeCopy(dataPath("levix.db"), filtered, { omitTables, keepBotKey, allowBotKey });
206
+ captureHookForTest?.("after-db-copy", stage);
207
+ const source = new DatabaseSync(dataPath("levix.db"), { readOnly: true });
208
+ try {
209
+ verifySecretFreeCopy(filtered, source, {
210
+ expectedVersion: source.prepare("PRAGMA user_version").get().user_version,
211
+ omitTables, keepBotKey, allowBotKey,
212
+ });
213
+ } finally { source.close(); }
214
+ }
215
+ catch (error) {
216
+ const busy = /busy|locked|transaction/i.test(String(error.message));
217
+ throw new BackupError(busy ? "BUSY" : "IO", "Backup snapshot unavailable");
218
+ }
219
+ for (const file of files) copyPrivate(file.source, path.join(stage, file.entry), file.stable);
220
+ captureHookForTest?.("after-files", stage);
221
+ const database = new DatabaseSync(filtered, { readOnly: true });
222
+ try {
223
+ return { paired, files, forbidden: rawForbiddenValues(), secrets, filtered,
224
+ digests: digestsFrom(restorableRows(database), secrets),
225
+ schema: database.prepare("PRAGMA user_version").get().user_version,
226
+ counts: countsOf(database, Boolean(paired), files.filter((f) => f.kind === "memory").length,
227
+ Object.keys(secrets).length) };
228
+ } finally { database.close(); }
229
+ }
230
+
231
+ function describeBackupContents() {
232
+ classifyTables(db);
233
+ const account = readPairedAccount();
234
+ const apiKeys = Object.keys(secretValues()).sort();
235
+ const files = referencedFiles(db, Boolean(account));
236
+ return { counts: countsOf(db, Boolean(account), files.filter((f) => f.kind === "memory").length, apiKeys.length),
237
+ apiKeys, paired: Boolean(account), maskedAccount: maskAccount(account), excluded: EXCLUDED_CATEGORIES };
238
+ }
239
+
240
+ // kdf and statfs are internal test hooks; panel jobs always use production defaults.
241
+ async function createBackup({ password, onProgress, kdf, statfs } = {}) {
242
+ validatePassword(password);
243
+ const id = crypto.randomBytes(16).toString("hex");
244
+ const token = crypto.randomBytes(32).toString("hex");
245
+ const base = ensureDataDir("tmp", "backup");
246
+ const stage = path.join(base, id);
247
+ const out = path.join(ensureDataDir("tmp", "backup", "exports"), `${token}.levixbak`);
248
+ try {
249
+ onProgress?.({ phase: "capture", bytes: 0, totalBytes: 0 });
250
+ let snapshot;
251
+ for (let attempt = 0; attempt < 5; attempt++) {
252
+ try { snapshot = capture(stage, statfs); break; }
253
+ catch (error) {
254
+ if (error?.code !== "BUSY") throw error;
255
+ fs.rmSync(stage, { recursive: true, force: true });
256
+ if (attempt === 4) throw error;
257
+ await new Promise((resolve) => setTimeout(resolve, 100));
258
+ }
259
+ }
260
+ onProgress?.({ phase: "filter", bytes: 0, totalBytes: 0 });
261
+ await scanSecrets(snapshot.filtered, snapshot.files, stage, snapshot.forbidden);
262
+ const apiKeys = Object.keys(snapshot.secrets).sort();
263
+ const sources = [await entryFor(snapshot.filtered, "db/levix.db", "db")];
264
+ if (apiKeys.length) sources.push(await entryFor(Buffer.from(JSON.stringify({ settings: snapshot.secrets })), "secrets.json", "secrets"));
265
+ for (const file of snapshot.files) sources.push(await entryFor(path.join(stage, file.entry), file.entry, file.kind));
266
+ const now = new Date();
267
+ const fileName = `levix-backup-${now.toISOString().replace(/[-:]/g, "").slice(0, 15).replace("T", "-")}.levixbak`;
268
+ const manifest = { format: "levix-backup-manifest", version: 1, created: now.toISOString(),
269
+ app: require("../../package.json").version, schema: snapshot.schema,
270
+ platform: `${process.platform}-${process.arch}`, account: snapshot.paired,
271
+ apiKeys, counts: snapshot.counts, digests: snapshot.digests };
272
+ const written = await writeBackup({ outPath: out, password, manifest, entries: sources, kdf, onProgress });
273
+ return { token, fileName, path: out, size: written.size };
274
+ } catch (error) {
275
+ fs.rmSync(out, { force: true });
276
+ throw error instanceof BackupError ? error : new BackupError("IO", "Backup creation failed");
277
+ } finally { fs.rmSync(stage, { recursive: true, force: true }); }
278
+ }
279
+
280
+ module.exports = { createBackup, describeBackupContents, setCaptureHookForTest };
@@ -0,0 +1,101 @@
1
+ // The Levix Plus data a backup may carry. An explicit allowlist: the message
2
+ // overrides, the presets and the visibility choices (settings, restored with
3
+ // them) and the Auto Reply account data (restored only after the same WhatsApp
4
+ // account is paired). Every `plus:*` key and every other `ext:*` key stays out.
5
+ const { isCustomizable } = require("../extensions/templateKeys.cjs");
6
+ const { BackupError } = require("./format.cjs");
7
+
8
+ const EXT_ID = "levix-plus";
9
+ const CFG_PREFIX = `ext:${EXT_ID}:cfg:`;
10
+ const ACCT_PREFIX = `ext:${EXT_ID}:acct:`;
11
+ const CFG_FIXED = Object.freeze(["presets", "visibility"]);
12
+ const ACCT_NAMES = Object.freeze(["autoReply"]);
13
+ const NAME_RE = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
14
+ // Same limits as the extension storage in store.cjs.
15
+ const VALUE_MAX_BYTES = 64 * 1024;
16
+ const MAX_NAMES = 200;
17
+ const MAX_DEPTH = 8;
18
+ const DANGEROUS = Object.freeze(["__proto__", "constructor", "prototype"]);
19
+
20
+ /** "cfg" | "acct" | null. Null for anything that is not an allowlisted Plus key. */
21
+ function kindOf(key) {
22
+ if (typeof key !== "string") return null;
23
+ if (key.startsWith(CFG_PREFIX)) {
24
+ const name = key.slice(CFG_PREFIX.length);
25
+ if (!NAME_RE.test(name)) return null;
26
+ return CFG_FIXED.includes(name) || isCustomizable(name) ? "cfg" : null;
27
+ }
28
+ if (key.startsWith(ACCT_PREFIX)) return ACCT_NAMES.includes(key.slice(ACCT_PREFIX.length)) ? "acct" : null;
29
+ return null;
30
+ }
31
+ const isRestorableExtKey = (key) => kindOf(key) !== null;
32
+ /** The key without the extension prefix, e.g. `cfg:presets`. */
33
+ const shortName = (key) => key.slice(`ext:${EXT_ID}:`.length);
34
+
35
+ function refuse(message) { return new BackupError("DAMAGED", message); }
36
+
37
+ /** Parse one stored value. Throws BackupError DAMAGED unless it is a safe plain object. */
38
+ function validateExtValue(raw) {
39
+ if (typeof raw !== "string" || Buffer.byteLength(raw, "utf8") > VALUE_MAX_BYTES)
40
+ throw refuse("Invalid extension value");
41
+ let parsed;
42
+ try { parsed = JSON.parse(raw); } catch { throw refuse("Invalid extension value"); }
43
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw refuse("Invalid extension value");
44
+ const stack = [[parsed, 1]];
45
+ while (stack.length) {
46
+ const [value, depth] = stack.pop();
47
+ if (depth > MAX_DEPTH) throw refuse("Invalid extension value");
48
+ for (const [name, child] of Array.isArray(value) ? value.entries() : Object.entries(value)) {
49
+ if (!Array.isArray(value) && DANGEROUS.includes(name)) throw refuse("Invalid extension value");
50
+ if (child && typeof child === "object") stack.push([child, depth + 1]);
51
+ }
52
+ }
53
+ return parsed;
54
+ }
55
+
56
+ /** The stored text a value gets when written back, so digests compare by content. */
57
+ function canonicalValue(raw) {
58
+ try { return JSON.stringify(JSON.parse(raw)); } catch { return String(raw); }
59
+ }
60
+
61
+ /** Allowlisted rows in `schema`.bot_settings (value null when over the size limit). */
62
+ function allowedRows(database, schema = "main") {
63
+ if (schema !== "main" && schema !== "pending") throw new Error("Invalid schema name");
64
+ const prefix = `ext:${EXT_ID}:`;
65
+ return database.prepare(`SELECT key,
66
+ CASE WHEN length(CAST(value AS BLOB)) <= ${VALUE_MAX_BYTES} THEN value ELSE NULL END AS value
67
+ FROM ${schema}.bot_settings WHERE key >= ? AND key < ?`).all(prefix, `${prefix}\uFFFF`)
68
+ .filter((row) => isRestorableExtKey(row.key));
69
+ }
70
+
71
+ /** Allowlisted rows whose value passes validateExtValue; the rest are dropped. */
72
+ function validRows(database, schema = "main") {
73
+ const result = [];
74
+ for (const { key, value } of allowedRows(database, schema)) {
75
+ try { result.push({ key, value, parsed: validateExtValue(value) }); } catch { /* skipped */ }
76
+ }
77
+ return result;
78
+ }
79
+
80
+ /** Refuse a staged database that holds any other ext: key or an invalid or too many Plus values. */
81
+ function assertStagedExtensions(database, keys) {
82
+ const counts = { cfg: 0, acct: 0 };
83
+ for (const key of keys) {
84
+ const kind = kindOf(key);
85
+ if (!kind) throw refuse("Backup database holds excluded data");
86
+ if (++counts[kind] > MAX_NAMES) throw refuse("Backup database holds too many extension values");
87
+ }
88
+ if (!keys.length) return;
89
+ for (const { value } of allowedRows(database)) validateExtValue(value);
90
+ }
91
+
92
+ /** Ask the extension host to reload stored config. Best effort; never throws. */
93
+ function reloadHost() {
94
+ try {
95
+ const result = require("../extensions/host.cjs").reloadExtensions();
96
+ Promise.resolve(result).catch(() => {});
97
+ } catch { /* Plus is optional */ }
98
+ }
99
+
100
+ module.exports = { EXT_ID, VALUE_MAX_BYTES, MAX_NAMES, isRestorableExtKey, kindOf, shortName,
101
+ validateExtValue, canonicalValue, allowedRows, validRows, assertStagedExtensions, reloadHost };