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.
- package/README.md +57 -3
- package/SETUP.md +63 -7
- package/app.cjs +159 -46
- package/deploy/install.sh +10 -5
- package/package.json +9 -6
- package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
- package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
- package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
- package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
- package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
- package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
- package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
- package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
- package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
- package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
- package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
- package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
- package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
- package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
- package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
- package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
- package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
- package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
- package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
- package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
- package/public/dashboard/assets/index-Da-j89O-.js +458 -0
- package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
- package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
- package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
- package/public/dashboard/gateway.html +17 -0
- package/public/dashboard/index.html +3 -5
- package/public/ui-boot.js +33 -14
- package/scheduler.cjs +76 -23
- package/src/auth/auth-storage.cjs +54 -7
- package/src/auth/use-database-auth-state.js +70 -39
- package/src/automation/engine.js +412 -0
- package/src/automation/limits.cjs +6 -0
- package/src/automation/manage.js +290 -0
- package/src/automation/reactions.js +471 -0
- package/src/automation/rules.cjs +114 -0
- package/src/automation/status.cjs +76 -0
- package/src/backup/account.cjs +29 -0
- package/src/backup/activation.cjs +247 -0
- package/src/backup/content.cjs +36 -0
- package/src/backup/create.cjs +280 -0
- package/src/backup/extensions.cjs +101 -0
- package/src/backup/format.cjs +565 -0
- package/src/backup/jobs.cjs +111 -0
- package/src/backup/journal.cjs +41 -0
- package/src/backup/plan.cjs +223 -0
- package/src/backup/recovery.cjs +110 -0
- package/src/backup/restore.cjs +460 -0
- package/src/backup/uploads.cjs +146 -0
- package/src/bootstrap/core.js +50 -12
- package/src/bootstrap/panel.js +53 -2
- package/src/bootstrap/session-startup-policy.js +8 -1
- package/src/cli.js +163 -22
- package/src/commands/autodelete.cjs +41 -57
- package/src/commands/autoschedule.cjs +7 -33
- package/src/commands/blacklist.cjs +17 -35
- package/src/commands/block.cjs +4 -18
- package/src/commands/calc.cjs +22 -74
- package/src/commands/debt.cjs +28 -59
- package/src/commands/deleteschedule.cjs +7 -23
- package/src/commands/digit.cjs +5 -39
- package/src/commands/gemini.cjs +135 -218
- package/src/commands/group/add.cjs +28 -76
- package/src/commands/group/all.cjs +4 -15
- package/src/commands/group/antilink.cjs +28 -41
- package/src/commands/group/antispam.cjs +25 -35
- package/src/commands/group/approveall.cjs +7 -21
- package/src/commands/group/clearwarns.cjs +4 -18
- package/src/commands/group/deletenote.cjs +4 -18
- package/src/commands/group/demote.cjs +6 -23
- package/src/commands/group/flagged.cjs +10 -19
- package/src/commands/group/kick.cjs +26 -36
- package/src/commands/group/media.cjs +21 -36
- package/src/commands/group/members.cjs +16 -28
- package/src/commands/group/note.cjs +3 -14
- package/src/commands/group/policy.cjs +16 -37
- package/src/commands/group/promote.cjs +5 -22
- package/src/commands/group/removeall.cjs +6 -38
- package/src/commands/group/rules.cjs +4 -19
- package/src/commands/group/save.cjs +4 -18
- package/src/commands/group/setname.cjs +5 -19
- package/src/commands/group/setpp.cjs +8 -26
- package/src/commands/group/setrules.cjs +4 -15
- package/src/commands/group/setwarn.cjs +6 -23
- package/src/commands/group/tagadmins.cjs +5 -16
- package/src/commands/group/warn.cjs +5 -16
- package/src/commands/group/warns.cjs +12 -33
- package/src/commands/group/welcome.cjs +17 -34
- package/src/commands/group.cjs +91 -68
- package/src/commands/help.cjs +48 -89
- package/src/commands/lang.cjs +38 -97
- package/src/commands/listschedules.cjs +19 -30
- package/src/commands/loop.cjs +9 -55
- package/src/commands/md.cjs +2 -13
- package/src/commands/memory.cjs +53 -87
- package/src/commands/mod.cjs +40 -79
- package/src/commands/notes.cjs +4 -15
- package/src/commands/pack.cjs +26 -49
- package/src/commands/packs.cjs +8 -18
- package/src/commands/perm.cjs +48 -51
- package/src/commands/ping.cjs +2 -10
- package/src/commands/poll.cjs +5 -38
- package/src/commands/prayer.cjs +55 -36
- package/src/commands/qr.cjs +4 -18
- package/src/commands/rand.cjs +9 -58
- package/src/commands/restart.cjs +15 -33
- package/src/commands/schedule.cjs +5 -25
- package/src/commands/score.cjs +6 -27
- package/src/commands/send.cjs +4 -18
- package/src/commands/setprefix.cjs +11 -23
- package/src/commands/shortlink.cjs +13 -39
- package/src/commands/status.cjs +188 -76
- package/src/commands/sticker.cjs +5 -16
- package/src/commands/stickers.cjs +16 -20
- package/src/commands/stopbot.cjs +9 -25
- package/src/commands/stt.cjs +75 -107
- package/src/commands/todo.cjs +11 -31
- package/src/commands/toimage.cjs +11 -27
- package/src/commands/translate.cjs +53 -36
- package/src/commands/tts.cjs +46 -40
- package/src/commands/unblock.cjs +3 -17
- package/src/commands/update.cjs +23 -0
- package/src/commands/weather.cjs +40 -47
- package/src/config/ai-identity.cjs +14 -1
- package/src/config/baileys.config.js +16 -3
- package/src/config/data-dir.cjs +37 -0
- package/src/config/defaults.cjs +1 -0
- package/src/config/exit-codes.cjs +11 -0
- package/src/config/lock.cjs +55 -81
- package/src/config/official-links.cjs +61 -0
- package/src/config/paths.cjs +4 -33
- package/src/config/release.cjs +87 -0
- package/src/config/settings.cjs +199 -10
- package/src/core/connection.js +77 -9
- package/src/core/events.js +119 -33
- package/src/core/session.js +536 -84
- package/src/core/socket.js +81 -10
- package/src/db/copy.cjs +136 -0
- package/src/db/db.cjs +241 -36
- package/src/db/startup-guard.js +5 -0
- package/src/db/store.cjs +561 -54
- package/src/diagnostics/baileysLog.cjs +87 -0
- package/src/diagnostics/debugLog.cjs +16 -4
- package/src/diagnostics/device.cjs +4 -2
- package/src/diagnostics/nodeRuntime.cjs +131 -0
- package/src/diagnostics/signalSessionInspect.cjs +38 -0
- package/src/domain/command.js +24 -22
- package/src/extensions/autoReply.cjs +521 -0
- package/src/extensions/context.cjs +73 -0
- package/src/extensions/contract.cjs +69 -0
- package/src/extensions/entitlement/client.cjs +381 -0
- package/src/extensions/entitlement/index.cjs +629 -0
- package/src/extensions/entitlement/installation.cjs +117 -0
- package/src/extensions/entitlement/keys.cjs +72 -0
- package/src/extensions/entitlement/state.cjs +201 -0
- package/src/extensions/entitlement/target.cjs +7 -0
- package/src/extensions/entitlement/token.cjs +225 -0
- package/src/extensions/host.cjs +519 -0
- package/src/extensions/templateKeys.cjs +81 -0
- package/src/handlers/command.handler.js +191 -64
- package/src/handlers/group.handler.js +78 -18
- package/src/handlers/message.handler.js +56 -25
- package/src/i18n/catalog.generated.cjs +3537 -0
- package/src/index.js +51 -12
- package/src/legal/bundled/ar.json +102 -0
- package/src/legal/bundled/en.json +102 -0
- package/src/legal/bundled/es-419.json +102 -0
- package/src/legal/bundled/pt-BR.json +102 -0
- package/src/legal/cli.cjs +200 -0
- package/src/legal/consent.cjs +187 -0
- package/src/legal/document.cjs +156 -0
- package/src/legal/keys.cjs +100 -0
- package/src/legal/release.cjs +226 -0
- package/src/legal/remote.cjs +419 -0
- package/src/legal/terms.cjs +142 -0
- package/src/messaging/escape.cjs +31 -0
- package/src/messaging/health.cjs +65 -0
- package/src/messaging/identity.cjs +42 -0
- package/src/messaging/message.cjs +136 -0
- package/src/messaging/parser.cjs +88 -0
- package/src/messaging/router.cjs +217 -0
- package/src/middleware/permissions.middleware.js +34 -2
- package/src/panel/account-profile.cjs +489 -0
- package/src/panel/fallback-page.cjs +177 -0
- package/src/panel/password-reset.cjs +13 -14
- package/src/panel/recovery-email.cjs +3 -1
- package/src/routes/backup.api.esm.js +175 -0
- package/src/routes/dashboard.api.esm.js +183 -7
- package/src/routes/plus.api.esm.js +172 -0
- package/src/routes/reactions.api.esm.js +60 -0
- package/src/services/aiAgent.cjs +56 -43
- package/src/services/aiDocs.cjs +187 -0
- package/src/services/aiImage.cjs +183 -0
- package/src/services/aiMedia.cjs +146 -0
- package/src/services/aiProviders.cjs +76 -80
- package/src/services/aiRouter.cjs +2 -2
- package/src/services/aiToolAuth.cjs +76 -4
- package/src/services/aiTools.cjs +431 -105
- package/src/services/autoDelete.cjs +9 -1
- package/src/services/levix-docs.generated.json +2623 -0
- package/src/services/memoryPolicy.cjs +56 -0
- package/src/services/updateCheck.cjs +362 -0
- package/src/stickers/errors.cjs +53 -97
- package/src/stickers/library.cjs +13 -6
- package/src/stickers/owner.cjs +1 -1
- package/src/utils/commandContext.cjs +13 -0
- package/src/utils/commandDocs.cjs +42 -20
- package/src/utils/geminiHttpOptions.cjs +56 -0
- package/src/utils/geminiMedia.cjs +28 -3
- package/src/utils/groupMetadataCache.cjs +386 -21
- package/src/utils/httpsFetch.cjs +113 -0
- package/src/utils/i18n.cjs +117 -7
- package/src/utils/linkPreview.cjs +90 -0
- package/src/utils/logger.cjs +6 -0
- package/src/utils/markdownParser.cjs +3 -3
- package/src/utils/memory.cjs +375 -28
- package/src/utils/messageContent.cjs +7 -1
- package/src/utils/moderationAction.cjs +116 -73
- package/src/utils/moderationSummary.cjs +32 -56
- package/src/utils/permissionLevel.cjs +7 -28
- package/src/utils/permissions.cjs +23 -14
- package/src/utils/permissions.esm.js +99 -166
- package/src/utils/recentMessageCache.esm.js +241 -37
- package/src/utils/recurrence.cjs +78 -66
- package/src/utils/sendBotMessage.cjs +14 -29
- package/src/utils/sendBotMessage.esm.js +28 -13
- package/src/utils/statusMessage.cjs +94 -33
- package/src/utils/stickerBot.cjs +18 -16
- package/src/utils/storage.cjs +2 -0
- package/src/utils/storage.esm.js +2 -0
- package/src/utils/thumbnail.cjs +5 -21
- package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
- package/public/dashboard/assets/index-CK8osB4o.css +0 -2
- package/public/dashboard.css +0 -3127
- package/public/dashboard.js +0 -1981
- package/public/gateway-i18n.js +0 -321
- package/public/gateway.js +0 -70
- package/views/dashboard.ejs +0 -775
- package/views/login.ejs +0 -408
- package/views/qr.ejs +0 -155
- package/views/setup.ejs +0 -118
|
@@ -0,0 +1,460 @@
|
|
|
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, migrate, MIGRATIONS, fsyncDirectory } = require("../db/db.cjs");
|
|
6
|
+
const { SECRET_TABLES, isSecretBotKey } = require("../db/copy.cjs");
|
|
7
|
+
const store = require("../db/store.cjs");
|
|
8
|
+
const settings = require("../config/settings.cjs");
|
|
9
|
+
const runtime = require("../config/runtime-config.cjs");
|
|
10
|
+
const { dataPath, ensureDataDir } = require("../config/paths.cjs");
|
|
11
|
+
const { applySettingChange } = require("../services/settingsTransfer.cjs");
|
|
12
|
+
const { BackupError, openBackup } = require("./format.cjs");
|
|
13
|
+
const { classifyTables, RESTORABLE_SETTING_KEYS, COMMAND_TABLE_KEYS } = require("./content.cjs");
|
|
14
|
+
const { readPairedAccount, maskAccount, accountsMatch } = require("./account.cjs");
|
|
15
|
+
const { writeJournal, readJournal, clearJournal, writeOutcome, readOutcome, atomicJson } = require("./journal.cjs");
|
|
16
|
+
const uploads = require("./uploads.cjs");
|
|
17
|
+
const extensions = require("./extensions.cjs");
|
|
18
|
+
const { buildPlan, appliedPlan, currentDigests, digestsFrom, restorableRows, publicPlan } = require("./plan.cjs");
|
|
19
|
+
|
|
20
|
+
const root = () => {
|
|
21
|
+
const folder = ensureDataDir("restore");
|
|
22
|
+
if (process.platform !== "win32") fs.chmodSync(folder, 0o700);
|
|
23
|
+
return folder;
|
|
24
|
+
};
|
|
25
|
+
const stageRoot = (id) => dataPath("restore", id);
|
|
26
|
+
const staged = (id) => dataPath("restore", id, "staged");
|
|
27
|
+
const marker = () => {
|
|
28
|
+
try { return JSON.parse(store.getBotSetting("restore:applied", "null"))?.id; }
|
|
29
|
+
catch { return null; }
|
|
30
|
+
};
|
|
31
|
+
let crashHook = null;
|
|
32
|
+
// Test-only injection. Tests may throw at a named boundary, then start recovery.
|
|
33
|
+
function setCrashHookForTest(fn) { crashHook = fn; }
|
|
34
|
+
function crash(name) {
|
|
35
|
+
if (!crashHook) return;
|
|
36
|
+
try { crashHook(name); }
|
|
37
|
+
catch (error) { error.restoreTestCrash = true; throw error; }
|
|
38
|
+
}
|
|
39
|
+
function schemaCheck(manifest) {
|
|
40
|
+
if (manifest.schema > MIGRATIONS.length) throw new BackupError("SCHEMA_NEWER", "Backup schema is newer");
|
|
41
|
+
}
|
|
42
|
+
function spaceCheck(manifest) {
|
|
43
|
+
const total = manifest.entries.reduce((n, entry) => n + entry.size, 0);
|
|
44
|
+
const dbSize = manifest.entries.find((entry) => entry.kind === "db").size;
|
|
45
|
+
const stat = fs.statfsSync(root());
|
|
46
|
+
if (Number(stat.bavail) * Number(stat.bsize) < total + 2 * dbSize + 64 * 1024 ** 2)
|
|
47
|
+
throw new BackupError("NO_SPACE", "Insufficient storage");
|
|
48
|
+
return total;
|
|
49
|
+
}
|
|
50
|
+
function safeJson(raw, fallback) { try { return JSON.parse(raw); } catch { return fallback; } }
|
|
51
|
+
|
|
52
|
+
const restorableKeys = [...RESTORABLE_SETTING_KEYS.map((key) => `setting:${key}`), ...COMMAND_TABLE_KEYS];
|
|
53
|
+
function quoteSqlName(name) {
|
|
54
|
+
return `"${String(name).replaceAll('"', '""')}"`;
|
|
55
|
+
}
|
|
56
|
+
// A Levix backup never contains these rows. Treat a copy that has them as crafted.
|
|
57
|
+
function assertNoExcludedData(database) {
|
|
58
|
+
for (const table of SECRET_TABLES) {
|
|
59
|
+
const present = database.prepare(
|
|
60
|
+
"SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",
|
|
61
|
+
).get(table);
|
|
62
|
+
if (!present) continue;
|
|
63
|
+
const row = database.prepare(`SELECT 1 AS present FROM ${quoteSqlName(table)} LIMIT 1`).get();
|
|
64
|
+
if (row) throw new BackupError("DAMAGED", "Backup database holds excluded data");
|
|
65
|
+
}
|
|
66
|
+
const settingsTable = database.prepare(
|
|
67
|
+
"SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'bot_settings'",
|
|
68
|
+
).get();
|
|
69
|
+
if (!settingsTable) return;
|
|
70
|
+
// Only the named Plus keys may carry extension data. plus:* and every other ext:* key is refused.
|
|
71
|
+
const extensionKeys = [];
|
|
72
|
+
for (const row of database.prepare("SELECT key FROM bot_settings").iterate()) {
|
|
73
|
+
if (isSecretBotKey(row.key, extensions.isRestorableExtKey)) throw new BackupError("DAMAGED", "Backup database holds excluded data");
|
|
74
|
+
if (row.key.startsWith("ext:")) extensionKeys.push(row.key);
|
|
75
|
+
}
|
|
76
|
+
extensions.assertStagedExtensions(database, extensionKeys);
|
|
77
|
+
}
|
|
78
|
+
function expectedSchema(database) {
|
|
79
|
+
const version = database.prepare("PRAGMA user_version").get().user_version;
|
|
80
|
+
if (!Number.isInteger(version) || version < 0) throw new BackupError("SCHEMA_MISMATCH", "Backup database schema differs");
|
|
81
|
+
if (version > MIGRATIONS.length) throw new BackupError("SCHEMA_NEWER", "Backup schema is newer");
|
|
82
|
+
const reference = new DatabaseSync(":memory:");
|
|
83
|
+
try {
|
|
84
|
+
migrate(reference, MIGRATIONS.slice(0, version));
|
|
85
|
+
const definitionRows = (dbHandle, limit) => dbHandle.prepare(
|
|
86
|
+
`SELECT type, name, tbl_name, substr(sql, 1, 65537) AS sql, length(sql) AS sql_length
|
|
87
|
+
FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'
|
|
88
|
+
ORDER BY type, name, tbl_name LIMIT ?`,
|
|
89
|
+
).all(limit);
|
|
90
|
+
const wanted = definitionRows(reference, 1000);
|
|
91
|
+
const actual = definitionRows(database, wanted.length + 1);
|
|
92
|
+
const normalize = (sql) => String(sql ?? "").replace(/\s+/g, " ").trim();
|
|
93
|
+
if (wanted.length === 1000 || actual.length !== wanted.length || actual.some((row, index) =>
|
|
94
|
+
row.sql_length > 65536 || row.type !== wanted[index].type || row.name !== wanted[index].name ||
|
|
95
|
+
row.tbl_name !== wanted[index].tbl_name || normalize(row.sql) !== normalize(wanted[index].sql)))
|
|
96
|
+
throw new BackupError("SCHEMA_MISMATCH", "Backup database schema differs");
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error instanceof BackupError) throw error;
|
|
99
|
+
throw new BackupError("SCHEMA_MISMATCH", "Backup database schema differs");
|
|
100
|
+
} finally { reference.close(); }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function fsyncStagedTree(folder) {
|
|
104
|
+
for (const entry of fs.readdirSync(folder, { withFileTypes: true })) {
|
|
105
|
+
const item = path.join(folder, entry.name);
|
|
106
|
+
if (entry.isDirectory()) fsyncStagedTree(item);
|
|
107
|
+
else if (entry.isFile()) {
|
|
108
|
+
const fd = fs.openSync(item, "r");
|
|
109
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
110
|
+
} else throw new BackupError("DAMAGED", "Invalid staged item");
|
|
111
|
+
}
|
|
112
|
+
fsyncDirectory(folder);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function applySettings(id, secrets, { base, confirmDestructive = false } = {}) {
|
|
116
|
+
const source = new DatabaseSync(path.join(staged(id), "db", "levix.db"), { readOnly: true });
|
|
117
|
+
const report = { applied: [], skipped: [], restartNeeded: [] };
|
|
118
|
+
let plusApplied = false;
|
|
119
|
+
const skip = (key) => report.skipped.push({ key, reason: "Rejected value" });
|
|
120
|
+
try {
|
|
121
|
+
db.exec("PRAGMA synchronous = FULL");
|
|
122
|
+
db.exec("BEGIN IMMEDIATE");
|
|
123
|
+
try {
|
|
124
|
+
const before = currentDigests();
|
|
125
|
+
// Only what the backup contains is written. A setting, an API key or a
|
|
126
|
+
// command-table entry the backup lacks keeps its value on this install.
|
|
127
|
+
const rows = source.prepare(`SELECT key,
|
|
128
|
+
CASE WHEN length(CAST(value AS BLOB)) <= 1048576 THEN value ELSE NULL END AS value,
|
|
129
|
+
length(CAST(value AS BLOB)) > 1048576 AS oversized
|
|
130
|
+
FROM bot_settings WHERE key IN (${restorableKeys.map(() => "?").join(",")})`).all(...restorableKeys);
|
|
131
|
+
const priority = (key) => key === "setting:ai_provider" ? 0 :
|
|
132
|
+
/^(setting:(gemini|openai|anthropic)_model|setting:ai_auto_detect_capabilities)$/.test(key) ? 1 :
|
|
133
|
+
["setting:ai_vision_enabled", "setting:ai_stt_enabled"].includes(key) ? 3 : 2;
|
|
134
|
+
for (const { key, value, oversized } of rows.filter((row) => row.key.startsWith("setting:"))
|
|
135
|
+
.sort((a, b) => priority(a.key) - priority(b.key))) {
|
|
136
|
+
if (!key.startsWith("setting:")) continue;
|
|
137
|
+
const name = key.slice(8);
|
|
138
|
+
if (!RESTORABLE_SETTING_KEYS.includes(name)) { skip("unknown setting"); continue; }
|
|
139
|
+
if (oversized) { skip(name); continue; }
|
|
140
|
+
const parsed = safeJson(value, undefined);
|
|
141
|
+
if (parsed === undefined) { skip(name); continue; }
|
|
142
|
+
try {
|
|
143
|
+
applySettingChange(name, parsed);
|
|
144
|
+
report.applied.push(name);
|
|
145
|
+
if (settings.RESTART_SETTING_KEYS.includes(name)) report.restartNeeded.push(name);
|
|
146
|
+
} catch { skip(name); }
|
|
147
|
+
}
|
|
148
|
+
if (secrets) {
|
|
149
|
+
if (!secrets.settings || typeof secrets.settings !== "object" || Array.isArray(secrets.settings))
|
|
150
|
+
throw new BackupError("BAD_MANIFEST", "Invalid secret payload");
|
|
151
|
+
for (const [key, value] of Object.entries(secrets.settings)) {
|
|
152
|
+
if (!settings.SECRET_SETTING_KEYS.includes(key)) { skip("unknown secret"); continue; }
|
|
153
|
+
try { applySettingChange(key, value); report.applied.push(key); }
|
|
154
|
+
catch { skip(key); }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// Plus config applies with the settings. Account data (acct) waits for activation. A cfg key the
|
|
158
|
+
// backup lacks keeps its value: nothing here deletes.
|
|
159
|
+
const plusRows = extensions.validRows(source);
|
|
160
|
+
for (const { key, parsed } of plusRows.filter((row) => extensions.kindOf(row.key) === "cfg")) {
|
|
161
|
+
const name = extensions.shortName(key);
|
|
162
|
+
try {
|
|
163
|
+
store.setExtStorage(extensions.EXT_ID, "cfg", name.slice("cfg:".length), parsed);
|
|
164
|
+
report.applied.push(name);
|
|
165
|
+
plusApplied = true;
|
|
166
|
+
} catch { skip(name); }
|
|
167
|
+
}
|
|
168
|
+
for (const row of rows.filter((item) => COMMAND_TABLE_KEYS.includes(item.key) && item.oversized)) skip(row.key);
|
|
169
|
+
const commandRows = new Map(rows.filter((row) => COMMAND_TABLE_KEYS.includes(row.key) && !row.oversized)
|
|
170
|
+
.map((row) => [row.key, safeJson(row.value, null)]));
|
|
171
|
+
if (commandRows.has("prefix")) {
|
|
172
|
+
try { runtime.setPrefix(commandRows.get("prefix")); report.applied.push("prefix"); }
|
|
173
|
+
catch { skip("prefix"); }
|
|
174
|
+
}
|
|
175
|
+
// A command-table key in the backup replaces this install's whole entry,
|
|
176
|
+
// all or nothing: one bad item puts the current entry back and skips it.
|
|
177
|
+
const isMap = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
178
|
+
const replaceEntry = (key, value, valid, applyAll) => {
|
|
179
|
+
if (!commandRows.has(key)) return;
|
|
180
|
+
if (!valid(value)) { skip(key); return; }
|
|
181
|
+
const previous = store.getBotSetting(key, null);
|
|
182
|
+
store.deleteBotSetting(key);
|
|
183
|
+
try { applyAll(value); report.applied.push(key); }
|
|
184
|
+
catch {
|
|
185
|
+
store.deleteBotSetting(key);
|
|
186
|
+
if (previous !== null) store.saveBotSetting(key, previous);
|
|
187
|
+
skip(key);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
replaceEntry("command_permissions", commandRows.get("command_permissions"), isMap, (map) => {
|
|
191
|
+
for (const [name, level] of Object.entries(map)) runtime.setPermission(name, level);
|
|
192
|
+
});
|
|
193
|
+
replaceEntry("command_aliases", commandRows.get("command_aliases"), isMap, (map) => {
|
|
194
|
+
for (const [name, list] of Object.entries(map)) runtime.setAliases(name, list);
|
|
195
|
+
});
|
|
196
|
+
const names = (list) => Array.isArray(list) &&
|
|
197
|
+
list.every((name) => typeof name === "string" && /^[^\s]{1,64}$/.test(name));
|
|
198
|
+
replaceEntry("disabled_commands", commandRows.get("disabled_commands"), names, (list) => {
|
|
199
|
+
for (const name of list) runtime.setEnabled(String(name), false);
|
|
200
|
+
});
|
|
201
|
+
// The decision uses what this transaction actually changed, side effects
|
|
202
|
+
// included. Refusing rolls back, so nothing live has changed.
|
|
203
|
+
const plan = appliedPlan({ before, after: currentDigests(),
|
|
204
|
+
source: digestsFrom([...rows, ...plusRows], secrets?.settings ?? {}), base });
|
|
205
|
+
report.plan = publicPlan(plan);
|
|
206
|
+
if (plan.destructive && confirmDestructive !== true) {
|
|
207
|
+
const refused = new BackupError("CONFIRM_REQUIRED", "Restore replaces existing values");
|
|
208
|
+
refused.plan = report.plan;
|
|
209
|
+
throw refused;
|
|
210
|
+
}
|
|
211
|
+
crash("inside-apply");
|
|
212
|
+
store.saveBotSetting("restore:applied", JSON.stringify({ id }));
|
|
213
|
+
db.exec("COMMIT");
|
|
214
|
+
} catch (error) { db.exec("ROLLBACK"); throw error; }
|
|
215
|
+
} finally {
|
|
216
|
+
try { db.exec("PRAGMA synchronous = NORMAL"); }
|
|
217
|
+
finally { source.close(); }
|
|
218
|
+
}
|
|
219
|
+
crash("after-commit");
|
|
220
|
+
if (plusApplied) extensions.reloadHost();
|
|
221
|
+
return report;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function installPersona(id) {
|
|
225
|
+
const source = path.join(staged(id), "persona.md");
|
|
226
|
+
const target = dataPath("ai-persona.md");
|
|
227
|
+
const { persona } = metadata(id);
|
|
228
|
+
if (typeof persona !== "boolean") throw new BackupError("DAMAGED", "Staged persona metadata missing");
|
|
229
|
+
if (persona && !fs.existsSync(source))
|
|
230
|
+
throw new BackupError("DAMAGED", "Staged persona missing");
|
|
231
|
+
// A backup without a persona leaves this install's persona as it is.
|
|
232
|
+
if (!persona) return;
|
|
233
|
+
const temp = dataPath(`ai-persona.${id}.part`);
|
|
234
|
+
fs.copyFileSync(source, temp);
|
|
235
|
+
fs.chmodSync(temp, 0o600);
|
|
236
|
+
const fd = fs.openSync(temp, "r");
|
|
237
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
238
|
+
fs.renameSync(temp, target);
|
|
239
|
+
fsyncDirectory(dataPath());
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function metadata(id) { return JSON.parse(fs.readFileSync(path.join(stageRoot(id), "metadata.json"), "utf8")); }
|
|
243
|
+
function stagedItemExists(file, directory = false) {
|
|
244
|
+
try {
|
|
245
|
+
const stat = fs.lstatSync(file);
|
|
246
|
+
return directory ? stat.isDirectory() : stat.isFile();
|
|
247
|
+
} catch (error) { if (error.code === "ENOENT") return false; throw error; }
|
|
248
|
+
}
|
|
249
|
+
function validateBeforePersona(id) {
|
|
250
|
+
const meta = metadata(id);
|
|
251
|
+
if (typeof meta.persona !== "boolean" || !meta.items ||
|
|
252
|
+
["memory", "stickers", "scheduleMedia"].some((key) => typeof meta.items[key] !== "boolean"))
|
|
253
|
+
throw new BackupError("DAMAGED", "Staged metadata missing");
|
|
254
|
+
if (meta.persona && !stagedItemExists(path.join(staged(id), "persona.md")))
|
|
255
|
+
throw new BackupError("DAMAGED", "Staged persona missing");
|
|
256
|
+
if (meta.account) {
|
|
257
|
+
for (const [name, required, directory] of [
|
|
258
|
+
["db/levix.db", true, false], ["memory", meta.items.memory, true],
|
|
259
|
+
["stickers", meta.items.stickers, true], ["media/schedules", meta.items.scheduleMedia, true],
|
|
260
|
+
]) {
|
|
261
|
+
if (required && !stagedItemExists(path.join(staged(id), name), directory))
|
|
262
|
+
throw new BackupError("DAMAGED", "Staged account item missing");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function pendingId() {
|
|
267
|
+
try { return JSON.parse(fs.readFileSync(dataPath("restore", "pending", "pending.json"), "utf8")).id; }
|
|
268
|
+
catch { return null; }
|
|
269
|
+
}
|
|
270
|
+
function installPending(id) {
|
|
271
|
+
const meta = metadata(id);
|
|
272
|
+
if (!meta.account) return;
|
|
273
|
+
if (pendingId() === id) {
|
|
274
|
+
for (const [name, required, directory] of [
|
|
275
|
+
["levix.db", true, false], ["files/memory", meta.items.memory, true],
|
|
276
|
+
["files/stickers", meta.items.stickers, true],
|
|
277
|
+
["files/media/schedules", meta.items.scheduleMedia, true],
|
|
278
|
+
]) {
|
|
279
|
+
if (required && !stagedItemExists(dataPath("restore", "pending", name), directory))
|
|
280
|
+
throw new BackupError("DAMAGED", "Pending account item missing");
|
|
281
|
+
}
|
|
282
|
+
syncPendingDirectories(id);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const next = dataPath("restore", "pending.next");
|
|
286
|
+
const pending = dataPath("restore", "pending");
|
|
287
|
+
const replaced = path.join(stageRoot(id), "replaced");
|
|
288
|
+
fs.mkdirSync(next, { recursive: true, mode: 0o700 });
|
|
289
|
+
fs.mkdirSync(path.join(next, "files"), { recursive: true, mode: 0o700 });
|
|
290
|
+
const items = [
|
|
291
|
+
["db/levix.db", "levix.db", true],
|
|
292
|
+
["memory", "files/memory", meta.items.memory],
|
|
293
|
+
["stickers", "files/stickers", meta.items.stickers],
|
|
294
|
+
["media/schedules", "files/media/schedules", meta.items.scheduleMedia],
|
|
295
|
+
];
|
|
296
|
+
for (const [sourceName, targetName, required] of items) {
|
|
297
|
+
if (!required) continue;
|
|
298
|
+
const source = path.join(staged(id), sourceName);
|
|
299
|
+
const target = path.join(next, targetName);
|
|
300
|
+
if (stagedItemExists(source, sourceName !== "db/levix.db")) {
|
|
301
|
+
if (fs.existsSync(target)) throw new BackupError("IO", "Duplicate pending item");
|
|
302
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
303
|
+
fs.renameSync(source, target);
|
|
304
|
+
} else if (!stagedItemExists(target, sourceName !== "db/levix.db"))
|
|
305
|
+
throw new BackupError("DAMAGED", "Missing pending item");
|
|
306
|
+
if (sourceName === "db/levix.db") crash("during-pending-items");
|
|
307
|
+
}
|
|
308
|
+
atomicJson(path.join(next, "pending.json"), { id, createdAt: new Date().toISOString(),
|
|
309
|
+
backupCreated: meta.created, account: meta.account, counts: meta.counts });
|
|
310
|
+
syncPendingDirectories(id);
|
|
311
|
+
if (fs.existsSync(pending)) {
|
|
312
|
+
if (fs.existsSync(replaced)) fs.rmSync(replaced, { recursive: true, force: true });
|
|
313
|
+
fs.renameSync(pending, replaced);
|
|
314
|
+
syncPendingDirectories(id);
|
|
315
|
+
}
|
|
316
|
+
crash("during-pending-renames");
|
|
317
|
+
fs.renameSync(next, pending);
|
|
318
|
+
syncPendingDirectories(id);
|
|
319
|
+
fs.rmSync(replaced, { recursive: true, force: true });
|
|
320
|
+
syncPendingDirectories(id);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function syncPendingDirectories(id) {
|
|
324
|
+
for (const folder of [stageRoot(id), staged(id), path.join(staged(id), "db"),
|
|
325
|
+
path.join(staged(id), "media"), dataPath("restore"),
|
|
326
|
+
dataPath("restore", "pending.next"), dataPath("restore", "pending"),
|
|
327
|
+
dataPath("restore", "pending.next", "files"), dataPath("restore", "pending", "files"),
|
|
328
|
+
dataPath("restore", "pending.next", "files", "media"),
|
|
329
|
+
dataPath("restore", "pending", "files", "media")]) {
|
|
330
|
+
if (fs.existsSync(folder)) fsyncDirectory(folder);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function finish(id, outcome = "restored") {
|
|
335
|
+
const meta = metadata(id);
|
|
336
|
+
const paired = readPairedAccount();
|
|
337
|
+
const result = { applied: meta.report?.applied || [], skipped: meta.report?.skipped || [],
|
|
338
|
+
restartNeeded: meta.report?.restartNeeded || [], plan: meta.report?.plan ?? null,
|
|
339
|
+
accountData: meta.account ? "waits" : "none",
|
|
340
|
+
accountMatchesPaired: accountsMatch(meta.account, paired) };
|
|
341
|
+
writeOutcome({ id, outcome, at: new Date().toISOString() });
|
|
342
|
+
clearJournal();
|
|
343
|
+
try { fs.rmSync(stageRoot(id), { recursive: true, force: true }); }
|
|
344
|
+
catch { /* Startup's orphan sweep removes it later. */ }
|
|
345
|
+
return result;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function restorePinnedUpload(id, file, password, onProgress, { confirmDestructive = false } = {}) {
|
|
349
|
+
if (readJournal()) throw new BackupError("BUSY", "A restore is awaiting recovery");
|
|
350
|
+
const opened = await openBackup({ path: file, password });
|
|
351
|
+
schemaCheck(opened.manifest);
|
|
352
|
+
const total = spaceCheck(opened.manifest);
|
|
353
|
+
onProgress?.({ phase: "verify", bytes: 0, totalBytes: total });
|
|
354
|
+
const restoreId = crypto.randomBytes(16).toString("hex");
|
|
355
|
+
const dir = stageRoot(restoreId);
|
|
356
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
357
|
+
fs.mkdirSync(staged(restoreId), { mode: 0o700 });
|
|
358
|
+
atomicJson(path.join(dir, "metadata.json"), { account: opened.manifest.account,
|
|
359
|
+
created: opened.manifest.created, counts: opened.manifest.counts,
|
|
360
|
+
persona: opened.manifest.entries.some((entry) => entry.kind === "persona"),
|
|
361
|
+
items: { memory: opened.manifest.entries.some((entry) => entry.kind === "memory"),
|
|
362
|
+
stickers: opened.manifest.entries.some((entry) => entry.kind === "sticker"),
|
|
363
|
+
scheduleMedia: opened.manifest.entries.some((entry) => entry.kind === "schedule-media") } });
|
|
364
|
+
writeJournal({ op: "restore", id: restoreId, step: "stage" });
|
|
365
|
+
crash("stage");
|
|
366
|
+
let secretsBuffer = null;
|
|
367
|
+
let secretsPayload = null;
|
|
368
|
+
let plan = null;
|
|
369
|
+
try {
|
|
370
|
+
onProgress?.({ phase: "stage", bytes: 0, totalBytes: total });
|
|
371
|
+
const extracted = await opened.extract({ dest: staged(restoreId),
|
|
372
|
+
onProgress(update) {
|
|
373
|
+
onProgress?.({ phase: "stage", bytes: update.bytes, totalBytes: total });
|
|
374
|
+
} });
|
|
375
|
+
secretsBuffer = extracted.memory["secrets.json"] ?? null;
|
|
376
|
+
if (secretsBuffer) {
|
|
377
|
+
secretsPayload = safeJson(secretsBuffer.toString("utf8"), null);
|
|
378
|
+
if (!secretsPayload || !secretsPayload.settings || typeof secretsPayload.settings !== "object" ||
|
|
379
|
+
Array.isArray(secretsPayload.settings))
|
|
380
|
+
throw new BackupError("BAD_MANIFEST", "Invalid secret payload");
|
|
381
|
+
}
|
|
382
|
+
crash("after-extract");
|
|
383
|
+
const stagedDb = path.join(staged(restoreId), "db", "levix.db");
|
|
384
|
+
const secretScan = new DatabaseSync(stagedDb, { readOnly: true });
|
|
385
|
+
try { assertNoExcludedData(secretScan); }
|
|
386
|
+
finally { secretScan.close(); }
|
|
387
|
+
const copy = new DatabaseSync(stagedDb);
|
|
388
|
+
try {
|
|
389
|
+
expectedSchema(copy);
|
|
390
|
+
if (copy.prepare("PRAGMA integrity_check").get().integrity_check !== "ok")
|
|
391
|
+
throw new BackupError("DAMAGED", "Backup database failed integrity check");
|
|
392
|
+
classifyTables(copy);
|
|
393
|
+
migrate(copy);
|
|
394
|
+
// Persona and account parts of the plan; applySettings adds the exact
|
|
395
|
+
// settings and API key changes inside its transaction and decides there.
|
|
396
|
+
plan = buildPlan({
|
|
397
|
+
digests: digestsFrom(restorableRows(copy), secretsPayload?.settings ?? {}),
|
|
398
|
+
personaSha: opened.manifest.entries.find((entry) => entry.kind === "persona")?.sha256 ?? null,
|
|
399
|
+
account: opened.manifest.account,
|
|
400
|
+
});
|
|
401
|
+
} finally { copy.close(); }
|
|
402
|
+
fsyncStagedTree(staged(restoreId));
|
|
403
|
+
writeJournal({ op: "restore", id: restoreId, step: "apply" });
|
|
404
|
+
onProgress?.({ phase: "apply", bytes: total, totalBytes: total });
|
|
405
|
+
const report = applySettings(restoreId, secretsPayload, { base: plan, confirmDestructive });
|
|
406
|
+
atomicJson(path.join(dir, "metadata.json"), { ...metadata(restoreId), report });
|
|
407
|
+
writeJournal({ op: "restore", id: restoreId, step: "persona" });
|
|
408
|
+
validateBeforePersona(restoreId);
|
|
409
|
+
crash("persona");
|
|
410
|
+
installPersona(restoreId);
|
|
411
|
+
crash("after-persona");
|
|
412
|
+
writeJournal({ op: "restore", id: restoreId, step: "pending" });
|
|
413
|
+
onProgress?.({ phase: "pending", bytes: total, totalBytes: total });
|
|
414
|
+
installPending(restoreId);
|
|
415
|
+
const result = finish(restoreId);
|
|
416
|
+
uploads.removeUpload(id);
|
|
417
|
+
onProgress?.({ phase: "done", bytes: total, totalBytes: total });
|
|
418
|
+
return result;
|
|
419
|
+
} catch (error) {
|
|
420
|
+
if (marker() === restoreId && readJournal()?.id === restoreId)
|
|
421
|
+
throw new BackupError("RESTORE_INCOMPLETE", "Restore will finish after restart");
|
|
422
|
+
if (!error.restoreTestCrash) {
|
|
423
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
424
|
+
clearJournal();
|
|
425
|
+
}
|
|
426
|
+
throw error;
|
|
427
|
+
} finally {
|
|
428
|
+
// Best-effort wipe of the decrypted secrets buffer. Parsed JS strings
|
|
429
|
+
// cannot be overwritten.
|
|
430
|
+
if (secretsBuffer) secretsBuffer.fill(0);
|
|
431
|
+
secretsPayload = null;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function restoreUpload(id, password, onProgress, options = {}) {
|
|
436
|
+
const pin = uploads.pinUpload(id);
|
|
437
|
+
if (!pin) throw new BackupError("NOT_FOUND", "Upload not found");
|
|
438
|
+
try { return await restorePinnedUpload(id, pin.path, password, onProgress, options); }
|
|
439
|
+
finally { pin.release(); }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function pendingStatus() {
|
|
443
|
+
const lastOutcome = readOutcome();
|
|
444
|
+
try {
|
|
445
|
+
const value = JSON.parse(fs.readFileSync(dataPath("restore", "pending", "pending.json"), "utf8"));
|
|
446
|
+
return { waiting: true, account: maskAccount(value.account), createdAt: value.createdAt,
|
|
447
|
+
backupCreated: value.backupCreated, counts: value.counts,
|
|
448
|
+
matchesPaired: accountsMatch(value.account, readPairedAccount()), lastOutcome };
|
|
449
|
+
} catch (error) { if (error.code === "ENOENT") return { waiting: false, lastOutcome }; throw error; }
|
|
450
|
+
}
|
|
451
|
+
function discardPending() {
|
|
452
|
+
const pending = dataPath("restore", "pending");
|
|
453
|
+
if (!fs.existsSync(pending)) return;
|
|
454
|
+
const trash = dataPath("restore", `${crypto.randomBytes(16).toString("hex")}.trash`);
|
|
455
|
+
fs.renameSync(pending, trash);
|
|
456
|
+
fs.rmSync(trash, { recursive: true, force: true });
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
module.exports = { restoreUpload, schemaCheck, expectedSchema, pendingStatus, discardPending, installPersona,
|
|
460
|
+
installPending, finish, marker, stageRoot, validateBeforePersona, setCrashHookForTest };
|
|
@@ -0,0 +1,146 @@
|
|
|
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, LIMITS } = require("./format.cjs");
|
|
6
|
+
const logger = require("../utils/logger.cjs");
|
|
7
|
+
|
|
8
|
+
const TTL = 60 * 60 * 1000;
|
|
9
|
+
const idRe = /^[0-9a-f]{32}$/;
|
|
10
|
+
const root = () => {
|
|
11
|
+
const folder = ensureDataDir("tmp", "restore");
|
|
12
|
+
if (process.platform !== "win32") fs.chmodSync(folder, 0o700);
|
|
13
|
+
return folder;
|
|
14
|
+
};
|
|
15
|
+
const filePath = (id) => idRe.test(id) ? path.join(root(), `${id}.levixbak`) : null;
|
|
16
|
+
const attempts = new Map();
|
|
17
|
+
const pins = new Map();
|
|
18
|
+
const pendingDelete = new Set();
|
|
19
|
+
let receiving = 0;
|
|
20
|
+
const activeParts = new Set();
|
|
21
|
+
|
|
22
|
+
function sweepUploads(all = false) {
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
for (const name of fs.readdirSync(root())) {
|
|
25
|
+
const file = path.join(root(), name);
|
|
26
|
+
const stat = fs.lstatSync(file);
|
|
27
|
+
const known = /^[0-9a-f]{32}\.levixbak(?:\.part)?$/.test(name);
|
|
28
|
+
const id = name.endsWith(".levixbak") ? name.slice(0, -9) : null;
|
|
29
|
+
if ((all || !known || now - stat.mtimeMs >= TTL || (id && pendingDelete.has(id))) &&
|
|
30
|
+
!activeParts.has(file) && !(id && pins.has(id))) {
|
|
31
|
+
fs.rmSync(file, { force: true, recursive: true });
|
|
32
|
+
if (id) { pendingDelete.delete(id); if (!lockedOut(id)) attempts.delete(id); }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (all) attempts.clear();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function removeUpload(id) {
|
|
39
|
+
const file = filePath(id);
|
|
40
|
+
if (file && pins.has(id)) pendingDelete.add(id);
|
|
41
|
+
else if (file) { fs.rmSync(file, { force: true }); pendingDelete.delete(id); }
|
|
42
|
+
if (!lockedOut(id)) attempts.delete(id);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function getUpload(id) {
|
|
46
|
+
const file = filePath(id);
|
|
47
|
+
if (!file) return null;
|
|
48
|
+
try {
|
|
49
|
+
const stat = fs.lstatSync(file);
|
|
50
|
+
if (!stat.isFile()) return null;
|
|
51
|
+
if (Date.now() - stat.mtimeMs >= TTL && !pins.has(id)) { removeUpload(id); return null; }
|
|
52
|
+
return file;
|
|
53
|
+
} catch (error) { if (error.code === "ENOENT") return null; throw error; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function pinUpload(id) {
|
|
57
|
+
const file = getUpload(id);
|
|
58
|
+
if (!file) return null;
|
|
59
|
+
pins.set(id, (pins.get(id) || 0) + 1);
|
|
60
|
+
let released = false;
|
|
61
|
+
return { path: file, release() {
|
|
62
|
+
if (released) return;
|
|
63
|
+
released = true;
|
|
64
|
+
const remaining = pins.get(id) - 1;
|
|
65
|
+
if (remaining) { pins.set(id, remaining); return; }
|
|
66
|
+
pins.delete(id);
|
|
67
|
+
try {
|
|
68
|
+
const stat = fs.statSync(file, { throwIfNoEntry: false });
|
|
69
|
+
if (pendingDelete.has(id) || (stat && Date.now() - stat.mtimeMs >= TTL)) removeUpload(id);
|
|
70
|
+
} catch { logger.error("[Backup] Could not remove released upload"); }
|
|
71
|
+
} };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function wrongPassword(id) {
|
|
75
|
+
const count = (attempts.get(id) || 0) + 1;
|
|
76
|
+
attempts.set(id, count);
|
|
77
|
+
if (count >= 5) {
|
|
78
|
+
if (pins.has(id)) pendingDelete.add(id);
|
|
79
|
+
else {
|
|
80
|
+
const file = filePath(id);
|
|
81
|
+
if (file) fs.rmSync(file, { force: true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return count > 5;
|
|
85
|
+
}
|
|
86
|
+
function lockedOut(id) { return (attempts.get(id) || 0) >= 5; }
|
|
87
|
+
|
|
88
|
+
async function receiveUpload(req) {
|
|
89
|
+
const header = req.headers["content-length"];
|
|
90
|
+
if (header === undefined) throw new BackupError("LENGTH_REQUIRED", "Content length required");
|
|
91
|
+
if (!/^\d+$/.test(header)) throw new BackupError("BAD_LENGTH", "Invalid content length");
|
|
92
|
+
const length = Number(header);
|
|
93
|
+
if (!Number.isSafeInteger(length) || length > LIMITS.file) throw new BackupError("LIMIT", "Upload too large");
|
|
94
|
+
sweepUploads();
|
|
95
|
+
if (fs.readdirSync(root()).filter((name) => /^[0-9a-f]{32}\.levixbak$/.test(name)).length + receiving >= 2)
|
|
96
|
+
throw new BackupError("BUSY", "Too many uploads");
|
|
97
|
+
const space = fs.statfsSync(root());
|
|
98
|
+
if (Number(space.bavail) * Number(space.bsize) < length + 64 * 1024 ** 2)
|
|
99
|
+
throw new BackupError("NO_SPACE", "Insufficient storage");
|
|
100
|
+
receiving += 1;
|
|
101
|
+
const id = crypto.randomBytes(16).toString("hex");
|
|
102
|
+
const part = path.join(root(), `${id}.levixbak.part`);
|
|
103
|
+
activeParts.add(part);
|
|
104
|
+
const final = filePath(id);
|
|
105
|
+
let fd;
|
|
106
|
+
let size = 0;
|
|
107
|
+
try {
|
|
108
|
+
fd = fs.openSync(part, "wx", 0o600);
|
|
109
|
+
for await (const chunk of req) {
|
|
110
|
+
size += chunk.length;
|
|
111
|
+
if (size > length) throw new BackupError("BAD_LENGTH", "Upload length mismatch");
|
|
112
|
+
for (let offset = 0; offset < chunk.length;) {
|
|
113
|
+
const written = fs.writeSync(fd, chunk, offset, chunk.length - offset);
|
|
114
|
+
if (!written) throw new BackupError("IO", "Upload write failed");
|
|
115
|
+
offset += written;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (size !== length) throw new BackupError("BAD_LENGTH", "Upload length mismatch");
|
|
119
|
+
fs.fsyncSync(fd);
|
|
120
|
+
fs.closeSync(fd);
|
|
121
|
+
fd = null;
|
|
122
|
+
fs.renameSync(part, final);
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
try {
|
|
125
|
+
const stat = fs.statSync(final, { throwIfNoEntry: false });
|
|
126
|
+
if (stat && Date.now() - stat.mtimeMs >= TTL) {
|
|
127
|
+
if (pins.has(id)) pendingDelete.add(id);
|
|
128
|
+
else removeUpload(id);
|
|
129
|
+
}
|
|
130
|
+
} catch { logger.error("[Backup] Could not expire upload"); }
|
|
131
|
+
}, TTL);
|
|
132
|
+
timer.unref();
|
|
133
|
+
return { uploadId: id, size };
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (fd !== undefined && fd !== null) fs.closeSync(fd);
|
|
136
|
+
fs.rmSync(part, { force: true });
|
|
137
|
+
if (size !== length && !(error instanceof BackupError))
|
|
138
|
+
throw new BackupError("BAD_LENGTH", "Upload length mismatch");
|
|
139
|
+
throw error;
|
|
140
|
+
} finally {
|
|
141
|
+
activeParts.delete(part);
|
|
142
|
+
receiving -= 1;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = { receiveUpload, getUpload, pinUpload, removeUpload, wrongPassword, lockedOut, sweepUploads, idRe };
|