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,565 @@
1
+ // Version 1 encrypted backups. The header authenticates the KDF parameters
2
+ // before any payload is opened; the final chunk flag authenticates EOF.
3
+
4
+ const crypto = require("node:crypto");
5
+ const fs = require("node:fs");
6
+ const fsp = fs.promises;
7
+ const path = require("node:path");
8
+ const { Readable } = require("node:stream");
9
+ const zlib = require("node:zlib");
10
+ const { promisify, TextDecoder } = require("node:util");
11
+
12
+ const CODES = Object.freeze([
13
+ "NOT_A_BACKUP", "UNSUPPORTED_VERSION", "BAD_HEADER", "KDF_LIMIT",
14
+ "WRONG_PASSWORD", "DAMAGED", "BAD_MANIFEST", "LIMIT", "BAD_PASSWORD",
15
+ "SOURCE_CHANGED", "BUSY", "IO",
16
+ ]);
17
+ const DEFAULT_KDF = Object.freeze({ N: 131072, r: 8, p: 1 });
18
+ const LIMITS = Object.freeze({
19
+ header: 4096, manifest: 8 * 1024 * 1024, chunk: 65536,
20
+ file: 16 * 1024 ** 3, db: 4 * 1024 ** 3, entry: 64 * 1024 ** 2,
21
+ memory: 1024 ** 2,
22
+ entries: 200000, passwordPointsMin: 12, passwordPointsMax: 1024,
23
+ passwordBytes: 4096, saltBytes: 32, kdfMinN: 32768, kdfMaxN: 262144,
24
+ maxPathSegments: 4,
25
+ });
26
+ const MAGIC = Buffer.from("LEVIXBAK");
27
+ const INNER = Buffer.from("LEVIXPL1");
28
+ const END = Buffer.from("LEVIXEND");
29
+ const TAG = 16;
30
+ const WIRE_CHUNK = LIMITS.chunk + TAG;
31
+ const scrypt = promisify(crypto.scrypt);
32
+
33
+ class BackupError extends Error {
34
+ constructor(code, message) {
35
+ super(message);
36
+ this.name = "BackupError";
37
+ this.code = code;
38
+ }
39
+ }
40
+
41
+ function fail(code, message) { throw new BackupError(code, message); }
42
+ function io(error) {
43
+ if (error instanceof BackupError) return error;
44
+ const result = new BackupError("IO", "Backup I/O failed");
45
+ result.cause = error;
46
+ return result;
47
+ }
48
+ function exactKeys(value, names, code) {
49
+ if (!value || typeof value !== "object" || Array.isArray(value) ||
50
+ Object.keys(value).some((key) => !names.includes(key)) ||
51
+ names.some((key) => !Object.hasOwn(value, key))) fail(code, "Invalid backup metadata");
52
+ }
53
+ function allowedKeys(value, names, code) {
54
+ if (!value || typeof value !== "object" || Array.isArray(value) ||
55
+ Object.keys(value).some((key) => !names.includes(key))) fail(code, "Invalid backup metadata");
56
+ }
57
+ function safeSize(value) { return Number.isSafeInteger(value) && value >= 0; }
58
+
59
+ function validatePassword(password) {
60
+ if (typeof password !== "string") fail("BAD_PASSWORD", "Invalid backup password");
61
+ const normalized = password.normalize("NFC");
62
+ const points = [...normalized].length;
63
+ if (points < LIMITS.passwordPointsMin || points > LIMITS.passwordPointsMax ||
64
+ Buffer.byteLength(normalized, "utf8") > LIMITS.passwordBytes)
65
+ fail("BAD_PASSWORD", "Invalid backup password");
66
+ return normalized;
67
+ }
68
+
69
+ function validPath(entry) {
70
+ const segments = entry.path.split("/");
71
+ const segment = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
72
+ if (segments.length > LIMITS.maxPathSegments || segments.some((s) => !segment.test(s) || s === "..")) return false;
73
+ if (entry.kind === "db") return entry.path === "db/levix.db";
74
+ if (entry.kind === "secrets") return entry.path === "secrets.json";
75
+ if (entry.kind === "persona") return entry.path === "persona.md";
76
+ if (entry.kind === "memory")
77
+ return (segments.length === 2 && segments[0] === "memory" && segments[1].endsWith(".md")) ||
78
+ (segments.length === 3 && segments[0] === "memory" && segments[1] === "chats" && segments[2].endsWith(".md"));
79
+ if (entry.kind === "schedule-media")
80
+ return segments.length === 3 && segments[0] === "media" && segments[1] === "schedules";
81
+ if (entry.kind === "sticker") {
82
+ const match = /^stickers\/([0-9a-f]{2})\/([0-9a-f]{64})(?:\.thumb)?\.webp$/.exec(entry.path);
83
+ return !!match && match[1] === match[2].slice(0, 2);
84
+ }
85
+ return false;
86
+ }
87
+
88
+ // Optional: digests of the restorable settings and API keys, so the restore
89
+ // preview can list what changes. Files from earlier v1 builds have none.
90
+ // `plus` is optional too: digests of the Levix Plus config and account rows.
91
+ function validateDigests(digests, apiKeys) {
92
+ const hasPlus = Boolean(digests) && typeof digests === "object" && Object.hasOwn(digests, "plus");
93
+ exactKeys(digests, hasPlus ? ["settings", "apiKeys", "plus"] : ["settings", "apiKeys"], "BAD_MANIFEST");
94
+ const map = (value, keyRe, limit) => value && typeof value === "object" && !Array.isArray(value) &&
95
+ Object.keys(value).length <= limit &&
96
+ Object.entries(value).every(([key, hash]) => keyRe.test(key) && typeof hash === "string" && /^[0-9a-f]{64}$/.test(hash));
97
+ if (hasPlus && !map(digests.plus, /^(cfg|acct):[A-Za-z][A-Za-z0-9._-]{0,63}$/, 400))
98
+ fail("BAD_MANIFEST", "Invalid manifest digests");
99
+ if (!map(digests.settings, /^[a-z][a-z0-9_:]{0,95}$/, 1024) || !map(digests.apiKeys, /^[a-z][a-z0-9_]{0,63}$/, 32))
100
+ fail("BAD_MANIFEST", "Invalid manifest digests");
101
+ const names = Object.keys(digests.apiKeys).sort();
102
+ if (JSON.stringify(names) !== JSON.stringify([...apiKeys].sort()))
103
+ fail("BAD_MANIFEST", "Manifest digests do not match the API key names");
104
+ }
105
+
106
+ function validateManifest(manifest) {
107
+ const required = ["format", "version", "created", "app", "schema", "platform", "account", "counts", "apiKeys", "entries"];
108
+ const hasDigests = Boolean(manifest) && typeof manifest === "object" && Object.hasOwn(manifest, "digests");
109
+ exactKeys(manifest, hasDigests ? [...required, "digests"] : required, "BAD_MANIFEST");
110
+ if (manifest.format !== "levix-backup-manifest") fail("BAD_MANIFEST", "Invalid manifest format");
111
+ if (manifest.version !== 1) fail("UNSUPPORTED_VERSION", "Unsupported manifest version");
112
+ if (typeof manifest.created !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(manifest.created) ||
113
+ Number.isNaN(Date.parse(manifest.created)) || new Date(manifest.created).toISOString() !== manifest.created)
114
+ fail("BAD_MANIFEST", "Invalid manifest date");
115
+ if (typeof manifest.app !== "string" || [...manifest.app].length > 64 ||
116
+ typeof manifest.platform !== "string" || [...manifest.platform].length > 64 ||
117
+ !safeSize(manifest.schema)) fail("BAD_MANIFEST", "Invalid manifest metadata");
118
+ if (manifest.account !== null) {
119
+ exactKeys(manifest.account, ["lid", "pn"], "BAD_MANIFEST");
120
+ const { lid, pn } = manifest.account;
121
+ if ((lid !== null && (typeof lid !== "string" || !/^\d{1,32}@lid$/.test(lid))) ||
122
+ (pn !== null && (typeof pn !== "string" || !/^\d{5,20}@s\.whatsapp\.net$/.test(pn))) ||
123
+ (lid === null && pn === null)) fail("BAD_MANIFEST", "Invalid account metadata");
124
+ }
125
+ allowedKeys(manifest.counts, ["settings", "apiKeys", "schedules", "groups", "roles", "conversations", "memoryFiles", "stickers", "packs"], "BAD_MANIFEST");
126
+ if (Object.values(manifest.counts).some((n) => !safeSize(n))) fail("BAD_MANIFEST", "Invalid manifest counts");
127
+ if (!Array.isArray(manifest.apiKeys) || manifest.apiKeys.length > 32 ||
128
+ manifest.apiKeys.some((name) => typeof name !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(name)) ||
129
+ new Set(manifest.apiKeys).size !== manifest.apiKeys.length)
130
+ fail("BAD_MANIFEST", "Invalid API key names");
131
+ if (hasDigests) validateDigests(manifest.digests, manifest.apiKeys);
132
+ if (!Array.isArray(manifest.entries)) fail("BAD_MANIFEST", "Invalid manifest entries");
133
+ if (manifest.entries.length > LIMITS.entries) fail("LIMIT", "Too many backup entries");
134
+ const paths = new Set();
135
+ let dbCount = 0;
136
+ let secretsCount = 0;
137
+ let personaCount = 0;
138
+ let total = 0;
139
+ for (const entry of manifest.entries) {
140
+ exactKeys(entry, ["path", "kind", "size", "sha256"], "BAD_MANIFEST");
141
+ if (typeof entry.path !== "string" || !validPath(entry) ||
142
+ typeof entry.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(entry.sha256) ||
143
+ !safeSize(entry.size)) fail("BAD_MANIFEST", "Invalid backup entry");
144
+ const folded = entry.path.toLowerCase();
145
+ if (paths.has(folded)) fail("BAD_MANIFEST", "Duplicate backup path");
146
+ paths.add(folded);
147
+ if (entry.size > (entry.kind === "db" ? LIMITS.db : LIMITS.entry)) fail("LIMIT", "Backup entry too large");
148
+ total += entry.size;
149
+ if (total > LIMITS.file) fail("LIMIT", "Backup payload too large");
150
+ dbCount += Number(entry.kind === "db");
151
+ secretsCount += Number(entry.kind === "secrets");
152
+ personaCount += Number(entry.kind === "persona");
153
+ }
154
+ if (dbCount !== 1 || secretsCount > 1 || personaCount > 1) fail("BAD_MANIFEST", "Invalid entry set");
155
+ }
156
+
157
+ function strictSalt(value) {
158
+ if (typeof value !== "string" || !/^[A-Za-z0-9+/]{43}=$/.test(value)) return false;
159
+ const bytes = Buffer.from(value, "base64");
160
+ return bytes.length === LIMITS.saltBytes && bytes.toString("base64") === value;
161
+ }
162
+ function validateKdf(kdf) {
163
+ exactKeys(kdf, ["name", "N", "r", "p", "salt"], "BAD_HEADER");
164
+ if (kdf.name !== "scrypt" || !strictSalt(kdf.salt)) fail("BAD_HEADER", "Invalid backup KDF");
165
+ if (!Number.isInteger(kdf.N) || kdf.N < LIMITS.kdfMinN || kdf.N > LIMITS.kdfMaxN ||
166
+ (kdf.N & (kdf.N - 1)) !== 0 || kdf.r !== 8 || kdf.p !== 1)
167
+ fail("KDF_LIMIT", "Unsupported backup KDF parameters");
168
+ }
169
+ function validateHeader(header) {
170
+ exactKeys(header, ["format", "version", "cipher", "chunk", "kdf"], "BAD_HEADER");
171
+ if (header.format !== "levix-backup") fail("BAD_HEADER", "Invalid backup format");
172
+ if (header.version !== 1) fail("UNSUPPORTED_VERSION", "Unsupported backup version");
173
+ if (header.cipher !== "aes-256-gcm" || header.chunk !== LIMITS.chunk)
174
+ fail("BAD_HEADER", "Invalid backup cipher");
175
+ validateKdf(header.kdf);
176
+ }
177
+ function parseJson(bytes, code) {
178
+ try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); }
179
+ catch { fail(code, "Invalid backup JSON"); }
180
+ }
181
+
182
+ let deriving = false;
183
+ const waiters = [];
184
+ async function deriveKeys(password, kdf) {
185
+ const normalized = validatePassword(password);
186
+ const parameters = { name: "scrypt", ...kdf };
187
+ validateKdf(parameters);
188
+ // The queue caps expensive scrypt work and its memory to one worker at a time.
189
+ if (deriving) {
190
+ if (waiters.length >= 2) fail("BUSY", "Backup key derivation busy");
191
+ await new Promise((resolve) => waiters.push(resolve));
192
+ } else deriving = true;
193
+ try {
194
+ const key = await scrypt(normalized, Buffer.from(parameters.salt, "base64"), 64, {
195
+ N: parameters.N, r: parameters.r, p: parameters.p,
196
+ maxmem: 128 * parameters.N * parameters.r + 1024 * 1024,
197
+ });
198
+ return { encKey: key.subarray(0, 32), macKey: key.subarray(32, 64) };
199
+ } finally {
200
+ if (waiters.length) waiters.shift()();
201
+ else deriving = false;
202
+ }
203
+ }
204
+ function headerBytes(header) {
205
+ const bytes = Buffer.from(JSON.stringify(header));
206
+ if (!bytes.length || bytes.length > LIMITS.header) fail("BAD_HEADER", "Invalid header length");
207
+ const length = Buffer.alloc(4);
208
+ length.writeUInt32BE(bytes.length);
209
+ return { bytes, prefix: Buffer.concat([MAGIC, length, bytes]) };
210
+ }
211
+ function headerFor(kdf, salt) {
212
+ return { format: "levix-backup", version: 1, cipher: "aes-256-gcm", chunk: LIMITS.chunk,
213
+ kdf: { name: "scrypt", N: kdf.N, r: kdf.r, p: kdf.p, salt: salt.toString("base64") } };
214
+ }
215
+ function nonce(index, final) {
216
+ const result = Buffer.alloc(12);
217
+ // Eleven bytes leave a nonce domain far beyond the 16 GiB file limit.
218
+ result.writeBigUInt64BE(BigInt(index), 3);
219
+ result[11] = Number(final);
220
+ return result;
221
+ }
222
+ function sealChunk(bytes, index, final, keys, aad) {
223
+ const cipher = crypto.createCipheriv("aes-256-gcm", keys.encKey, nonce(index, final));
224
+ cipher.setAAD(aad);
225
+ return Buffer.concat([cipher.update(bytes), cipher.final(), cipher.getAuthTag()]);
226
+ }
227
+ function openChunk(bytes, index, final, keys, aad) {
228
+ if (bytes.length < 17) fail("DAMAGED", "Truncated backup chunk");
229
+ try {
230
+ const decipher = crypto.createDecipheriv("aes-256-gcm", keys.encKey, nonce(index, final));
231
+ decipher.setAAD(aad);
232
+ decipher.setAuthTag(bytes.subarray(bytes.length - TAG));
233
+ return Buffer.concat([decipher.update(bytes.subarray(0, -TAG)), decipher.final()]);
234
+ } catch { fail("DAMAGED", "Backup chunk authentication failed"); }
235
+ }
236
+ async function readHeader(filePath) {
237
+ let handle;
238
+ try {
239
+ handle = await fsp.open(filePath, "r");
240
+ const stat = await handle.stat();
241
+ if (stat.size > LIMITS.file) fail("LIMIT", "Backup file too large");
242
+ const first = Buffer.alloc(12);
243
+ const start = await handle.read(first, 0, 12, 0);
244
+ if (start.bytesRead < 8 || !first.subarray(0, 8).equals(MAGIC)) fail("NOT_A_BACKUP", "Not a Levix backup");
245
+ if (start.bytesRead < 12) fail("DAMAGED", "Truncated backup header");
246
+ const hlen = first.readUInt32BE(8);
247
+ if (hlen < 1 || hlen > LIMITS.header) fail("BAD_HEADER", "Invalid backup header length");
248
+ if (stat.size < 12 + hlen + 32 + 17) fail("DAMAGED", "Truncated backup file");
249
+ const rest = Buffer.alloc(hlen + 32);
250
+ const got = await handle.read(rest, 0, rest.length, 12);
251
+ if (got.bytesRead !== rest.length) fail("DAMAGED", "Truncated backup header");
252
+ const header = parseJson(rest.subarray(0, hlen), "BAD_HEADER");
253
+ validateHeader(header);
254
+ return { header, prefix: Buffer.concat([first, rest.subarray(0, hlen)]),
255
+ hmac: rest.subarray(hlen), offset: 12 + hlen + 32 };
256
+ } catch (error) { throw io(error); }
257
+ finally { await handle?.close(); }
258
+ }
259
+ function verifyHeader(info, keys) {
260
+ const expected = crypto.createHmac("sha256", keys.macKey).update(info.prefix).digest();
261
+ if (!crypto.timingSafeEqual(expected, info.hmac)) fail("WRONG_PASSWORD", "Wrong backup password or changed header");
262
+ }
263
+ async function* decrypted(filePath, info, keys) {
264
+ let pending = Buffer.alloc(0);
265
+ let index = 0;
266
+ let seen = info.offset;
267
+ const input = fs.createReadStream(filePath, { start: info.offset });
268
+ try {
269
+ for await (const data of input) {
270
+ seen += data.length;
271
+ if (seen > LIMITS.file) fail("LIMIT", "Backup file too large");
272
+ pending = Buffer.concat([pending, data]);
273
+ // Hold a whole wire chunk until another byte proves it is not final.
274
+ while (pending.length > WIRE_CHUNK) {
275
+ yield openChunk(pending.subarray(0, WIRE_CHUNK), index++, false, keys, info.hmac);
276
+ pending = pending.subarray(WIRE_CHUNK);
277
+ }
278
+ }
279
+ if (pending.length < 17 || pending.length > WIRE_CHUNK) fail("DAMAGED", "Truncated backup tail");
280
+ yield openChunk(pending, index, true, keys, info.hmac);
281
+ } catch (error) { throw error instanceof BackupError ? error : io(error); }
282
+ finally { input.destroy(); }
283
+ }
284
+ function payloadStream(filePath, info, keys) {
285
+ const source = Readable.from(decrypted(filePath, info, keys));
286
+ const unzip = zlib.createGunzip();
287
+ source.on("error", (error) => unzip.destroy(error));
288
+ source.pipe(unzip);
289
+ return { source, unzip };
290
+ }
291
+ class ByteReader {
292
+ constructor(stream) {
293
+ this.iterator = stream[Symbol.asyncIterator]();
294
+ this.pending = Buffer.alloc(0);
295
+ this.count = 0;
296
+ // One output chunk may straddle the manifest boundary before its length is known.
297
+ this.limit = 20 + LIMITS.manifest + LIMITS.chunk;
298
+ this.readingManifest = true;
299
+ }
300
+ async pull() {
301
+ const next = await this.iterator.next();
302
+ if (next.done) return false;
303
+ this.pending = next.value;
304
+ this.count += this.pending.length;
305
+ if (this.readingManifest && this.count > this.limit)
306
+ fail("LIMIT", "Inflated backup exceeds manifest limit");
307
+ return true;
308
+ }
309
+ async read(size, onBytes) {
310
+ const pieces = onBytes ? null : [];
311
+ let remaining = size;
312
+ while (remaining) {
313
+ if (!this.pending.length && !(await this.pull())) fail("DAMAGED", "Truncated backup payload");
314
+ const piece = this.pending.subarray(0, Math.min(remaining, this.pending.length));
315
+ if (onBytes) await onBytes(piece);
316
+ else pieces.push(piece);
317
+ this.pending = this.pending.subarray(piece.length);
318
+ remaining -= piece.length;
319
+ }
320
+ return pieces ? Buffer.concat(pieces) : undefined;
321
+ }
322
+ async end() {
323
+ if (this.pending.length || await this.pull()) fail("DAMAGED", "Trailing backup payload");
324
+ }
325
+ }
326
+ async function readManifest(reader) {
327
+ if (!(await reader.read(8)).equals(INNER)) fail("DAMAGED", "Invalid backup payload marker");
328
+ const length = (await reader.read(4)).readUInt32BE();
329
+ if (!length) fail("BAD_MANIFEST", "Empty backup manifest");
330
+ if (length > LIMITS.manifest) fail("LIMIT", "Backup manifest too large");
331
+ const bytes = await reader.read(length);
332
+ const manifest = parseJson(bytes, "BAD_MANIFEST");
333
+ validateManifest(manifest);
334
+ const total = manifest.entries.reduce((sum, item) => sum + item.size, 0);
335
+ reader.limit = 20 + length + total;
336
+ reader.readingManifest = false;
337
+ return { manifest, bytes, total };
338
+ }
339
+ async function withPayload(filePath, info, keys, action) {
340
+ const { source, unzip } = payloadStream(filePath, info, keys);
341
+ try { return await action(new ByteReader(unzip)); }
342
+ catch (error) {
343
+ if (error instanceof BackupError) throw error;
344
+ // zlib's failures indicate corrupt authenticated plaintext, not I/O.
345
+ if (error?.code?.startsWith?.("Z_")) fail("DAMAGED", "Invalid backup compression");
346
+ throw io(error);
347
+ } finally {
348
+ const closed = source.closed ? Promise.resolve() : new Promise((resolve) => source.once("close", resolve));
349
+ source.destroy();
350
+ unzip.destroy();
351
+ await closed;
352
+ }
353
+ }
354
+ async function emptyDestination(dest) {
355
+ try {
356
+ const stat = await fsp.lstat(dest);
357
+ if (!stat.isDirectory() || stat.isSymbolicLink() ||
358
+ (typeof process.getuid === "function" &&
359
+ (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)) ||
360
+ (await fsp.readdir(dest)).length)
361
+ fail("IO", "Backup destination must be an empty directory");
362
+ return await fsp.realpath(dest);
363
+ } catch (error) { throw io(error); }
364
+ }
365
+ async function entryTarget(root, entryPath) {
366
+ const target = path.resolve(root, entryPath);
367
+ if (!target.startsWith(root + path.sep)) fail("BAD_MANIFEST", "Invalid backup path");
368
+ const parts = entryPath.split("/");
369
+ let parent = root;
370
+ for (const part of parts.slice(0, -1)) {
371
+ parent = path.join(parent, part);
372
+ try { await fsp.mkdir(parent, { mode: 0o700 }); }
373
+ catch (error) { if (error.code !== "EEXIST") throw error; }
374
+ // A pre-existing link must never redirect a later file creation.
375
+ if (!(await fsp.lstat(parent)).isDirectory() || await fsp.realpath(parent) !== parent)
376
+ fail("IO", "Unsafe backup destination");
377
+ }
378
+ return target;
379
+ }
380
+ async function extractInto(filePath, info, keys, manifestBytes, dest, onProgress) {
381
+ const root = await emptyDestination(dest);
382
+ return withPayload(filePath, info, keys, async (reader) => {
383
+ const current = await readManifest(reader);
384
+ if (!current.bytes.equals(manifestBytes)) fail("DAMAGED", "Backup manifest changed");
385
+ let done = 0;
386
+ const memory = {};
387
+ for (const entry of current.manifest.entries) {
388
+ const hash = crypto.createHash("sha256");
389
+ // Decrypted API keys stay in memory. Callers cannot opt into a file.
390
+ if (entry.kind === "secrets") {
391
+ if (entry.size > LIMITS.memory) fail("LIMIT", "In-memory backup entry too large");
392
+ const buffer = await reader.read(entry.size);
393
+ hash.update(buffer);
394
+ done += buffer.length;
395
+ onProgress?.({ phase: "write", bytes: done, totalBytes: current.total });
396
+ if (hash.digest("hex") !== entry.sha256) {
397
+ buffer.fill(0);
398
+ fail("DAMAGED", "Backup entry checksum failed");
399
+ }
400
+ memory[entry.path] = buffer;
401
+ continue;
402
+ }
403
+ const target = await entryTarget(root, entry.path);
404
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL |
405
+ (fs.constants.O_NOFOLLOW || 0);
406
+ const output = await fsp.open(target, flags, 0o600);
407
+ try {
408
+ await reader.read(entry.size, async (piece) => {
409
+ hash.update(piece);
410
+ await output.writeFile(piece);
411
+ done += piece.length;
412
+ onProgress?.({ phase: "write", bytes: done, totalBytes: current.total });
413
+ });
414
+ } finally { await output.close(); }
415
+ if (hash.digest("hex") !== entry.sha256) fail("DAMAGED", "Backup entry checksum failed");
416
+ }
417
+ if (!(await reader.read(8)).equals(END)) {
418
+ if (reader.count > reader.limit) fail("LIMIT", "Inflated backup exceeds declared size");
419
+ fail("DAMAGED", "Missing backup end marker");
420
+ }
421
+ await reader.end();
422
+ return { entries: current.manifest.entries.length, bytes: done, memory };
423
+ });
424
+ }
425
+ async function openWithKeys({ path: filePath, keys }) {
426
+ const info = await readHeader(filePath);
427
+ verifyHeader(info, keys);
428
+ const { manifest, bytes } = await withPayload(filePath, info, keys, readManifest);
429
+ let used = false;
430
+ return { header: info.header, manifest,
431
+ // Callers must create dest as a private directory and remove it on any
432
+ // failure; extraction leaves partial files for the caller to clean up.
433
+ async extract({ dest, onProgress } = {}) {
434
+ if (used) fail("IO", "Backup extraction already used");
435
+ used = true;
436
+ try { return await extractInto(filePath, info, keys, bytes, dest, onProgress); }
437
+ catch (error) { throw io(error); }
438
+ } };
439
+ }
440
+ async function openBackup({ path: filePath, password }) {
441
+ const normalized = validatePassword(password);
442
+ const info = await readHeader(filePath);
443
+ const keys = await deriveKeys(normalized, info.header.kdf);
444
+ return openWithKeys({ path: filePath, keys });
445
+ }
446
+
447
+ async function* rawPayload(manifestBytes, entries, onSourceBytes) {
448
+ const length = Buffer.alloc(4);
449
+ length.writeUInt32BE(manifestBytes.length);
450
+ yield INNER;
451
+ yield length;
452
+ yield manifestBytes;
453
+ for (const entry of entries) {
454
+ const hash = crypto.createHash("sha256");
455
+ let size = 0;
456
+ const source = Buffer.isBuffer(entry.source) ? Readable.from([entry.source]) :
457
+ fs.createReadStream(entry.source);
458
+ for await (const bytes of source) {
459
+ size += bytes.length;
460
+ if (size > entry.size) fail("SOURCE_CHANGED", "Backup source changed");
461
+ hash.update(bytes);
462
+ onSourceBytes(bytes.length);
463
+ yield bytes;
464
+ }
465
+ if (size !== entry.size || hash.digest("hex") !== entry.sha256)
466
+ fail("SOURCE_CHANGED", "Backup source changed");
467
+ }
468
+ yield END;
469
+ }
470
+ async function writeAll(handle, bytes, hash, state) {
471
+ if (state.size + bytes.length > LIMITS.file) fail("LIMIT", "Backup file too large");
472
+ let offset = 0;
473
+ while (offset < bytes.length) {
474
+ const result = await handle.write(bytes, offset, bytes.length - offset);
475
+ if (!result.bytesWritten) fail("IO", "Backup write failed");
476
+ offset += result.bytesWritten;
477
+ }
478
+ hash.update(bytes);
479
+ state.size += bytes.length;
480
+ }
481
+ async function writeBackup({ outPath, password, manifest, entries, kdf = DEFAULT_KDF, onProgress }) {
482
+ const normalized = validatePassword(password);
483
+ if (!Array.isArray(entries)) fail("BAD_MANIFEST", "Invalid backup entries");
484
+ const full = { ...manifest, entries: entries.map(({ path, kind, size, sha256 }) => ({ path, kind, size, sha256 })) };
485
+ validateManifest(full);
486
+ const manifestBytes = Buffer.from(JSON.stringify(full));
487
+ if (!manifestBytes.length || manifestBytes.length > LIMITS.manifest) fail("LIMIT", "Backup manifest too large");
488
+ for (const entry of entries) {
489
+ if (!Buffer.isBuffer(entry.source) && (typeof entry.source !== "string" || !path.isAbsolute(entry.source)))
490
+ fail("BAD_MANIFEST", "Invalid backup source");
491
+ }
492
+ exactKeys(kdf, ["N", "r", "p"], "BAD_HEADER");
493
+ const salt = crypto.randomBytes(32);
494
+ const header = headerFor(kdf, salt);
495
+ validateHeader(header);
496
+ onProgress?.({ phase: "kdf", bytes: 0, totalBytes: 0 });
497
+ const keys = await deriveKeys(normalized, header.kdf);
498
+ const { prefix } = headerBytes(header);
499
+ const aad = crypto.createHmac("sha256", keys.macKey).update(prefix).digest();
500
+ let handle;
501
+ let ownsPart = false;
502
+ const part = `${outPath}.part`;
503
+ try {
504
+ handle = await fsp.open(part, "wx", 0o600);
505
+ ownsPart = true;
506
+ const hash = crypto.createHash("sha256");
507
+ const state = { size: 0 };
508
+ await writeAll(handle, Buffer.concat([prefix, aad]), hash, state);
509
+ const total = full.entries.reduce((sum, item) => sum + item.size, 0);
510
+ let consumed = 0;
511
+ const gzip = zlib.createGzip({ level: 6 });
512
+ const source = Readable.from(rawPayload(manifestBytes, entries, (size) => {
513
+ consumed += size;
514
+ onProgress?.({ phase: "write", bytes: consumed, totalBytes: total });
515
+ }));
516
+ source.on("error", (error) => gzip.destroy(error));
517
+ source.pipe(gzip);
518
+ let pending = Buffer.alloc(0);
519
+ let index = 0;
520
+ try {
521
+ for await (const bytes of gzip) {
522
+ pending = Buffer.concat([pending, bytes]);
523
+ while (pending.length > LIMITS.chunk) {
524
+ await writeAll(handle, sealChunk(pending.subarray(0, LIMITS.chunk), index++, false, keys, aad), hash, state);
525
+ pending = pending.subarray(LIMITS.chunk);
526
+ }
527
+ }
528
+ if (!pending.length) fail("DAMAGED", "Empty backup payload");
529
+ await writeAll(handle, sealChunk(pending, index, true, keys, aad), hash, state);
530
+ } finally { source.destroy(); gzip.destroy(); }
531
+ onProgress?.({ phase: "write", bytes: total, totalBytes: total });
532
+ await handle.sync();
533
+ await handle.close();
534
+ handle = null;
535
+ await fsp.rename(part, outPath);
536
+ try {
537
+ const dir = await fsp.open(path.dirname(outPath), "r");
538
+ try { await dir.sync(); } finally { await dir.close(); }
539
+ } catch (error) {
540
+ if (!["EINVAL", "ENOTSUP", "EISDIR", "EPERM", "EBADF"].includes(error.code)) throw error;
541
+ }
542
+ return { size: state.size, sha256: hash.digest("hex") };
543
+ } catch (error) {
544
+ await handle?.close().catch(() => {});
545
+ if (ownsPart) await fsp.rm(part, { force: true }).catch(() => {});
546
+ throw io(error);
547
+ }
548
+ }
549
+
550
+ // Test-only hooks. Production callers use writeBackup and openBackup.
551
+ function sealRaw(payloadBytes, { keys, kdf = DEFAULT_KDF, salt = crypto.randomBytes(32), headerOverride } = {}) {
552
+ const base = headerFor(kdf, salt);
553
+ const header = { ...base, ...headerOverride, kdf: { ...base.kdf, ...headerOverride?.kdf } };
554
+ const { prefix } = headerBytes(header);
555
+ const aad = crypto.createHmac("sha256", keys.macKey).update(prefix).digest();
556
+ const chunks = [];
557
+ for (let offset = 0, index = 0; offset < payloadBytes.length; offset += LIMITS.chunk, index++) {
558
+ const end = Math.min(offset + LIMITS.chunk, payloadBytes.length);
559
+ chunks.push(sealChunk(payloadBytes.subarray(offset, end), index, end === payloadBytes.length, keys, aad));
560
+ }
561
+ return Buffer.concat([prefix, aad, ...chunks]);
562
+ }
563
+
564
+ module.exports = { BackupError, CODES, DEFAULT_KDF, LIMITS, validatePassword, validateManifest,
565
+ writeBackup, openBackup, _internal: { deriveKeys, sealRaw, openWithKeys } };
@@ -0,0 +1,111 @@
1
+ const crypto = require("node:crypto");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const { ensureDataDir } = require("../config/paths.cjs");
5
+ const { BackupError, CODES } = require("./format.cjs");
6
+ const { createBackup } = require("./create.cjs");
7
+ const { restoreUpload } = require("./restore.cjs");
8
+ const uploads = require("./uploads.cjs");
9
+ const { readJournal } = require("./journal.cjs");
10
+ const logger = require("../utils/logger.cjs");
11
+ let session = null;
12
+ function setSession(manager) { session = manager; }
13
+ function reconnectForMatchingResult(result) {
14
+ if (!result?.accountMatchesPaired || !session ||
15
+ ["idle", "disconnected", "retry_exhausted", "logged_out", "error"].includes(session.state))
16
+ return Promise.resolve(false);
17
+ return Promise.resolve().then(() => session.reconnect({ reason: "restore-activation" }))
18
+ .then(() => true)
19
+ .catch(() => { logger.error("[Backup] Reconnect after restore failed"); return false; });
20
+ }
21
+
22
+ function sweepBackupTemp() {
23
+ const root = ensureDataDir("tmp", "backup");
24
+ // A previous process cannot own a current job.
25
+ for (const name of fs.readdirSync(root)) fs.rmSync(path.join(root, name), { recursive: true, force: true });
26
+ ensureDataDir("tmp", "backup", "exports");
27
+ }
28
+
29
+ const jobs = new Map();
30
+ const exportsByToken = new Map();
31
+ let active = null;
32
+ const EXPIRE_MS = 30 * 60 * 1000;
33
+
34
+ function startExport(password) {
35
+ if (active || readJournal()) throw new BackupError("BUSY", "Backup job busy");
36
+ const job = { id: crypto.randomBytes(16).toString("hex"), kind: "backup",
37
+ phase: "queued", bytes: 0, totalBytes: 0, done: false, error: null, result: null };
38
+ jobs.set(job.id, job);
39
+ active = job.id;
40
+ setImmediate(async () => {
41
+ try {
42
+ const file = await createBackup({ password, onProgress(update) {
43
+ job.phase = update.phase;
44
+ job.bytes = update.bytes;
45
+ job.totalBytes = update.totalBytes;
46
+ } });
47
+ const expiresAt = new Date(Date.now() + EXPIRE_MS).toISOString();
48
+ exportsByToken.set(file.token, { ...file, expiresAt });
49
+ job.result = { token: file.token, fileName: file.fileName, size: file.size, expiresAt };
50
+ job.phase = "done";
51
+ const timer = setTimeout(() => removeExport(file.token), EXPIRE_MS);
52
+ timer.unref();
53
+ } catch (error) {
54
+ job.phase = "error";
55
+ job.error = { code: [...CODES, "NO_SPACE", "UNCLASSIFIED_TABLE", "SECRET_FOUND"].includes(error?.code) ? error.code : "IO" };
56
+ } finally {
57
+ job.done = true;
58
+ active = null;
59
+ const timer = setTimeout(() => jobs.delete(job.id), EXPIRE_MS);
60
+ timer.unref();
61
+ }
62
+ });
63
+ return job.id;
64
+ }
65
+
66
+ function startRestore(uploadId, password, options = {}) {
67
+ if (active || readJournal()) throw new BackupError("BUSY", "Backup job busy");
68
+ const pin = uploads.pinUpload(uploadId);
69
+ if (!pin) throw new BackupError("NOT_FOUND", "Upload not found");
70
+ const job = { id: crypto.randomBytes(16).toString("hex"), kind: "restore",
71
+ phase: "queued", bytes: 0, totalBytes: 0, done: false, error: null, result: null };
72
+ jobs.set(job.id, job);
73
+ active = job.id;
74
+ setImmediate(async () => {
75
+ try {
76
+ job.result = await restoreUpload(uploadId, password, (update) => Object.assign(job, update), options);
77
+ job.phase = "done";
78
+ void reconnectForMatchingResult(job.result);
79
+ } catch (error) {
80
+ job.phase = "error";
81
+ const code = error?.code === "WRONG_PASSWORD" && uploads.wrongPassword(uploadId) ?
82
+ "too_many_attempts" : error instanceof BackupError ? error.code : "IO";
83
+ job.error = code === "CONFIRM_REQUIRED" && error.plan ? { code, plan: error.plan } : { code };
84
+ } finally {
85
+ pin.release();
86
+ job.done = true;
87
+ active = null;
88
+ const timer = setTimeout(() => jobs.delete(job.id), EXPIRE_MS);
89
+ timer.unref();
90
+ }
91
+ });
92
+ return job.id;
93
+ }
94
+
95
+ function getJob(id) { return jobs.get(id) || null; }
96
+ function getExport(token) {
97
+ const entry = exportsByToken.get(token);
98
+ if (!entry) return null;
99
+ if (Date.parse(entry.expiresAt) <= Date.now()) { removeExport(token); return null; }
100
+ return entry;
101
+ }
102
+ function removeExport(token) {
103
+ const entry = exportsByToken.get(token);
104
+ if (!entry) return false;
105
+ exportsByToken.delete(token);
106
+ fs.rmSync(entry.path, { force: true });
107
+ return true;
108
+ }
109
+
110
+ module.exports = { sweepBackupTemp, startExport, startRestore, getJob, getExport, removeExport,
111
+ setSession, reconnectForMatchingResult };