synabun 2.4.1 → 2.4.2
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/CHANGELOG.md +30 -0
- package/README.md +1 -1
- package/browser-extension/content.js +56 -14
- package/browser-extension/engine.js +158 -8
- package/browser-extension/manifest.json +3 -1
- package/browser-extension/protocol.js +91 -6
- package/browser-extension/service-worker.js +13 -5
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +24 -4
- package/lib/data-home-files.js +4 -2
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +5 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +11 -7
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +27 -9
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +22 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +26 -9
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +263 -1
- package/neural-interface/i18n/pt-BR.json +264 -2
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +257 -95
- package/neural-interface/lib/assistant-persona.js +16 -4
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +131 -47
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +39 -33
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +788 -233
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +89 -13
- package/neural-interface/lib/browser-extension-bridge.js +18 -7
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +28 -7
- package/neural-interface/lib/opencode-build-preflight.js +18 -1
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +31 -43
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +194 -95
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +233 -24
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +1 -1
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +105 -38
- package/neural-interface/public/shared/assistant/asst-route.js +100 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -52
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +341 -437
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +124 -17
- package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +224 -65
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +5 -1
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +477 -139
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
accessSync,
|
|
3
|
+
chmodSync,
|
|
3
4
|
closeSync,
|
|
4
5
|
copyFileSync,
|
|
5
6
|
constants as FS_CONSTANTS,
|
|
@@ -18,17 +19,27 @@ import {
|
|
|
18
19
|
unlinkSync,
|
|
19
20
|
writeFileSync,
|
|
20
21
|
} from 'node:fs';
|
|
22
|
+
import { chmod, copyFile, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
21
23
|
import { execFileSync } from 'node:child_process';
|
|
22
24
|
import { createHash } from 'node:crypto';
|
|
23
25
|
import { basename, dirname, extname, isAbsolute, join, parse as parsePath, relative, resolve, sep } from 'node:path';
|
|
24
26
|
import * as nodeSqlite from 'node:sqlite';
|
|
25
27
|
import { DatabaseSync } from 'node:sqlite';
|
|
26
|
-
import { Worker } from 'node:worker_threads';
|
|
28
|
+
import { parentPort, Worker, workerData } from 'node:worker_threads';
|
|
27
29
|
import archiver from 'archiver';
|
|
30
|
+
import { markActivity } from './loop-stall.js';
|
|
28
31
|
import { openZipArchive, readZipEntry, verifyBackupChecksums } from './backup-zip-reader.js';
|
|
29
32
|
import { writeZipArchive } from './backup-zip-writer.js';
|
|
33
|
+
import { authKeyOf, BACKUP_ENC_EXTENSION, BackupEncryptionError, isEncryptedBackupFile, readBackupHeaderFile, snapshotRecordDigest } from './backup-crypto.js';
|
|
34
|
+
import { sweepRestoreStages } from './backup-restore-stage.js';
|
|
35
|
+
import { createEncryptedBackupWriter, openEncryptedBackupSource } from './backup-crypto-io.js';
|
|
36
|
+
import { backupRecipientFor } from './backup-encryption.js';
|
|
30
37
|
import { hashFileSync, walkDataHomeTree } from '../../lib/data-home-files.js';
|
|
31
38
|
import { LOCK_FILE_NAME } from './rulesets/lock.js';
|
|
39
|
+
import {
|
|
40
|
+
BACKUP_GROUP_IDS, backupGroupOf, checkManifestGroups, dataDirsOfGroup, estimateArchivedBytes, isNeverBackedUp,
|
|
41
|
+
isNeverBackedUpDir, manifestGroups, selectedBackupGroups,
|
|
42
|
+
} from './backup-groups.js';
|
|
32
43
|
|
|
33
44
|
export const BACKUP_MANIFEST_VERSION = 3;
|
|
34
45
|
export const BACKUP_PREFIX = 'synabun-auto-backup';
|
|
@@ -129,7 +140,10 @@ const ESSENTIAL_STATE_EXTENSIONS = new Set(['.db', '.sqlite', '.sqlite3', '.json
|
|
|
129
140
|
// npm update path is what made upgrades look broken.
|
|
130
141
|
const UPGRADE_SNAPSHOT_SOFT_LIMIT_BYTES = 1024 * 1024 * 1024;
|
|
131
142
|
|
|
143
|
+
// For estimates only (what a snapshot leaves out, a progress hint): any file it cannot stat counts as 0 bytes. A
|
|
144
|
+
// decision about what to archive uses backupFileSize, where only a missing file is 0 and any other error is thrown.
|
|
132
145
|
function fileBytes(path) {
|
|
146
|
+
reportBackupWorkerProgress();
|
|
133
147
|
try { return statSync(path).size; } catch { return 0; }
|
|
134
148
|
}
|
|
135
149
|
|
|
@@ -183,8 +197,73 @@ function safeTimestamp(date) {
|
|
|
183
197
|
return date.toISOString().replace(/[:.]/g, '-');
|
|
184
198
|
}
|
|
185
199
|
|
|
186
|
-
function archiveNameFor(kind, createdAt) {
|
|
187
|
-
return `synabun-${kind}-${safeTimestamp(createdAt)}.zip`;
|
|
200
|
+
function archiveNameFor(kind, createdAt, encrypted = false) {
|
|
201
|
+
return `synabun-${kind}-${safeTimestamp(createdAt)}.zip${encrypted ? BACKUP_ENC_EXTENSION : ''}`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── Encryption (lib/backup-encryption.js, docs/backup-encryption.md) ──
|
|
205
|
+
//
|
|
206
|
+
// Every function that makes a backup asks here who it is for, by itself: a caller that says nothing gets what the
|
|
207
|
+
// data home's key file says, so a new caller cannot forget it. There is no way to ask for a plain backup while the
|
|
208
|
+
// owner has encryption on, and no fallback to one: when the key file is there and cannot be used, the lookup throws
|
|
209
|
+
// and the backup fails.
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Who a backup of `dataHome` is encrypted for: null (the owner has not turned encryption on) or
|
|
213
|
+
* { recipient, chunkSize? }. `encryption`: what the caller passed; undefined means "what the owner set".
|
|
214
|
+
*/
|
|
215
|
+
function backupEncryptionFor(dataHome, encryption) {
|
|
216
|
+
if (encryption === undefined) {
|
|
217
|
+
const recipient = backupRecipientFor(dataHome);
|
|
218
|
+
return recipient ? { recipient } : null;
|
|
219
|
+
}
|
|
220
|
+
if (encryption && typeof encryption === 'object' && encryption.recipient) return encryption;
|
|
221
|
+
throw new BackupEncryptionError('BACKUP_ENC_OPTION', 'createVerifiedBackup: `encryption` is { recipient } or left out', { status: 500 });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Where an encrypted backup stages its plaintext copies: inside the data home, never in the destination folder. */
|
|
225
|
+
export function privateBackupStagingRoot(dataHome) {
|
|
226
|
+
return resolve(dataHome, 'backups', 'encrypt-staging');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The staging folder of an encrypted backup, made private (0700): the copies in it are plaintext, and the
|
|
231
|
+
* destination may be a drive without permissions or a folder another program uploads. Removed with the backup.
|
|
232
|
+
*/
|
|
233
|
+
async function makePrivateStage(dataHome) {
|
|
234
|
+
const root = privateBackupStagingRoot(dataHome);
|
|
235
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
236
|
+
if (process.platform !== 'win32') await chmod(root, 0o700);
|
|
237
|
+
const stage = await mkdtemp(resolve(root, `.synabun-files-${process.pid}-`));
|
|
238
|
+
if (process.platform !== 'win32') await chmod(stage, 0o700);
|
|
239
|
+
return stage;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The sidecar of an encrypted upgrade snapshot: what a later start reads without the password (see writeSnapshotInfo). */
|
|
243
|
+
export function backupInfoPath(path) {
|
|
244
|
+
return `${path}.info.json`;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Removes a backup file and what belongs to it (an encrypted upgrade snapshot's sidecar). */
|
|
248
|
+
export async function removeBackupFile(path) {
|
|
249
|
+
await unlink(path);
|
|
250
|
+
await rm(backupInfoPath(path), { force: true }).catch(() => {});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function pathInside(candidate, parent) {
|
|
254
|
+
const rel = relative(resolve(parent), resolve(candidate));
|
|
255
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Room on two volumes: the archive in the destination, the staged copies in the data home's private folder. */
|
|
259
|
+
function checkSplitWorkingSpace(folderPath, stageRoot, estimate, getAvailableBytes, reserveBytes) {
|
|
260
|
+
let sameVolume = true;
|
|
261
|
+
try { sameVolume = statSync(folderPath).dev === statSync(stageRoot).dev; } catch { /* one check, as before */ }
|
|
262
|
+
if (sameVolume) return checkWorkingSpace(folderPath, estimate, getAvailableBytes);
|
|
263
|
+
const reserve = Math.max(0, Number(reserveBytes) || 0);
|
|
264
|
+
const staged = estimate.stagedMutableBytes + estimate.sqliteSnapshotBytes;
|
|
265
|
+
checkWorkingSpace(stageRoot, { ...estimate, requiredBytes: reserve + staged }, getAvailableBytes);
|
|
266
|
+
return checkWorkingSpace(folderPath, { ...estimate, requiredBytes: Math.max(0, estimate.requiredBytes - staged) }, getAvailableBytes);
|
|
188
267
|
}
|
|
189
268
|
|
|
190
269
|
function hashFile(path) {
|
|
@@ -201,28 +280,6 @@ function escapeSqliteString(value) {
|
|
|
201
280
|
return String(value).replace(/'/g, "''");
|
|
202
281
|
}
|
|
203
282
|
|
|
204
|
-
function createConsistentSqliteSnapshot(sourcePath, snapshotPath) {
|
|
205
|
-
if (!existsSync(sourcePath)) return null;
|
|
206
|
-
try { if (existsSync(snapshotPath)) unlinkSync(snapshotPath); } catch {}
|
|
207
|
-
let source;
|
|
208
|
-
let snapshot;
|
|
209
|
-
try {
|
|
210
|
-
source = new DatabaseSync(sourcePath);
|
|
211
|
-
source.exec('PRAGMA busy_timeout = 10000');
|
|
212
|
-
source.exec(`VACUUM INTO '${escapeSqliteString(snapshotPath)}'`);
|
|
213
|
-
snapshot = new DatabaseSync(snapshotPath, { readOnly: true });
|
|
214
|
-
const integrityRow = snapshot.prepare('PRAGMA integrity_check').get();
|
|
215
|
-
const integrity = integrityRow?.integrity_check || integrityRow?.integrity || 'unknown';
|
|
216
|
-
if (integrity !== 'ok') throw new Error(`SQLite snapshot integrity check returned: ${integrity}`);
|
|
217
|
-
let memoryCount = null;
|
|
218
|
-
try { memoryCount = Number(snapshot.prepare('SELECT COUNT(*) AS count FROM memories').get()?.count || 0); } catch {}
|
|
219
|
-
return { path: snapshotPath, integrity, memoryCount, sizeBytes: statSync(snapshotPath).size };
|
|
220
|
-
} finally {
|
|
221
|
-
try { snapshot?.close(); } catch {}
|
|
222
|
-
try { source?.close(); } catch {}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
283
|
// SQLite rollback journals, including the ones left beside migration copies
|
|
227
284
|
// (memory.db.pre-v4-….bak-journal). They are only meaningful next to the file
|
|
228
285
|
// they belonged to, and that file is snapshotted consistently or not at all.
|
|
@@ -241,19 +298,19 @@ export function isLocalProfileFolderPath(relativePath) {
|
|
|
241
298
|
return parts[0] === 'local-profiles' && parts.length > 2;
|
|
242
299
|
}
|
|
243
300
|
|
|
301
|
+
// What no archive of any kind holds: one list, in backup-groups.js (isNeverBackedUp), asked by the full backup, the
|
|
302
|
+
// upgrade snapshot and the size estimate. It names what the three lists above name, and since 2026-11-21 also every
|
|
303
|
+
// log (a rotated server-stdout.log.1 was 50 MB of a backup), the launcher's and supervisor's records, the hooks' lock
|
|
304
|
+
// file, the automation browser's Chromium profiles, imports left in staging, and the system's own .DS_Store files.
|
|
244
305
|
function shouldSkipDataPath(relativePath) {
|
|
245
306
|
const normalized = relativePath.replace(/\\/g, '/');
|
|
246
307
|
const parts = normalized.split('/');
|
|
247
308
|
const name = parts.at(-1);
|
|
309
|
+
if (isNeverBackedUp(normalized)) return true;
|
|
248
310
|
if (isLocalProfileFolderPath(normalized)) return true;
|
|
249
|
-
if (parts[0] === 'updater') return true;
|
|
250
|
-
if (parts[0] === 'logs') return true;
|
|
251
311
|
if (parts.length > 1 && EXCLUDED_DATA_DIRS.has(parts[0])) return true;
|
|
252
312
|
if (TRANSIENT_DATA_NAMES.has(name)) return true;
|
|
253
313
|
if (isLockOnlyDataFile(name)) return true;
|
|
254
|
-
if (name.endsWith('.tmp') || name.endsWith('.pid')) return true;
|
|
255
|
-
if (/\.db-(?:wal|shm)$/i.test(name)) return true;
|
|
256
|
-
if (SQLITE_JOURNAL_RE.test(name)) return true;
|
|
257
314
|
return false;
|
|
258
315
|
}
|
|
259
316
|
|
|
@@ -306,20 +363,24 @@ export function assertBackupDestinationMounted(folderPath, options) {
|
|
|
306
363
|
|
|
307
364
|
// De-duplicate as files are discovered. Later additional entries take precedence,
|
|
308
365
|
// as before, without constructing an argument list or a second subtree listing.
|
|
309
|
-
|
|
366
|
+
// `skipDirs[dir]`: a folder of that data folder (relative path) the walk does not enter, because the filter would
|
|
367
|
+
// drop every file in it anyway.
|
|
368
|
+
function collectBackupFiles(dataHome, filters, additionalEntries, skipDirs = {}) {
|
|
310
369
|
const entries = new Map();
|
|
311
370
|
const add = (diskPath, archivePath) => entries.set(archivePath.replace(/\\/g, '/'), { diskPath, archivePath });
|
|
312
371
|
const envPath = resolve(dataHome, '.env');
|
|
313
372
|
if (existsSync(envPath)) add(envPath, 'env.bak');
|
|
314
373
|
|
|
315
|
-
function collect(root, archiveRoot, filter) {
|
|
316
|
-
|
|
374
|
+
function collect(root, archiveRoot, filter, skipDir = null) {
|
|
375
|
+
const descend = skipDir ? (path) => !skipDir(relative(root, path).replace(/\\/g, '/')) : null;
|
|
376
|
+
for (const { path, stat } of walkDataHomeTree(root, { descend })) {
|
|
377
|
+
reportBackupWorkerProgress();
|
|
317
378
|
if (!stat.isFile()) continue;
|
|
318
379
|
const rel = relative(root, path).replace(/\\/g, '/');
|
|
319
380
|
if (!filter || filter(rel)) add(path, rel ? `${archiveRoot}/${rel}` : archiveRoot);
|
|
320
381
|
}
|
|
321
382
|
}
|
|
322
|
-
for (const dir of BACKUP_DATA_DIRS) collect(resolve(dataHome, dir), dir, filters[dir]);
|
|
383
|
+
for (const dir of BACKUP_DATA_DIRS) collect(resolve(dataHome, dir), dir, filters[dir], skipDirs[dir]);
|
|
323
384
|
for (const entry of additionalEntries) {
|
|
324
385
|
if (entry?.diskPath && entry?.archivePath) collect(entry.diskPath, entry.archivePath);
|
|
325
386
|
}
|
|
@@ -327,6 +388,7 @@ function collectBackupFiles(dataHome, filters, additionalEntries) {
|
|
|
327
388
|
}
|
|
328
389
|
|
|
329
390
|
function backupFileSize(file) {
|
|
391
|
+
reportBackupWorkerProgress();
|
|
330
392
|
try { return statSync(file.diskPath).size; }
|
|
331
393
|
catch (error) {
|
|
332
394
|
if (error?.code === 'ENOENT') return 0;
|
|
@@ -350,13 +412,11 @@ export function backupAvailableBytes(folderPath) {
|
|
|
350
412
|
return Number(stats.bavail) * Number(stats.bsize);
|
|
351
413
|
}
|
|
352
414
|
|
|
353
|
-
|
|
354
|
-
folderPath,
|
|
415
|
+
function estimateBackupWorkingSpace({
|
|
355
416
|
files = [],
|
|
356
417
|
databasePath = null,
|
|
357
418
|
expectedArchiveBytes = 0,
|
|
358
419
|
freeSpaceReserveBytes = BACKUP_FREE_SPACE_RESERVE_BYTES,
|
|
359
|
-
getAvailableBytes = backupAvailableBytes,
|
|
360
420
|
} = {}) {
|
|
361
421
|
const primaryDatabaseBytes = databasePath && existsSync(databasePath) ? statSync(databasePath).size : 0;
|
|
362
422
|
let inputBytes = primaryDatabaseBytes;
|
|
@@ -373,17 +433,19 @@ export function assertBackupWorkingSpace({
|
|
|
373
433
|
+ stagedMutableBytes
|
|
374
434
|
+ sqliteSnapshotBytes
|
|
375
435
|
+ archiveBytes;
|
|
436
|
+
return { requiredBytes, archiveBytes, stagedMutableBytes, sqliteSnapshotBytes };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function checkWorkingSpace(folderPath, estimate, getAvailableBytes) {
|
|
376
440
|
const availableBytes = Number(getAvailableBytes(folderPath));
|
|
377
|
-
if (Number.isFinite(availableBytes) && availableBytes < requiredBytes) {
|
|
378
|
-
throw new BackupStorageError({ availableBytes, requiredBytes, folderPath });
|
|
441
|
+
if (Number.isFinite(availableBytes) && availableBytes < estimate.requiredBytes) {
|
|
442
|
+
throw new BackupStorageError({ availableBytes, requiredBytes: estimate.requiredBytes, folderPath });
|
|
379
443
|
}
|
|
380
|
-
return {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
sqliteSnapshotBytes,
|
|
386
|
-
};
|
|
444
|
+
return { availableBytes, ...estimate };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function assertBackupWorkingSpace({ folderPath, getAvailableBytes = backupAvailableBytes, ...inputs } = {}) {
|
|
448
|
+
return checkWorkingSpace(folderPath, estimateBackupWorkingSpace(inputs), getAvailableBytes);
|
|
387
449
|
}
|
|
388
450
|
|
|
389
451
|
/**
|
|
@@ -392,20 +454,27 @@ export function assertBackupWorkingSpace({
|
|
|
392
454
|
* so its partial archive is orphaned forever — a killed pre-update snapshot
|
|
393
455
|
* left hundreds of MB behind with nothing to reclaim it.
|
|
394
456
|
*/
|
|
395
|
-
export function cleanupStaleBackupArtifacts(folderPath, { maxAgeMs = 60 * 60 * 1000, now = Date.now } = {}) {
|
|
457
|
+
export function cleanupStaleBackupArtifacts(folderPath, { maxAgeMs = 60 * 60 * 1000, now = Date.now, ownerGone = null } = {}) {
|
|
396
458
|
if (!existsSync(folderPath)) return [];
|
|
397
459
|
const removed = [];
|
|
398
460
|
let entries;
|
|
399
461
|
try { entries = readdirSync(folderPath); }
|
|
400
462
|
catch { return removed; }
|
|
401
463
|
for (const name of entries) {
|
|
402
|
-
|
|
464
|
+
reportBackupWorkerProgress();
|
|
465
|
+
const archiveTemp = name.match(/\.zip(?:\.enc)?(?:\.info\.json)?\.(\d+)\.tmp$/);
|
|
403
466
|
const isSqliteTemp = /^\.synabun-(?:db|extra-db)-.*\.tmp$/.test(name);
|
|
404
|
-
const
|
|
405
|
-
|
|
467
|
+
const stageDir = name.match(/^\.synabun-files-(\d+)-/);
|
|
468
|
+
// A sidecar whose snapshot is gone (its removal was interrupted) describes nothing.
|
|
469
|
+
const orphanInfo = /\.zip\.enc\.info\.json$/.test(name) && !entries.includes(name.slice(0, -'.info.json'.length));
|
|
470
|
+
if (!archiveTemp && !isSqliteTemp && !stageDir && !orphanInfo) continue;
|
|
406
471
|
const path = resolve(folderPath, name);
|
|
407
472
|
try {
|
|
408
|
-
|
|
473
|
+
// The process that made it is named in it. One that is gone will never finish or remove it: it goes now,
|
|
474
|
+
// whatever its age (a staged copy is plaintext). One that still runs keeps its files for `maxAgeMs`.
|
|
475
|
+
const owner = Number((archiveTemp || stageDir)?.[1]) || 0;
|
|
476
|
+
const abandoned = !!ownerGone && owner > 0 && owner !== process.pid && ownerGone(owner);
|
|
477
|
+
if (!abandoned && now() - statSync(path).mtimeMs < maxAgeMs) continue;
|
|
409
478
|
rmSync(path, { recursive: true, force: true });
|
|
410
479
|
removed.push(name);
|
|
411
480
|
} catch { /* another process may be mid-cleanup; leave it */ }
|
|
@@ -413,38 +482,121 @@ export function cleanupStaleBackupArtifacts(folderPath, { maxAgeMs = 60 * 60 * 1
|
|
|
413
482
|
return removed;
|
|
414
483
|
}
|
|
415
484
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
485
|
+
/**
|
|
486
|
+
* cleanupCrashedBackupArtifacts on a worker thread: the server calls it once as it starts, and a backup folder can
|
|
487
|
+
* be a drive that answers slowly. `before` defaults to when this process started.
|
|
488
|
+
*/
|
|
489
|
+
export function sweepCrashedBackupArtifacts({ dataHome, folders = [], scratchFolders = [], before = Date.now() - Math.round(process.uptime() * 1000), workerOptions = {} } = {}) {
|
|
490
|
+
if (!dataHome) throw new Error('dataHome is required');
|
|
491
|
+
return runBackupTask('sweep', { dataHome, folders, scratchFolders, before }, workerOptions);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** True when no process has this id any more. A process this one may not signal (EPERM) is there. */
|
|
495
|
+
export function processIsGone(pid) {
|
|
496
|
+
try { process.kill(pid, 0); return false; }
|
|
497
|
+
catch (error) { return error?.code === 'ESRCH'; }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* What a backup that never finished left behind (a crash, a kill, a power cut): the partial archives, the staged
|
|
502
|
+
* plaintext copies and the uploads of a restore. The server calls this once as it starts, for every folder a backup
|
|
503
|
+
* can have worked in; `folders` that do not exist are skipped. Working files of a process that is gone are removed
|
|
504
|
+
* at once, the rest after an hour, as before a backup. Returns the names removed, by folder.
|
|
505
|
+
* @param {{ dataHome: string, folders?: string[], scratchFolders?: string[] }} o `scratchFolders`: folders that hold
|
|
506
|
+
* nothing but working files of this server (restore uploads, the browser download's staging): emptied.
|
|
507
|
+
*/
|
|
508
|
+
export function cleanupCrashedBackupArtifacts({ dataHome, folders = [], scratchFolders = [], ownerGone = processIsGone, before = Date.now() } = {}) {
|
|
509
|
+
const removed = {};
|
|
510
|
+
const sweep = [...new Set([privateBackupStagingRoot(dataHome), resolve(dataHome, 'backups', 'updates'), ...folders.filter(Boolean).map(folder => resolve(folder))])];
|
|
511
|
+
for (const folder of sweep) {
|
|
512
|
+
let names = [];
|
|
513
|
+
try { names = cleanupStaleBackupArtifacts(folder, { ownerGone }); } catch { /* a drive that is not there */ }
|
|
514
|
+
if (names.length) removed[folder] = names;
|
|
515
|
+
}
|
|
516
|
+
// The command-line restore stages next to the data home; a killed one leaves decrypted files there.
|
|
420
517
|
try {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
518
|
+
const stages = sweepRestoreStages(dataHome, { ownerGone });
|
|
519
|
+
if (stages.length) removed[dirname(resolve(dataHome))] = stages;
|
|
520
|
+
} catch { /* a parent folder that cannot be read */ }
|
|
521
|
+
for (const folder of scratchFolders.filter(Boolean).map(item => resolve(item))) {
|
|
522
|
+
let names = [];
|
|
523
|
+
try { names = readdirSync(folder); } catch { continue; }
|
|
524
|
+
const gone = [];
|
|
525
|
+
for (const name of names) {
|
|
526
|
+
// `before`: when this server started. What was written since belongs to a request it is serving now.
|
|
428
527
|
try {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
// longer part of the state being backed up. Other failures are fatal.
|
|
434
|
-
if (error?.code !== 'ENOENT') throw error;
|
|
435
|
-
}
|
|
528
|
+
if (statSync(resolve(folder, name)).mtimeMs >= before) continue;
|
|
529
|
+
rmSync(resolve(folder, name), { recursive: true, force: true });
|
|
530
|
+
gone.push(name);
|
|
531
|
+
} catch { /* in use */ }
|
|
436
532
|
}
|
|
437
|
-
|
|
438
|
-
}
|
|
439
|
-
|
|
533
|
+
if (gone.length) removed[folder] = [...(removed[folder] || []), ...gone];
|
|
534
|
+
}
|
|
535
|
+
return removed;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** Raised when a backup is cancelled (createVerifiedBackup `signal`): nothing is published, its working files are removed. */
|
|
539
|
+
export class BackupCancelledError extends Error {
|
|
540
|
+
constructor() {
|
|
541
|
+
super('The backup was cancelled.');
|
|
542
|
+
this.name = 'BackupCancelledError';
|
|
543
|
+
this.code = 'BACKUP_CANCELLED';
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function throwIfCancelled(signal) {
|
|
548
|
+
if (signal?.aborted) throw new BackupCancelledError();
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Start a worker task and await it, stopping its thread when `signal` aborts (the task then rejects, and this throws
|
|
553
|
+
* cancelled). `start` is called only when the backup is not already cancelled: a thread started for a cancelled backup
|
|
554
|
+
* would run on against working files its caller is removing.
|
|
555
|
+
*/
|
|
556
|
+
async function cancellable(start, signal) {
|
|
557
|
+
throwIfCancelled(signal);
|
|
558
|
+
const task = start();
|
|
559
|
+
if (!signal) return task;
|
|
560
|
+
const stop = () => { try { task.cancel?.(); } catch { /* already over */ } };
|
|
561
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
562
|
+
try { return await task; }
|
|
563
|
+
catch (error) {
|
|
564
|
+
// The thread's own end is kept on the error: the caller's cleanup tries again once native I/O has let go.
|
|
565
|
+
if (signal.aborted) throw Object.assign(new BackupCancelledError(), { workerTermination: error?.workerTermination });
|
|
440
566
|
throw error;
|
|
567
|
+
} finally { signal.removeEventListener('abort', stop); }
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// `privateFiles`: the copies are made readable by their owner alone (an encrypted backup's staging).
|
|
571
|
+
async function snapshotMutableBackupFiles(files, stageDir, signal = null, { privateFiles = false } = {}) {
|
|
572
|
+
const snapshots = [];
|
|
573
|
+
for (const [index, file] of files.entries()) {
|
|
574
|
+
throwIfCancelled(signal);
|
|
575
|
+
if (!isMutableBackupInput(file)) {
|
|
576
|
+
snapshots.push(file);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
const diskPath = resolve(stageDir, String(index));
|
|
580
|
+
try {
|
|
581
|
+
await copyFile(file.diskPath, diskPath);
|
|
582
|
+
if (privateFiles && process.platform !== 'win32') await chmod(diskPath, 0o600);
|
|
583
|
+
snapshots.push({ ...file, diskPath });
|
|
584
|
+
} catch (error) {
|
|
585
|
+
// A runtime file deleted since enumeration is no longer part of the backup.
|
|
586
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
587
|
+
}
|
|
441
588
|
}
|
|
589
|
+
return snapshots;
|
|
442
590
|
}
|
|
443
591
|
|
|
444
|
-
|
|
592
|
+
// `output`: where the archive goes instead of a new file at `tempPath` (the encrypted writer's stream).
|
|
593
|
+
async function writeArchive({ tempPath, files, manifest, level = 6, signal = null, output: givenOutput = null }) {
|
|
445
594
|
const { createWriteStream } = await import('node:fs');
|
|
446
|
-
|
|
447
|
-
|
|
595
|
+
throwIfCancelled(signal);
|
|
596
|
+
let onAbort = null;
|
|
597
|
+
try {
|
|
598
|
+
await new Promise((resolveWrite, reject) => {
|
|
599
|
+
const output = givenOutput || createWriteStream(tempPath, { flags: 'wx' });
|
|
448
600
|
const archive = archiver('zip', { zlib: { level } });
|
|
449
601
|
const remaining = files.values();
|
|
450
602
|
let failure;
|
|
@@ -454,6 +606,8 @@ async function writeArchive({ tempPath, files, manifest, level = 6 }) {
|
|
|
454
606
|
archive.abort();
|
|
455
607
|
output.destroy();
|
|
456
608
|
}
|
|
609
|
+
onAbort = () => fail(new BackupCancelledError());
|
|
610
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
457
611
|
// Archiver queues a stat and a lazy stream for each file handed to it.
|
|
458
612
|
// Feed one member after the preceding entry has finished.
|
|
459
613
|
function appendNext() {
|
|
@@ -473,30 +627,108 @@ async function writeArchive({ tempPath, files, manifest, level = 6 }) {
|
|
|
473
627
|
archive.on('entry', appendNext);
|
|
474
628
|
archive.pipe(output);
|
|
475
629
|
archive.append(JSON.stringify(manifest, null, 2), { name: `${BACKUP_PREFIX}/manifest.json` });
|
|
476
|
-
|
|
630
|
+
});
|
|
631
|
+
} finally {
|
|
632
|
+
if (onAbort) signal?.removeEventListener('abort', onAbort);
|
|
633
|
+
}
|
|
477
634
|
}
|
|
478
635
|
|
|
479
636
|
/**
|
|
480
637
|
* Reopen a finished archive and stream every manifest-listed entry through
|
|
481
638
|
* sha256. Streaming matters: reading the archive into memory failed every
|
|
482
639
|
* backup over 2 GiB, which is when a backup matters most.
|
|
640
|
+
*
|
|
641
|
+
* An archive whose manifest records its groups (backup-groups.js) is also held to them: it holds exactly the groups
|
|
642
|
+
* it names, the memory database exactly when `memories` is one of them, and no entry its manifest does not list.
|
|
643
|
+
* `signal`: stops between two entries (BackupCancelledError).
|
|
644
|
+
*/
|
|
645
|
+
/**
|
|
646
|
+
* A backup file opened as a ZIP, encrypted or not (told by how the file begins, never by its name). An encrypted
|
|
647
|
+
* one needs `fileKey` (the backup just written) or `password`; without either it throws BACKUP_PASSWORD_REQUIRED,
|
|
648
|
+
* with a wrong password WRONG_PASSWORD, and nothing of its contents is read. The ZIP inside is read through the
|
|
649
|
+
* decrypting source: no plaintext copy of the archive is written. `zip.encrypted` says which it was.
|
|
483
650
|
*/
|
|
484
|
-
export async function
|
|
485
|
-
|
|
651
|
+
export async function openBackupArchive(path, { fileKey = null, authKey = null, password = null, inline = false } = {}) {
|
|
652
|
+
if (!(await isEncryptedBackupFile(path))) return openZipArchive(path);
|
|
653
|
+
const source = await openEncryptedBackupSource(path, { fileKey, authKey, password, inline });
|
|
654
|
+
return openZipArchive(path, { source });
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* For an encrypted archive (`fileKey` with `authKey`, or `password`, as openBackupArchive) the check also opens every part of the
|
|
659
|
+
* file the ZIP's entries did not reach, so that every byte of it has passed its authentication.
|
|
660
|
+
*/
|
|
661
|
+
export async function verifyBackupArchive(path, { onBytes = null, signal = null, fileKey = null, authKey = null, password = null, inline = false } = {}) {
|
|
662
|
+
const zip = await openBackupArchive(path, { fileKey, authKey, password, inline });
|
|
486
663
|
try {
|
|
487
664
|
const manifestEntry = zip.getEntry(`${BACKUP_PREFIX}/manifest.json`);
|
|
488
665
|
if (!manifestEntry) throw new Error('Backup verification failed: manifest is missing');
|
|
489
666
|
const manifest = JSON.parse((await readZipEntry(zip, manifestEntry)).toString('utf-8'));
|
|
490
|
-
|
|
667
|
+
assertBackupGroups(zip, manifest, BACKUP_PREFIX, 'Backup verification failed');
|
|
668
|
+
await verifyBackupChecksums(zip, { prefix: BACKUP_PREFIX, manifest, onBytes, signal });
|
|
669
|
+
throwIfCancelled(signal);
|
|
670
|
+
if (zip.encrypted) await zip.source.authenticateRest({ signal });
|
|
671
|
+
throwIfCancelled(signal);
|
|
491
672
|
return manifest;
|
|
673
|
+
} catch (error) {
|
|
674
|
+
if (signal?.aborted) throw new BackupCancelledError();
|
|
675
|
+
throw error;
|
|
492
676
|
} finally {
|
|
493
677
|
await zip.close();
|
|
494
678
|
}
|
|
495
679
|
}
|
|
496
680
|
|
|
497
|
-
/**
|
|
498
|
-
|
|
499
|
-
|
|
681
|
+
/**
|
|
682
|
+
* Refuse an archive that does not hold what its manifest says it holds (checkManifestGroups). The restore paths call
|
|
683
|
+
* it before they write anything; a manifest from before groups passes (it promised nothing about them).
|
|
684
|
+
*/
|
|
685
|
+
export function assertBackupGroups(zip, manifest, prefix, label = 'Invalid backup') {
|
|
686
|
+
const problems = checkManifestGroups(manifest, zip.entries.filter(entry => !entry.isDirectory).map(entry => entry.name), prefix);
|
|
687
|
+
if (problems.length) throw Object.assign(new Error(`${label}: ${problems[0]}`), { code: 'BACKUP_GROUPS_MISMATCH' });
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* What an encrypted upgrade snapshot says about itself outside its ciphertext: `<archive>.info.json`, beside it.
|
|
692
|
+
* The start after an update decides without a password whether the snapshot still stands for the data
|
|
693
|
+
* (checkUpgradeSnapshotFreshness), and that needs what the snapshot was taken from: its manifest without the file
|
|
694
|
+
* list and its checksums. A plain SHA-256 of `.env` beside the ciphertext would let anybody test a guess at it, so the
|
|
695
|
+
* checksums are kept keyed by the authentication key (`keyedChecksums`): the next start, which has the key file, can
|
|
696
|
+
* compare them and nobody else can read them. The sidecar names the archive's own header (a hash of it), so it
|
|
697
|
+
* describes that file and no other. It is written only for a snapshot inside the data home.
|
|
698
|
+
*/
|
|
699
|
+
async function writeSnapshotInfo(tempInfoPath, archivePath, manifest, authKey) {
|
|
700
|
+
const header = await readBackupHeaderFile(archivePath);
|
|
701
|
+
const { files, checksums, ...rest } = manifest;
|
|
702
|
+
const info = {
|
|
703
|
+
version: 2,
|
|
704
|
+
header: createHash('sha256').update(header.start).update(header.mac).digest('hex'),
|
|
705
|
+
manifest: { ...rest, fileCount: Array.isArray(files) ? files.length : 0 },
|
|
706
|
+
keyedChecksums: Object.fromEntries(Object.entries(checksums || {}).map(([entry, value]) => [entry, snapshotRecordDigest(authKey, `${entry}\0${value}`)])),
|
|
707
|
+
};
|
|
708
|
+
await writeFile(tempInfoPath, `${JSON.stringify(info)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async function readSnapshotInfo(path) {
|
|
712
|
+
let info;
|
|
713
|
+
try { info = JSON.parse(await readFile(backupInfoPath(path), 'utf8')); }
|
|
714
|
+
catch { throw new BackupEncryptionError('BACKUP_PASSWORD_REQUIRED', 'This backup is encrypted: its password is needed to read it.', { status: 401 }); }
|
|
715
|
+
const header = await readBackupHeaderFile(path);
|
|
716
|
+
const actual = createHash('sha256').update(header.start).update(header.mac).digest('hex');
|
|
717
|
+
if (info?.version !== 2 || info.header !== actual || !info.manifest || typeof info.manifest !== 'object' || !info.keyedChecksums || typeof info.keyedChecksums !== 'object') {
|
|
718
|
+
throw new Error('Backup verification failed: the record beside this encrypted snapshot is not its own');
|
|
719
|
+
}
|
|
720
|
+
return { ...info.manifest, keyedChecksums: info.keyedChecksums };
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* The manifest of a backup archive, read without reading anything else (its central directory and the manifest entry).
|
|
725
|
+
* An encrypted one is opened with `fileKey` and `authKey`, or `password`; without them, an encrypted upgrade snapshot answers
|
|
726
|
+
* with the record beside it (writeSnapshotInfo: the manifest without its file list), any other encrypted backup
|
|
727
|
+
* with BACKUP_PASSWORD_REQUIRED.
|
|
728
|
+
*/
|
|
729
|
+
export async function readBackupArchiveManifest(path, { fileKey = null, authKey = null, password = null, inline = false } = {}) {
|
|
730
|
+
if (!fileKey && password == null && await isEncryptedBackupFile(path)) return readSnapshotInfo(path);
|
|
731
|
+
const zip = await openBackupArchive(path, { fileKey, authKey, password, inline });
|
|
500
732
|
try {
|
|
501
733
|
const manifestEntry = zip.getEntry(`${BACKUP_PREFIX}/manifest.json`);
|
|
502
734
|
if (!manifestEntry) throw new Error('Backup verification failed: manifest is missing');
|
|
@@ -506,6 +738,80 @@ export async function readBackupArchiveManifest(path) {
|
|
|
506
738
|
}
|
|
507
739
|
}
|
|
508
740
|
|
|
741
|
+
// What a full backup takes from data/ and mcp-data/: everything but what no archive holds, the migration copies of
|
|
742
|
+
// memory.db, and memory.db itself (archived as database/memory.db, from a consistent copy).
|
|
743
|
+
const fullBackupFilters = () => ({
|
|
744
|
+
data: rel => !shouldSkipDataPath(rel),
|
|
745
|
+
'mcp-data': rel => !shouldSkipDataPath(rel)
|
|
746
|
+
&& !isDatabaseCopyArtifact(rel)
|
|
747
|
+
&& !/^memory\.db(?:-wal|-shm)?$/i.test(rel)
|
|
748
|
+
&& !/\.db-(?:wal|shm)$/i.test(rel),
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
// The folders of data/ a walk can leave unread: what no archive holds, and the folders a left-out group owns.
|
|
752
|
+
function dataDirsToSkip(groups) {
|
|
753
|
+
const left = groups ? BACKUP_GROUP_IDS.filter(id => !groups.includes(id)).flatMap(dataDirsOfGroup) : [];
|
|
754
|
+
return { data: rel => isNeverBackedUpDir(rel) || left.includes(rel), 'mcp-data': rel => isNeverBackedUpDir(rel) };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// The tree walk, space estimate and stale-directory removal can touch every file in a data home.
|
|
758
|
+
// `groups`: the ids of the groups to archive (backup-groups.js), or null for everything a full backup holds.
|
|
759
|
+
function collectVerifiedBackupInputs({ dataHome, folderPath, additionalEntries, leanSnapshot, upgradeSoftLimitBytes, groups = null, ...space }) {
|
|
760
|
+
cleanupStaleBackupArtifacts(folderPath);
|
|
761
|
+
const chosen = groups ? new Set(groups) : null;
|
|
762
|
+
const deduped = collectBackupFiles(dataHome, fullBackupFilters(), additionalEntries, dataDirsToSkip(groups))
|
|
763
|
+
.filter((file) => {
|
|
764
|
+
const group = backupGroupOf(file.archivePath);
|
|
765
|
+
return group !== null && (!chosen || chosen.has(group));
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
// Keep the upgrade path bounded: state is archived, generated media is not.
|
|
769
|
+
const selection = leanSnapshot
|
|
770
|
+
? selectUpgradeSnapshotFiles(deduped, { softLimitBytes: upgradeSoftLimitBytes })
|
|
771
|
+
: { files: deduped, excluded: null };
|
|
772
|
+
const includeDatabase = !chosen || chosen.has('memories');
|
|
773
|
+
return {
|
|
774
|
+
...selection, includeDatabase,
|
|
775
|
+
estimate: estimateBackupWorkingSpace({ ...space, databasePath: includeDatabase ? space.databasePath : null, files: selection.files }),
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* How much each group holds right now: { groups: { id: { files, bytes, archiveBytes } }, never: { files, bytes } }.
|
|
781
|
+
* `bytes` is what the files take on disk, `archiveBytes` about what they take in the ZIP (estimateArchivedBytes).
|
|
782
|
+
* `never`: what no backup holds, as far as it is cheap to count (the folders the walk never enters are not read).
|
|
783
|
+
* Every group is measured whatever the selection, so the page can show what switching one on would add. Only names
|
|
784
|
+
* and sizes are read, no file is opened; it runs on a worker thread (runBackupTask 'measure').
|
|
785
|
+
*/
|
|
786
|
+
function measureBackupGroups({ dataHome, databasePath, additionalEntries = [] }) {
|
|
787
|
+
const groups = Object.fromEntries(BACKUP_GROUP_IDS.map(id => [id, { files: 0, bytes: 0, archiveBytes: 0 }]));
|
|
788
|
+
const never = { files: 0, bytes: 0 };
|
|
789
|
+
const count = (archivePath, bytes) => {
|
|
790
|
+
const group = backupGroupOf(archivePath);
|
|
791
|
+
if (group === null) { never.files += 1; never.bytes += bytes; return; }
|
|
792
|
+
groups[group].files += 1;
|
|
793
|
+
groups[group].bytes += bytes;
|
|
794
|
+
groups[group].archiveBytes += estimateArchivedBytes(archivePath, bytes);
|
|
795
|
+
};
|
|
796
|
+
// Everything a walk reaches, the never-archived files too (they are counted as such, not dropped unseen).
|
|
797
|
+
const everything = { data: () => true, 'mcp-data': rel => !isDatabaseCopyArtifact(rel) && !/^memory\.db(?:-wal|-shm|-journal)?$/i.test(rel) };
|
|
798
|
+
for (const file of collectBackupFiles(dataHome, everything, additionalEntries, dataDirsToSkip(null))) count(file.archivePath, fileBytes(file.diskPath));
|
|
799
|
+
if (databasePath) {
|
|
800
|
+
const bytes = fileBytes(databasePath) + fileBytes(`${databasePath}-wal`);
|
|
801
|
+
if (bytes > 0) count('database/memory.db', bytes);
|
|
802
|
+
}
|
|
803
|
+
return { groups, never };
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// A dead mount can also wedge cleanup. After a worker timeout, try each cleanup for at most a second;
|
|
807
|
+
// the async removal continues and the worker's eventual termination schedules another attempt.
|
|
808
|
+
async function waitForBackupCleanup(cleaning, workerTimedOut) {
|
|
809
|
+
if (!workerTimedOut) return cleaning;
|
|
810
|
+
let timer;
|
|
811
|
+
try { await Promise.race([cleaning, new Promise(resolve => { timer = setTimeout(resolve, 1000); })]); }
|
|
812
|
+
finally { clearTimeout(timer); }
|
|
813
|
+
}
|
|
814
|
+
|
|
509
815
|
/** Create, reopen, checksum-verify, and atomically publish one immutable ZIP. */
|
|
510
816
|
export async function createVerifiedBackup({
|
|
511
817
|
dataHome,
|
|
@@ -519,54 +825,55 @@ export async function createVerifiedBackup({
|
|
|
519
825
|
expectedArchiveBytes = 0,
|
|
520
826
|
freeSpaceReserveBytes = BACKUP_FREE_SPACE_RESERVE_BYTES,
|
|
521
827
|
getAvailableBytes = backupAvailableBytes,
|
|
828
|
+
checkIntegrity = checkSqliteIntegrity,
|
|
829
|
+
workerOptions = {},
|
|
522
830
|
onBeforeArchive = null,
|
|
523
831
|
onProgress = null,
|
|
524
832
|
upgradeSoftLimitBytes = UPGRADE_SNAPSHOT_SOFT_LIMIT_BYTES,
|
|
833
|
+
// Which groups go in (backup-groups.js): ids, or a { id: boolean } selection; null is everything. The manifest
|
|
834
|
+
// records them, and the archive is verified against them before it is published.
|
|
835
|
+
groups = null,
|
|
836
|
+
// An AbortSignal: aborting stops the backup at its next step (BackupCancelledError); nothing is published and the
|
|
837
|
+
// archive under way and the staged copies are removed, as after any failure.
|
|
838
|
+
signal = null,
|
|
839
|
+
// Left out: the backup is encrypted when the owner turned encryption on (the data home's key file), and fails
|
|
840
|
+
// when that key cannot be used. { recipient } names the key directly (tests). There is no value for "plain".
|
|
841
|
+
encryption = undefined,
|
|
525
842
|
now = () => new Date(),
|
|
526
843
|
} = {}) {
|
|
527
844
|
// A large data home spends minutes in checksum/archive with no output. Phase
|
|
528
845
|
// reporting is what stops that from reading as a hang to the caller.
|
|
529
846
|
const report = typeof onProgress === 'function' ? onProgress : () => {};
|
|
530
847
|
if (!dataHome || !folderPath) throw new Error('dataHome and folderPath are required');
|
|
848
|
+
const chosenGroups = groups == null ? null : selectedBackupGroups(groups);
|
|
849
|
+
if (chosenGroups && !chosenGroups.length) {
|
|
850
|
+
throw Object.assign(new Error('Nothing is selected for this backup: switch on at least one group.'), { code: 'BACKUP_NOTHING_SELECTED', status: 400 });
|
|
851
|
+
}
|
|
852
|
+
throwIfCancelled(signal);
|
|
853
|
+
// Before anything is written: a key file that cannot be used fails the backup here.
|
|
854
|
+
const encrypt = backupEncryptionFor(dataHome, encryption);
|
|
531
855
|
const createdAt = now();
|
|
532
856
|
assertBackupDestinationMounted(folderPath);
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
const destination = resolve(folderPath, archiveNameFor(kind, createdAt));
|
|
857
|
+
await mkdir(folderPath, { recursive: true });
|
|
858
|
+
const destination = resolve(folderPath, archiveNameFor(kind, createdAt, !!encrypt));
|
|
536
859
|
const tempPath = `${destination}.${process.pid}.tmp`;
|
|
537
|
-
const sqliteTemp = resolve(folderPath, `.synabun-db-${process.pid}-${Date.now()}.tmp`);
|
|
538
|
-
const extraSqliteTemps = [];
|
|
539
860
|
if (existsSync(destination)) throw new Error(`Backup already exists: ${destination}`);
|
|
540
861
|
|
|
541
|
-
let sqliteSnapshot = null;
|
|
542
862
|
let stageDir = null;
|
|
863
|
+
let workerTimedOut = false;
|
|
864
|
+
// The encrypted writer and this file's key, while they exist: both are gone before this function returns.
|
|
865
|
+
let writer = null;
|
|
543
866
|
try {
|
|
544
|
-
// BACKUP_DATA_DIRS is the list other modules read (backupRoots): every folder copied here is on it.
|
|
545
|
-
const dataDirFilters = {
|
|
546
|
-
data: rel => !shouldSkipDataPath(rel),
|
|
547
|
-
'mcp-data': rel => !shouldSkipDataPath(rel)
|
|
548
|
-
&& !isDatabaseCopyArtifact(rel)
|
|
549
|
-
&& !/^memory\.db(?:-wal|-shm)?$/i.test(rel)
|
|
550
|
-
&& !/\.db-(?:wal|shm)$/i.test(rel),
|
|
551
|
-
};
|
|
552
|
-
const deduped = collectBackupFiles(dataHome, dataDirFilters, additionalEntries);
|
|
553
|
-
|
|
554
|
-
// Keep the upgrade path bounded: state is archived, generated media is not.
|
|
555
867
|
const leanSnapshot = UPGRADE_BACKUP_KINDS.has(kind);
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
const workingSpace =
|
|
563
|
-
folderPath,
|
|
564
|
-
|
|
565
|
-
databasePath,
|
|
566
|
-
expectedArchiveBytes,
|
|
567
|
-
freeSpaceReserveBytes,
|
|
568
|
-
getAvailableBytes,
|
|
569
|
-
});
|
|
868
|
+
markActivity('backup:collect');
|
|
869
|
+
const { files, excluded, estimate, includeDatabase } = await cancellable(() => runBackupTask('collect', {
|
|
870
|
+
dataHome, folderPath, additionalEntries, leanSnapshot, upgradeSoftLimitBytes, groups: chosenGroups,
|
|
871
|
+
databasePath, expectedArchiveBytes, freeSpaceReserveBytes,
|
|
872
|
+
}, workerOptions.collect), signal);
|
|
873
|
+
if (encrypt) cleanupStaleBackupArtifacts(privateBackupStagingRoot(dataHome));
|
|
874
|
+
const workingSpace = encrypt
|
|
875
|
+
? checkSplitWorkingSpace(folderPath, existsSync(privateBackupStagingRoot(dataHome)) ? privateBackupStagingRoot(dataHome) : dataHome, estimate, getAvailableBytes, freeSpaceReserveBytes)
|
|
876
|
+
: checkWorkingSpace(folderPath, estimate, getAvailableBytes);
|
|
570
877
|
report({
|
|
571
878
|
phase: 'collect',
|
|
572
879
|
files: files.length,
|
|
@@ -576,32 +883,54 @@ export async function createVerifiedBackup({
|
|
|
576
883
|
skippedReason: excluded?.reason ?? null,
|
|
577
884
|
});
|
|
578
885
|
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
886
|
+
// Own all staged files, including partial database copies and their SQLite sidecars. They are plaintext: an
|
|
887
|
+
// encrypted backup stages them in the data home's private folder, never in the destination.
|
|
888
|
+
stageDir = encrypt ? await makePrivateStage(dataHome) : await mkdtemp(resolve(folderPath, `.synabun-files-${process.pid}-`));
|
|
889
|
+
const databases = files.filter(file => /\.db$/i.test(file.archivePath));
|
|
890
|
+
markActivity('backup:copy');
|
|
891
|
+
// The memory database is copied only when the memories are part of this backup.
|
|
892
|
+
const copied = await cancellable(() => runBackupTask('copy', { databasePath: includeDatabase === false ? null : databasePath, databases, stageDir, privateFiles: !!encrypt }, {
|
|
893
|
+
inputBytes: estimate.sqliteSnapshotBytes, ...workerOptions.copy,
|
|
894
|
+
}), signal);
|
|
895
|
+
// An empty extra database (and its sidecars) is left out of the archive, the manifest and the checks.
|
|
896
|
+
const skippedDatabases = new Set(copied.filter(copy => copy.skipped).map(copy => copy.archivePath.replace(/\\/g, '/')));
|
|
897
|
+
const copies = copied.filter(copy => !copy.skipped);
|
|
898
|
+
const sqliteSnapshot = copies.find(copy => copy.primary);
|
|
899
|
+
const byEntry = new Map(files.map(file => [file.archivePath.replace(/\\/g, '/'), file])
|
|
900
|
+
.filter(([entry]) => !skippedDatabases.has(entry.replace(/-(?:wal|shm|journal)$/i, ''))));
|
|
901
|
+
// The phases from here on count what is archived. Collect counted every collected file: these say what of it the
|
|
902
|
+
// copy found empty and left out (the databases, and them with their sidecars), so the two counts add up.
|
|
903
|
+
const skippedEmpty = { skippedEmptyDatabases: skippedDatabases.size, skippedEmptyDatabaseFiles: files.length - byEntry.size };
|
|
904
|
+
for (const { archivePath, path } of copies) byEntry.set(archivePath.replace(/\\/g, '/'), { archivePath, diskPath: path });
|
|
905
|
+
|
|
906
|
+
let results;
|
|
907
|
+
try {
|
|
908
|
+
markActivity('backup:integrity');
|
|
909
|
+
results = await cancellable(() => checkIntegrity(copies.map(copy => copy.path), {
|
|
910
|
+
inputBytes: copies.reduce((sum, copy) => sum + copy.sizeBytes, 0), ...workerOptions.integrity,
|
|
911
|
+
}), signal);
|
|
912
|
+
} catch (cause) {
|
|
913
|
+
if (cause.code === 'BACKUP_WORKER_TIMEOUT' || cause.code === 'BACKUP_CANCELLED') throw cause;
|
|
914
|
+
throw Object.assign(new Error(`SQLite's integrity check of the copies could not run: ${cause.message}`, { cause }), { code: 'EINTEGRITY' });
|
|
585
915
|
}
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
for (let index = 0; index < files.length; index++) {
|
|
590
|
-
const file = files[index];
|
|
591
|
-
if (!/\.db$/i.test(file.archivePath) || file.archivePath === 'database/memory.db') continue;
|
|
592
|
-
const temp = resolve(folderPath, `.synabun-extra-db-${process.pid}-${Date.now()}-${index}.tmp`);
|
|
593
|
-
const consistent = createConsistentSqliteSnapshot(file.diskPath, temp);
|
|
594
|
-
if (!consistent) continue;
|
|
595
|
-
extraSqliteTemps.push(temp);
|
|
596
|
-
files[index] = { ...file, diskPath: temp };
|
|
916
|
+
for (const copy of copies) {
|
|
917
|
+
const verdict = results?.find(result => result?.path === copy.path);
|
|
918
|
+
if (verdict?.ok !== true) throw new SnapshotIntegrityError(copy.archivePath, verdict?.lines || []);
|
|
597
919
|
}
|
|
598
|
-
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
report({ phase: 'checksum', files: finalFiles.length });
|
|
920
|
+
markActivity('backup:snapshot-files');
|
|
921
|
+
const finalFiles = await snapshotMutableBackupFiles([...byEntry.values()], stageDir, signal, { privateFiles: !!encrypt });
|
|
922
|
+
finalFiles.sort((a, b) => a.archivePath.localeCompare(b.archivePath));
|
|
923
|
+
markActivity('backup:checksum');
|
|
924
|
+
report({ phase: 'checksum', files: finalFiles.length, ...skippedEmpty });
|
|
603
925
|
const checksums = {};
|
|
604
|
-
for (const file of finalFiles)
|
|
926
|
+
for (const file of finalFiles) {
|
|
927
|
+
throwIfCancelled(signal);
|
|
928
|
+
checksums[file.archivePath] = `sha256:${await hashFile(file.diskPath)}`;
|
|
929
|
+
}
|
|
930
|
+
// What this archive holds, by group. `absent`: a group that was asked for and had nothing to give (a data home
|
|
931
|
+
// without a memory database), so a reader does not take the missing database for damage.
|
|
932
|
+
const recordedGroups = leanSnapshot ? null : manifestGroups(chosenGroups);
|
|
933
|
+
if (recordedGroups && recordedGroups.included.includes('memories') && !sqliteSnapshot) recordedGroups.absent = ['memories'];
|
|
605
934
|
|
|
606
935
|
const manifest = {
|
|
607
936
|
version: BACKUP_MANIFEST_VERSION,
|
|
@@ -612,59 +941,76 @@ export async function createVerifiedBackup({
|
|
|
612
941
|
sourceFingerprint,
|
|
613
942
|
storage: 'sqlite',
|
|
614
943
|
database: sqliteSnapshot ? {
|
|
615
|
-
file:
|
|
944
|
+
file: sqliteSnapshot.archivePath,
|
|
616
945
|
sizeBytes: sqliteSnapshot.sizeBytes,
|
|
617
946
|
memoryCount: sqliteSnapshot.memoryCount,
|
|
618
|
-
integrity:
|
|
947
|
+
integrity: 'ok',
|
|
619
948
|
} : null,
|
|
620
949
|
files: finalFiles.map(file => file.archivePath),
|
|
621
950
|
checksums,
|
|
622
|
-
// A lean snapshot is not a whole-data-home backup. Recording
|
|
623
|
-
// keeps a restore from silently presenting it as one.
|
|
624
|
-
scope: leanSnapshot ? 'state-only' : 'complete',
|
|
951
|
+
// A lean snapshot is not a whole-data-home backup, and neither is one the owner left groups out of. Recording
|
|
952
|
+
// that here keeps a restore from silently presenting it as one.
|
|
953
|
+
scope: leanSnapshot ? 'state-only' : recordedGroups.excluded.length ? 'selected' : 'complete',
|
|
954
|
+
...(recordedGroups ? { groups: recordedGroups } : {}),
|
|
625
955
|
excluded,
|
|
626
956
|
verified: true,
|
|
627
957
|
verification: { algorithm: 'sha256', publication: 'verify-before-atomic-rename' },
|
|
628
958
|
};
|
|
629
959
|
if (typeof onBeforeArchive === 'function') await onBeforeArchive({ files: finalFiles, manifest });
|
|
630
|
-
|
|
960
|
+
throwIfCancelled(signal);
|
|
961
|
+
markActivity('backup:archive');
|
|
962
|
+
// tempPath: where the archive grows, for a caller that shows how much is written (lib/backup-download.js).
|
|
963
|
+
report({ phase: 'archive', files: finalFiles.length, bytes: workingSpace.archiveBytes, tempPath, ...skippedEmpty });
|
|
631
964
|
// Level 1 on the blocking upgrade path: the remaining payload is mostly
|
|
632
965
|
// SQLite and JSON, where fast deflate still shrinks well.
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
966
|
+
// Encrypted: the archive never exists in plaintext. Its bytes go from archiver through the encrypting thread
|
|
967
|
+
// into the file, and the file is then read back with this file's key, which nothing else ever holds.
|
|
968
|
+
if (encrypt) writer = createEncryptedBackupWriter(tempPath, encrypt.recipient, { chunkSize: encrypt.chunkSize, now });
|
|
969
|
+
await writeArchive({ tempPath, files: finalFiles, manifest, level: leanSnapshot ? 1 : 6, signal, output: writer ? writer.stream() : null });
|
|
970
|
+
markActivity('backup:verify');
|
|
971
|
+
report({ phase: 'verify', files: finalFiles.length, tempPath, ...skippedEmpty });
|
|
972
|
+
const publishedManifest = await verifyBackupArchive(tempPath, { signal, fileKey: writer ? writer.fileKey : null, authKey: writer ? writer.authKey : null });
|
|
973
|
+
throwIfCancelled(signal);
|
|
974
|
+
// No downgrade, checked on the file itself: with encryption on, what is published begins as an encrypted backup.
|
|
975
|
+
if (encrypt && !(await isEncryptedBackupFile(tempPath))) throw new BackupEncryptionError('BACKUP_ENC_NOT_ENCRYPTED', 'The backup was not encrypted: it is not published.', { status: 500 });
|
|
976
|
+
// rename replaces: a file that took the name while this archive was built is kept, and this one is not published.
|
|
977
|
+
if (existsSync(destination)) throw new Error(`Backup already exists: ${destination}`);
|
|
978
|
+
await rename(tempPath, destination);
|
|
637
979
|
return {
|
|
638
980
|
path: destination,
|
|
639
981
|
name: basename(destination),
|
|
640
982
|
kind,
|
|
641
983
|
createdAt: createdAt.toISOString(),
|
|
642
|
-
sizeBytes:
|
|
984
|
+
sizeBytes: (await stat(destination)).size,
|
|
643
985
|
manifest: publishedManifest,
|
|
986
|
+
encrypted: !!encrypt,
|
|
987
|
+
...(writer ? { keyId: writer.keyId } : {}),
|
|
644
988
|
};
|
|
645
989
|
} catch (error) {
|
|
646
|
-
|
|
990
|
+
workerTimedOut = error.code === 'BACKUP_WORKER_TIMEOUT';
|
|
991
|
+
// Native I/O may outlive terminate(). Retry cleanup when it finally releases its files (notably on Windows).
|
|
992
|
+
error.workerTermination?.then(async () => {
|
|
993
|
+
await rm(tempPath, { force: true }).catch(() => {});
|
|
994
|
+
if (stageDir) await rm(stageDir, { recursive: true, force: true }).catch(() => {});
|
|
995
|
+
}).catch(() => {});
|
|
996
|
+
// The encrypting thread lets go of the file before it is removed.
|
|
997
|
+
if (writer) await writer.abort().catch(() => {});
|
|
998
|
+
await waitForBackupCleanup(rm(tempPath, { force: true }).catch(() => {}), workerTimedOut);
|
|
647
999
|
throw error;
|
|
648
1000
|
} finally {
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
try { if (existsSync(path)) unlinkSync(path); } catch {}
|
|
652
|
-
}
|
|
653
|
-
if (stageDir) {
|
|
654
|
-
try { rmSync(stageDir, { recursive: true, force: true }); } catch {}
|
|
655
|
-
}
|
|
1001
|
+
if (writer) writer.wipe();
|
|
1002
|
+
if (stageDir) await waitForBackupCleanup(rm(stageDir, { recursive: true, force: true }).catch(() => {}), workerTimedOut);
|
|
656
1003
|
}
|
|
657
1004
|
}
|
|
658
1005
|
|
|
659
1006
|
// ── The pre-update snapshot: quick at any size ──
|
|
660
1007
|
//
|
|
661
|
-
//
|
|
662
|
-
//
|
|
663
|
-
// and the pre-update snapshot is taken while SynaBun restarts into a new version, with the user waiting.
|
|
1008
|
+
// The full backup deflates database copies and reads them back through inflate. The pre-update snapshot
|
|
1009
|
+
// is taken while SynaBun restarts into a new version, with the user waiting.
|
|
664
1010
|
// createUpgradeSnapshot() keeps what that snapshot promises (the state as of one commit, every byte in a ZIP the
|
|
665
1011
|
// restore paths read, every database copy passing the integrity check the restore runs, read back once and checked
|
|
666
|
-
// before it is published) and
|
|
667
|
-
//
|
|
1012
|
+
// before it is published) and avoids deflating the database and inflating it again.
|
|
1013
|
+
// Its integrity check runs on a thread of its own while the archive is written.
|
|
668
1014
|
//
|
|
669
1015
|
// The snapshot also records what it was taken from (`inputs` in its manifest): checkUpgradeSnapshotFreshness()
|
|
670
1016
|
// tells later, from any process, whether it still stands for the data as it is (lib/update-snapshot.js before the
|
|
@@ -688,8 +1034,10 @@ export function cloneMethodFor(source, targetDir, { platform = process.platform,
|
|
|
688
1034
|
}
|
|
689
1035
|
|
|
690
1036
|
function cloneFileNow(source, target, method) {
|
|
691
|
-
|
|
692
|
-
|
|
1037
|
+
// A worker thread shares the server's POSIX locks. Closing a raw descriptor for the live database
|
|
1038
|
+
// in this process can release SQLite's locks, so let cp open and close its own descriptors.
|
|
1039
|
+
const cloneFlag = method === 'clone' ? '-c' : '--reflink=always';
|
|
1040
|
+
execFileSync('/bin/cp', [cloneFlag, resolve(source), resolve(target)], { stdio: 'ignore', timeout: 60_000 });
|
|
693
1041
|
}
|
|
694
1042
|
|
|
695
1043
|
const SQLITE_HEADER = Buffer.from('SQLite format 3\0', 'latin1');
|
|
@@ -767,38 +1115,52 @@ export function sameSqliteFingerprint(a, b) {
|
|
|
767
1115
|
* can reset it while the lock is held.
|
|
768
1116
|
* backup anywhere else (or when the lock is not free within `busyTimeoutMs`), SQLite's online backup in
|
|
769
1117
|
* one step: one sequential read and write, from one read transaction, and no writer ever waits.
|
|
770
|
-
* vacuum a Node without the backup API (before 22.16): VACUUM INTO
|
|
1118
|
+
* vacuum a Node without the backup API (before 22.16): VACUUM INTO.
|
|
771
1119
|
*
|
|
772
|
-
*
|
|
773
|
-
* so the
|
|
774
|
-
*
|
|
775
|
-
*
|
|
1120
|
+
* For an upgrade freshness fingerprint, try a TRUNCATE checkpoint (waiting up to a second for older readers)
|
|
1121
|
+
* so the fingerprint survives the close of the last connection. Take it under the write lock for a clone or
|
|
1122
|
+
* immediately before the copy otherwise. Full backups need only the copy and can leave the live WAL alone.
|
|
1123
|
+
* The copy is then opened read-only once: its header must account for its whole size,
|
|
776
1124
|
* and the memories of the `primary` database are counted (a query that fails there fails the copy). Resolves
|
|
777
1125
|
* { method, path, sizeBytes, memoryCount, pageCount, fingerprint }, or null when there is no database.
|
|
778
1126
|
*/
|
|
779
1127
|
export async function copySqliteDatabase(sourcePath, targetPath, {
|
|
780
1128
|
platform = process.platform, method: forced = null, busyTimeoutMs = 15_000, clone = cloneFileNow, primary = false,
|
|
1129
|
+
captureFingerprint = true, skipEmpty = false,
|
|
781
1130
|
} = {}) {
|
|
782
1131
|
if (!existsSync(sourcePath)) return null;
|
|
783
1132
|
for (const suffix of ['', '-wal', '-shm', '-journal']) rmSync(`${targetPath}${suffix}`, { force: true });
|
|
784
1133
|
const fallback = typeof nodeSqlite.backup === 'function' ? 'backup' : 'vacuum';
|
|
785
1134
|
let method = forced || cloneMethodFor(sourcePath, dirname(targetPath), { platform }) || fallback;
|
|
786
1135
|
let fingerprint = null;
|
|
1136
|
+
const readFingerprint = () => captureFingerprint ? sqliteFingerprint(sourcePath) : null;
|
|
787
1137
|
const source = new DatabaseSync(sourcePath);
|
|
788
1138
|
try {
|
|
789
|
-
//
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1139
|
+
// Only an upgrade freshness check needs a stable fingerprint. A full backup can copy the WAL as it is.
|
|
1140
|
+
if (captureFingerprint) {
|
|
1141
|
+
try {
|
|
1142
|
+
source.exec('PRAGMA busy_timeout = 1000');
|
|
1143
|
+
source.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
|
|
1144
|
+
} catch { /* busy or not a WAL database */ }
|
|
1145
|
+
}
|
|
794
1146
|
source.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(busyTimeoutMs))}`);
|
|
1147
|
+
// An extra database nothing ever initialized (no page on disk or in its WAL) holds nothing to keep.
|
|
1148
|
+
if (skipEmpty && Number(source.prepare('PRAGMA page_count').get().page_count) === 0) {
|
|
1149
|
+
return { skipped: true, reason: 'empty', path: null };
|
|
1150
|
+
}
|
|
1151
|
+
// A zero-byte, uninitialized database is valid SQLite. Cloning it leaves an empty file; SQLite's
|
|
1152
|
+
// backup/VACUUM materializes its header. Read logical pages (including WAL) BEFORE BEGIN IMMEDIATE,
|
|
1153
|
+
// which gives an empty database a virtual first page without writing it to disk.
|
|
1154
|
+
if ((method === 'clone' || method === 'reflink') && Number(source.prepare('PRAGMA page_count').get().page_count) === 0) {
|
|
1155
|
+
method = fallback;
|
|
1156
|
+
}
|
|
795
1157
|
if (method === 'clone' || method === 'reflink') {
|
|
796
1158
|
let locked = false;
|
|
797
1159
|
let cloned = false;
|
|
798
1160
|
try {
|
|
799
1161
|
source.exec('BEGIN IMMEDIATE');
|
|
800
1162
|
locked = true;
|
|
801
|
-
fingerprint =
|
|
1163
|
+
fingerprint = readFingerprint();
|
|
802
1164
|
clone(sourcePath, targetPath, method);
|
|
803
1165
|
const wal = `${sourcePath}-wal`;
|
|
804
1166
|
if (existsSync(wal) && statSync(wal).size > 0) clone(wal, `${targetPath}-wal`, method);
|
|
@@ -812,11 +1174,11 @@ export async function copySqliteDatabase(sourcePath, targetPath, {
|
|
|
812
1174
|
if (!cloned) method = fallback;
|
|
813
1175
|
}
|
|
814
1176
|
if (method === 'backup') {
|
|
815
|
-
fingerprint =
|
|
1177
|
+
fingerprint = readFingerprint();
|
|
816
1178
|
// One step holds one read transaction for the whole copy: no restart, whatever the server writes.
|
|
817
1179
|
await nodeSqlite.backup(source, targetPath, { rate: 1_000_000_000 });
|
|
818
1180
|
} else if (method === 'vacuum') {
|
|
819
|
-
fingerprint =
|
|
1181
|
+
fingerprint = readFingerprint();
|
|
820
1182
|
source.exec(`VACUUM INTO '${escapeSqliteString(targetPath)}'`);
|
|
821
1183
|
}
|
|
822
1184
|
} finally {
|
|
@@ -850,26 +1212,138 @@ export async function copySqliteDatabase(sourcePath, targetPath, {
|
|
|
850
1212
|
}
|
|
851
1213
|
}
|
|
852
1214
|
|
|
1215
|
+
// Even the online-copy path can wait synchronously for locks, checkpoint a large WAL or use VACUUM on old Node.
|
|
1216
|
+
// `databasePath` null: a backup without the memories. The memory database is then not opened at all.
|
|
1217
|
+
async function copyVerifiedDatabases({ databasePath, databases, stageDir, privateFiles = false }) {
|
|
1218
|
+
const copies = [];
|
|
1219
|
+
const primary = databasePath ? { archivePath: 'database/memory.db', diskPath: databasePath, primary: true } : null;
|
|
1220
|
+
for (const [index, file] of [...(primary ? [primary] : []), ...databases].entries()) {
|
|
1221
|
+
const isPrimary = file === primary;
|
|
1222
|
+
if (!isPrimary && file.archivePath.replace(/\\/g, '/') === 'database/memory.db') continue;
|
|
1223
|
+
// A single online backup/VACUUM has no intermediate progress; give this database room to finish.
|
|
1224
|
+
reportBackupWorkerProgress(fileBytes(file.diskPath) + fileBytes(`${file.diskPath}-wal`), true);
|
|
1225
|
+
const target = resolve(stageDir, `db-${index}.tmp`);
|
|
1226
|
+
let copy;
|
|
1227
|
+
try {
|
|
1228
|
+
copy = await copySqliteDatabase(file.diskPath, target, { primary: isPrimary, captureFingerprint: false, skipEmpty: !isPrimary });
|
|
1229
|
+
} catch (cause) {
|
|
1230
|
+
throw Object.assign(new Error(`Could not copy ${file.archivePath}: ${cause.message}`, { cause }), { code: cause.code });
|
|
1231
|
+
}
|
|
1232
|
+
if (!copy) {
|
|
1233
|
+
if (isPrimary) continue;
|
|
1234
|
+
throw Object.assign(new Error(`SQLite backup input disappeared: ${file.archivePath}`), { code: 'ENOENT' });
|
|
1235
|
+
}
|
|
1236
|
+
if (copy.skipped) { copies.push({ archivePath: file.archivePath, skipped: copy.reason }); continue; }
|
|
1237
|
+
if (privateFiles && process.platform !== 'win32') chmodSync(copy.path, 0o600);
|
|
1238
|
+
copies.push({ archivePath: file.archivePath, path: copy.path, sizeBytes: copy.sizeBytes, memoryCount: copy.memoryCount, primary: isPrimary });
|
|
1239
|
+
}
|
|
1240
|
+
return copies;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* How much each backup group holds right now, measured on a worker thread (names and sizes only; no file is opened
|
|
1245
|
+
* and the server's own thread does nothing but wait). Resolves { groups: { id: { files, bytes, archiveBytes } },
|
|
1246
|
+
* never: { files, bytes } }; `cancel()` on the promise stops the thread.
|
|
1247
|
+
*/
|
|
1248
|
+
export function measureBackupContents({ dataHome, databasePath = resolve(dataHome, 'mcp-data', 'memory.db'), additionalEntries = [], workerOptions = {} } = {}) {
|
|
1249
|
+
if (!dataHome) throw new Error('dataHome is required');
|
|
1250
|
+
return runBackupTask('measure', { dataHome, databasePath, additionalEntries }, workerOptions);
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
// Early Node 22 releases gate node:sqlite on a flag. File-backed workers cannot inherit --input-type or --eval.
|
|
1254
|
+
const sqliteWorkerArgs = process.execArgv.filter(arg => arg === '--experimental-sqlite' || arg === '--disable-warning=ExperimentalWarning');
|
|
1255
|
+
|
|
1256
|
+
// Collection reports actual filesystem progress, never a heartbeat that could mask a stuck operation.
|
|
1257
|
+
let lastBackupWorkerProgress = 0;
|
|
1258
|
+
function reportBackupWorkerProgress(inputBytes, force = false) {
|
|
1259
|
+
if (!parentPort || !workerData?.verifiedBackupTask) return;
|
|
1260
|
+
const now = Date.now();
|
|
1261
|
+
if (!force && now - lastBackupWorkerProgress < 1000) return;
|
|
1262
|
+
lastBackupWorkerProgress = now;
|
|
1263
|
+
parentPort.postMessage({ progress: true, inputBytes });
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
/** Inactivity budgets: two minutes per collection operation; 10 min + 5 min/GiB per native database operation. */
|
|
1267
|
+
export function backupWorkerTimeoutMs(task, inputBytes = 0) {
|
|
1268
|
+
if (task === 'collect' || task === 'measure' || task === 'sweep') return 2 * 60_000;
|
|
1269
|
+
return Math.min(2_147_000_000, 10 * 60_000 + Math.ceil(Math.max(0, Number(inputBytes) || 0) / 1024 ** 3) * 5 * 60_000);
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
function watchBackupWorker(task, data, {
|
|
1273
|
+
spawnWorker, timeoutMs = null, inputBytes = 0, terminationGraceMs = 1000,
|
|
1274
|
+
} = {}) {
|
|
1275
|
+
let cancel = () => {};
|
|
1276
|
+
const checking = new Promise((resolveTask, reject) => {
|
|
1277
|
+
let worker;
|
|
1278
|
+
let timer;
|
|
1279
|
+
let grace;
|
|
1280
|
+
let settled = false;
|
|
1281
|
+
let stopping = null;
|
|
1282
|
+
const settle = (fn, value) => {
|
|
1283
|
+
if (settled) return;
|
|
1284
|
+
settled = true;
|
|
1285
|
+
clearTimeout(timer);
|
|
1286
|
+
clearTimeout(grace);
|
|
1287
|
+
fn(value);
|
|
1288
|
+
};
|
|
1289
|
+
const stop = (error) => {
|
|
1290
|
+
if (settled || stopping) return;
|
|
1291
|
+
stopping = error;
|
|
1292
|
+
clearTimeout(timer);
|
|
1293
|
+
// Usually termination is immediate. A thread stuck in native I/O may not exit until the OS returns:
|
|
1294
|
+
// still settle the caller after a bounded grace period, and let its cleanup retry after that exit.
|
|
1295
|
+
try { error.workerTermination = Promise.resolve(worker.terminate()); }
|
|
1296
|
+
catch { error.workerTermination = Promise.resolve(); }
|
|
1297
|
+
error.workerTermination.then(() => settle(reject, error), () => settle(reject, error));
|
|
1298
|
+
grace = setTimeout(() => { worker.unref?.(); settle(reject, error); }, terminationGraceMs);
|
|
1299
|
+
};
|
|
1300
|
+
const reset = (bytes = inputBytes) => {
|
|
1301
|
+
inputBytes = bytes;
|
|
1302
|
+
clearTimeout(timer);
|
|
1303
|
+
const limit = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : backupWorkerTimeoutMs(task, inputBytes);
|
|
1304
|
+
timer = setTimeout(() => stop(Object.assign(
|
|
1305
|
+
new Error(`Backup ${task} worker timed out after ${limit} ms without progress`),
|
|
1306
|
+
{ code: 'BACKUP_WORKER_TIMEOUT', task, timeoutMs: limit },
|
|
1307
|
+
)), limit);
|
|
1308
|
+
};
|
|
1309
|
+
try { worker = spawnWorker(data); }
|
|
1310
|
+
catch (error) { settle(reject, error); return; }
|
|
1311
|
+
worker.on('message', (message) => {
|
|
1312
|
+
if (settled || stopping) return;
|
|
1313
|
+
if (message?.progress === true) { reset(message.inputBytes); return; }
|
|
1314
|
+
if (message?.error) settle(reject, Object.assign(message.error, { code: message.code }));
|
|
1315
|
+
else settle(resolveTask, Array.isArray(message) ? message : message.result);
|
|
1316
|
+
});
|
|
1317
|
+
worker.once('error', (error) => settle(reject, stopping || error));
|
|
1318
|
+
worker.once('exit', (code) => settle(reject, stopping || Object.assign(
|
|
1319
|
+
new Error(`Backup ${task} worker exited (${code}) without a result`), { code: 'BACKUP_WORKER_EXIT', task },
|
|
1320
|
+
)));
|
|
1321
|
+
cancel = () => stop(Object.assign(new Error(`Backup ${task} worker cancelled`), { code: 'BACKUP_WORKER_CANCELLED', task }));
|
|
1322
|
+
reset();
|
|
1323
|
+
});
|
|
1324
|
+
checking.cancel = () => cancel();
|
|
1325
|
+
return checking;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
export function runBackupTask(task, options, {
|
|
1329
|
+
spawnWorker = (data) => new Worker(new URL(import.meta.url), { workerData: data, execArgv: sqliteWorkerArgs }),
|
|
1330
|
+
...watchdog
|
|
1331
|
+
} = {}) {
|
|
1332
|
+
return watchBackupWorker(task, { verifiedBackupTask: task, options }, { ...watchdog, spawnWorker });
|
|
1333
|
+
}
|
|
1334
|
+
|
|
853
1335
|
/**
|
|
854
1336
|
* SQLite's PRAGMA integrity_check, the one `synabun restore-backup` runs, on each file in `paths`, on a thread of
|
|
855
1337
|
* its own (sqlite-integrity-worker.js): a 3.9 GB memory.db takes about 28 s, spent while the archive is written.
|
|
856
1338
|
* Resolves [{ path, ok, lines, ms }] (`lines`: SQLite's first findings when a file is not ok); `cancel()` on the
|
|
857
|
-
* promise stops the thread (it then rejects).
|
|
1339
|
+
* promise stops the thread (it then rejects). Each database gets a size-based inactivity budget.
|
|
858
1340
|
*/
|
|
859
|
-
export function checkSqliteIntegrity(paths, {
|
|
1341
|
+
export function checkSqliteIntegrity(paths, {
|
|
1342
|
+
spawnWorker = (data) => new Worker(new URL('./sqlite-integrity-worker.js', import.meta.url), { workerData: data, execArgv: sqliteWorkerArgs }),
|
|
1343
|
+
...watchdog
|
|
1344
|
+
} = {}) {
|
|
860
1345
|
if (!paths.length) return Object.assign(Promise.resolve([]), { cancel: () => {} });
|
|
861
|
-
|
|
862
|
-
const checking = new Promise((resolveCheck, reject) => {
|
|
863
|
-
let settled = false;
|
|
864
|
-
const settle = (fn, value) => { if (!settled) { settled = true; fn(value); } };
|
|
865
|
-
try { worker = spawnWorker({ paths }); }
|
|
866
|
-
catch (error) { reject(error); return; }
|
|
867
|
-
worker.once('message', (results) => settle(resolveCheck, results));
|
|
868
|
-
worker.once('error', (error) => settle(reject, error));
|
|
869
|
-
worker.once('exit', (code) => settle(reject, new Error(`the integrity check ended (exit ${code}) without a result`)));
|
|
870
|
-
});
|
|
871
|
-
checking.cancel = () => { try { worker?.terminate(); } catch { /* already gone */ } };
|
|
872
|
-
return checking;
|
|
1346
|
+
return watchBackupWorker('integrity', { paths }, { ...watchdog, spawnWorker });
|
|
873
1347
|
}
|
|
874
1348
|
|
|
875
1349
|
/** Raised when a database copy fails SQLite's integrity check: the snapshot is not published. */
|
|
@@ -943,13 +1417,29 @@ function collectUpgradeInputs({ dataHome, additionalEntries = [], softLimitBytes
|
|
|
943
1417
|
};
|
|
944
1418
|
const deduped = collectBackupFiles(dataHome, dataDirFilters, additionalEntries);
|
|
945
1419
|
const { files: kept, excluded } = selectUpgradeSnapshotFiles(deduped, { softLimitBytes });
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
1420
|
+
// An extra .db nothing initialized (0 bytes, no WAL with content) is skipped with its sidecars, as in a full backup.
|
|
1421
|
+
// Only a file that is not there is 0 bytes here (backupFileSize): one whose size cannot be read fails the snapshot
|
|
1422
|
+
// instead of passing for empty and dropping out of it.
|
|
1423
|
+
const empty = new Set(kept.filter(file => /\.db$/i.test(file.archivePath)
|
|
1424
|
+
&& backupFileSize(file) === 0 && backupFileSize({ diskPath: `${file.diskPath}-wal` }) === 0).map(file => file.archivePath.toLowerCase()));
|
|
1425
|
+
const marked = kept.filter(file => !empty.has(file.archivePath.toLowerCase()))
|
|
1426
|
+
.map(file => ({ ...file, sqlite: isSqliteDatabaseFile(file.diskPath) }));
|
|
1427
|
+
const databases = new Set([...empty, ...marked.filter(file => file.sqlite).map(file => file.archivePath.toLowerCase())]);
|
|
1428
|
+
// The database a journal, WAL or shared-memory file belongs to (lower case), or null for a file of its own.
|
|
1429
|
+
const ownerOf = (archivePath) => {
|
|
949
1430
|
const lower = archivePath.toLowerCase();
|
|
950
|
-
|
|
1431
|
+
const suffix = SQLITE_SIDE_FILES.find(item => item && lower.endsWith(item) && databases.has(lower.slice(0, -item.length)));
|
|
1432
|
+
return suffix ? lower.slice(0, -suffix.length) : null;
|
|
951
1433
|
};
|
|
952
|
-
|
|
1434
|
+
const inputs = [];
|
|
1435
|
+
// What the empty-database rule left out, for the progress report: the databases and every file that went with them.
|
|
1436
|
+
const skippedEmpty = { databases: kept.length - marked.length, files: kept.length - marked.length };
|
|
1437
|
+
for (const file of marked) {
|
|
1438
|
+
const owner = ownerOf(file.archivePath);
|
|
1439
|
+
if (!owner) inputs.push(file);
|
|
1440
|
+
else if (empty.has(owner)) skippedEmpty.files += 1;
|
|
1441
|
+
}
|
|
1442
|
+
return { inputs, excluded, skippedEmpty };
|
|
953
1443
|
}
|
|
954
1444
|
|
|
955
1445
|
/** Where an input is, as the manifest records it: relative to the data home (forward slashes), absolute outside it. */
|
|
@@ -970,6 +1460,19 @@ export async function checkUpgradeSnapshotFreshness({
|
|
|
970
1460
|
} = {}) {
|
|
971
1461
|
const recorded = manifest?.inputs?.entries;
|
|
972
1462
|
if (!dataHome || !Array.isArray(recorded)) return { fresh: false, reason: 'it does not record what it was taken from', changed: [] };
|
|
1463
|
+
// An encrypted snapshot's record keeps its checksums keyed: they are compared with this installation's key. A new
|
|
1464
|
+
// password keeps that key; one that did change since (encryption turned off and on, a key file replaced) cannot
|
|
1465
|
+
// match, and a new snapshot is taken.
|
|
1466
|
+
let recordKey = null;
|
|
1467
|
+
if (manifest.keyedChecksums) {
|
|
1468
|
+
try { const recipient = backupRecipientFor(dataHome); recordKey = recipient ? authKeyOf(recipient) : null; } catch { /* below */ }
|
|
1469
|
+
if (!recordKey) return { fresh: false, reason: 'its record needs the backup key, which is not here', changed: [] };
|
|
1470
|
+
}
|
|
1471
|
+
const sameContent = (entry, actual) => {
|
|
1472
|
+
if (actual === null) return false;
|
|
1473
|
+
if (recordKey) return manifest.keyedChecksums[entry] === snapshotRecordDigest(recordKey, `${entry}\0${actual}`);
|
|
1474
|
+
return actual === manifest.checksums?.[entry];
|
|
1475
|
+
};
|
|
973
1476
|
const current = new Map(collectUpgradeInputs({ dataHome, softLimitBytes: upgradeSoftLimitBytes }).inputs.map(file => [file.archivePath, file]));
|
|
974
1477
|
if (existsSync(databasePath)) current.set('database/memory.db', { archivePath: 'database/memory.db', diskPath: databasePath, sqlite: true });
|
|
975
1478
|
const before = new Map(recorded.filter(item => item && typeof item.entry === 'string').map(item => [item.entry, item]));
|
|
@@ -992,7 +1495,7 @@ export async function checkUpgradeSnapshotFreshness({
|
|
|
992
1495
|
}
|
|
993
1496
|
let actual = null;
|
|
994
1497
|
try { actual = `sha256:${await hashFile(file.diskPath)}`; } catch { /* gone or unreadable: changed */ }
|
|
995
|
-
if (actual
|
|
1498
|
+
if (!sameContent(entry, actual) && differs(entry, path, 'changed')) break scan;
|
|
996
1499
|
}
|
|
997
1500
|
}
|
|
998
1501
|
return changed.length
|
|
@@ -1023,8 +1526,10 @@ export async function checkUpgradeSnapshotFreshness({
|
|
|
1023
1526
|
* restore-backup` restore it as they restore any backup.
|
|
1024
1527
|
*
|
|
1025
1528
|
* onProgress({ phase: 'collect' | 'copy' | 'archive' | 'verify' | 'integrity', ... }): collect says how much (files,
|
|
1026
|
-
* bytes, skipped
|
|
1027
|
-
* and
|
|
1529
|
+
* bytes, skipped; `files` already leaves out the empty extra databases: skippedEmptyDatabases counts them,
|
|
1530
|
+
* skippedEmptyDatabaseFiles them and their sidecars), archive and verify say how far (done, total, in bytes);
|
|
1531
|
+
* integrity says that the archive is ready and the integrity check still runs (state 'running'), then that it passed
|
|
1532
|
+
* (state 'ok').
|
|
1028
1533
|
*/
|
|
1029
1534
|
export async function createUpgradeSnapshot({
|
|
1030
1535
|
dataHome,
|
|
@@ -1041,28 +1546,37 @@ export async function createUpgradeSnapshot({
|
|
|
1041
1546
|
upgradeSoftLimitBytes = UPGRADE_SNAPSHOT_SOFT_LIMIT_BYTES,
|
|
1042
1547
|
copyDatabase = copySqliteDatabase,
|
|
1043
1548
|
checkIntegrity = checkSqliteIntegrity,
|
|
1549
|
+
// As for createVerifiedBackup: left out, the snapshot is encrypted when the owner turned encryption on.
|
|
1550
|
+
encryption = undefined,
|
|
1044
1551
|
now = () => new Date(),
|
|
1045
1552
|
} = {}) {
|
|
1046
|
-
const report = (detail) => { try { if (typeof onProgress === 'function') onProgress(detail); } catch { /* reporting never stops a snapshot */ } };
|
|
1553
|
+
const report = (detail) => { markActivity(`backup:${detail.phase}`); try { if (typeof onProgress === 'function') onProgress(detail); } catch { /* reporting never stops a snapshot */ } };
|
|
1047
1554
|
if (!dataHome || !folderPath) throw new Error('dataHome and folderPath are required');
|
|
1048
1555
|
if (!UPGRADE_BACKUP_KINDS.has(kind)) throw new Error(`An upgrade snapshot is ${[...UPGRADE_BACKUP_KINDS].join(' or ')}, not ${kind}`);
|
|
1049
1556
|
const started = Date.now();
|
|
1557
|
+
// Before anything is written: a key file that cannot be used fails the snapshot here.
|
|
1558
|
+
const encrypt = backupEncryptionFor(dataHome, encryption);
|
|
1050
1559
|
const createdAt = now();
|
|
1051
1560
|
assertBackupDestinationMounted(folderPath);
|
|
1052
1561
|
mkdirSync(folderPath, { recursive: true });
|
|
1053
1562
|
cleanupStaleBackupArtifacts(folderPath);
|
|
1054
|
-
const destination = resolve(folderPath, archiveNameFor(kind, createdAt));
|
|
1563
|
+
const destination = resolve(folderPath, archiveNameFor(kind, createdAt, !!encrypt));
|
|
1055
1564
|
if (existsSync(destination)) throw new Error(`Backup already exists: ${destination}`);
|
|
1056
1565
|
const tempPath = `${destination}.${process.pid}.tmp`;
|
|
1057
|
-
|
|
1058
|
-
|
|
1566
|
+
const tempInfoPath = `${backupInfoPath(destination)}.${process.pid}.tmp`;
|
|
1567
|
+
// Everything this snapshot copies lives here until the archive is published (an abandoned one is swept after an
|
|
1568
|
+
// hour). The copies are plaintext: an encrypted snapshot keeps them in the data home's private folder.
|
|
1569
|
+
if (encrypt) cleanupStaleBackupArtifacts(privateBackupStagingRoot(dataHome));
|
|
1570
|
+
const work = encrypt ? await makePrivateStage(dataHome) : mkdtempSync(resolve(folderPath, `.synabun-files-${process.pid}-`));
|
|
1571
|
+
let writer = null;
|
|
1059
1572
|
const timings = {};
|
|
1060
1573
|
const mark = (name, since) => { timings[name] = Date.now() - since; };
|
|
1061
1574
|
// The integrity check of the database copies, once they exist: { results, ms } or { error, ms }, never a rejection.
|
|
1062
1575
|
let integrity = null;
|
|
1576
|
+
let workerTimedOut = false;
|
|
1063
1577
|
try {
|
|
1064
1578
|
let since = Date.now();
|
|
1065
|
-
const { inputs: kept, excluded } = collectUpgradeInputs({ dataHome, additionalEntries, softLimitBytes: upgradeSoftLimitBytes });
|
|
1579
|
+
const { inputs: kept, excluded, skippedEmpty } = collectUpgradeInputs({ dataHome, additionalEntries, softLimitBytes: upgradeSoftLimitBytes });
|
|
1066
1580
|
const databaseBytes = existsSync(databasePath) ? statSync(databasePath).size : 0;
|
|
1067
1581
|
const walBytes = existsSync(`${databasePath}-wal`) ? statSync(`${databasePath}-wal`).size : 0;
|
|
1068
1582
|
const keptBytes = kept.reduce((sum, file) => sum + backupFileSize(file), 0);
|
|
@@ -1073,6 +1587,8 @@ export async function createUpgradeSnapshot({
|
|
|
1073
1587
|
skippedFiles: excluded?.files ?? 0,
|
|
1074
1588
|
skippedBytes: excluded?.bytes ?? 0,
|
|
1075
1589
|
skippedReason: excluded?.reason ?? null,
|
|
1590
|
+
skippedEmptyDatabases: skippedEmpty.databases,
|
|
1591
|
+
skippedEmptyDatabaseFiles: skippedEmpty.files,
|
|
1076
1592
|
});
|
|
1077
1593
|
|
|
1078
1594
|
// Room for it: the archive holds everything once; a database that cannot be cloned is copied first.
|
|
@@ -1125,6 +1641,7 @@ export async function createUpgradeSnapshot({
|
|
|
1125
1641
|
if (error?.code === 'ENOENT') continue;
|
|
1126
1642
|
throw error;
|
|
1127
1643
|
}
|
|
1644
|
+
if (encrypt && process.platform !== 'win32') chmodSync(staged, 0o600);
|
|
1128
1645
|
entries.push({ diskPath: staged, archivePath: file.archivePath, store });
|
|
1129
1646
|
recorded.push({ entry: file.archivePath, path: inputPath(dataHome, file.diskPath) });
|
|
1130
1647
|
}
|
|
@@ -1173,10 +1690,12 @@ export async function createUpgradeSnapshot({
|
|
|
1173
1690
|
verification: { algorithm: 'sha256', publication: 'verify-before-atomic-rename', writer: 'one-pass', integrity: 'integrity_check' },
|
|
1174
1691
|
}, null, 2);
|
|
1175
1692
|
};
|
|
1693
|
+
// Encrypted: the ZIP goes through the encrypting thread as it is written and never exists in plaintext.
|
|
1694
|
+
if (encrypt) writer = createEncryptedBackupWriter(tempPath, encrypt.recipient, { chunkSize: encrypt.chunkSize, now });
|
|
1176
1695
|
await writeZipArchive(tempPath, [
|
|
1177
1696
|
...entries.map(entry => ({ name: `${BACKUP_PREFIX}/${entry.archivePath}`, diskPath: entry.diskPath, store: entry.store })),
|
|
1178
1697
|
{ name: `${BACKUP_PREFIX}/manifest.json`, data: manifestFor },
|
|
1179
|
-
], { now, onProgress: ({ bytes, totalBytes }) => report({ phase: 'archive', done: bytes, total: Math.max(total, totalBytes) }) });
|
|
1698
|
+
], { now, sink: writer, onProgress: ({ bytes, totalBytes }) => report({ phase: 'archive', done: bytes, total: Math.max(total, totalBytes) }) });
|
|
1180
1699
|
mark('archive', since);
|
|
1181
1700
|
|
|
1182
1701
|
since = Date.now();
|
|
@@ -1184,6 +1703,8 @@ export async function createUpgradeSnapshot({
|
|
|
1184
1703
|
let reportedAt = 0;
|
|
1185
1704
|
report({ phase: 'verify', done: 0, total });
|
|
1186
1705
|
const publishedManifest = await verifyBackupArchive(tempPath, {
|
|
1706
|
+
fileKey: writer ? writer.fileKey : null,
|
|
1707
|
+
authKey: writer ? writer.authKey : null,
|
|
1187
1708
|
onBytes: (bytes) => {
|
|
1188
1709
|
checked += bytes;
|
|
1189
1710
|
if (checked - reportedAt >= 64 * 1024 * 1024 || checked >= total) { reportedAt = checked; report({ phase: 'verify', done: checked, total }); }
|
|
@@ -1197,6 +1718,7 @@ export async function createUpgradeSnapshot({
|
|
|
1197
1718
|
timings.integrity = verdict.ms;
|
|
1198
1719
|
mark('integrityWait', since);
|
|
1199
1720
|
if (verdict.error) {
|
|
1721
|
+
if (verdict.error.code === 'BACKUP_WORKER_TIMEOUT') throw verdict.error;
|
|
1200
1722
|
throw Object.assign(new Error(`SQLite's integrity check of the copies could not run: ${verdict.error?.message || verdict.error}`), { code: 'EINTEGRITY' });
|
|
1201
1723
|
}
|
|
1202
1724
|
for (const [index, result] of copies.entries()) {
|
|
@@ -1206,7 +1728,12 @@ export async function createUpgradeSnapshot({
|
|
|
1206
1728
|
report({ phase: 'integrity', state: 'ok' });
|
|
1207
1729
|
// The copies are in the archive and checked: their room goes back.
|
|
1208
1730
|
try { rmSync(work, { recursive: true, force: true }); } catch {}
|
|
1731
|
+
if (encrypt && !(await isEncryptedBackupFile(tempPath))) throw new BackupEncryptionError('BACKUP_ENC_NOT_ENCRYPTED', 'The snapshot was not encrypted: it is not published.', { status: 500 });
|
|
1732
|
+
// What the next start reads without the password, for a snapshot that stays inside the data home.
|
|
1733
|
+
const withInfo = !!encrypt && pathInside(folderPath, dataHome);
|
|
1734
|
+
if (withInfo) await writeSnapshotInfo(tempInfoPath, tempPath, publishedManifest, writer.authKey);
|
|
1209
1735
|
renameSync(tempPath, destination);
|
|
1736
|
+
if (withInfo) renameSync(tempInfoPath, backupInfoPath(destination));
|
|
1210
1737
|
return {
|
|
1211
1738
|
path: destination,
|
|
1212
1739
|
name: basename(destination),
|
|
@@ -1214,25 +1741,36 @@ export async function createUpgradeSnapshot({
|
|
|
1214
1741
|
createdAt: createdAt.toISOString(),
|
|
1215
1742
|
sizeBytes: statSync(destination).size,
|
|
1216
1743
|
manifest: publishedManifest,
|
|
1744
|
+
encrypted: !!encrypt,
|
|
1217
1745
|
stamp: backupFileStamp(destination),
|
|
1218
1746
|
database: database ? { method: database.method, sizeBytes: database.sizeBytes, memoryCount: database.memoryCount, integrity: 'ok' } : null,
|
|
1219
1747
|
timings: { ...timings, total: Date.now() - started },
|
|
1220
1748
|
};
|
|
1221
1749
|
} catch (error) {
|
|
1222
|
-
|
|
1750
|
+
workerTimedOut = error.code === 'BACKUP_WORKER_TIMEOUT';
|
|
1751
|
+
error.workerTermination?.then(async () => {
|
|
1752
|
+
await rm(tempPath, { force: true }).catch(() => {});
|
|
1753
|
+
await rm(work, { recursive: true, force: true }).catch(() => {});
|
|
1754
|
+
}).catch(() => {});
|
|
1755
|
+
if (writer) await writer.abort().catch(() => {});
|
|
1756
|
+
try { rmSync(tempInfoPath, { force: true }); } catch {}
|
|
1757
|
+
if (workerTimedOut) await waitForBackupCleanup(rm(tempPath, { force: true }).catch(() => {}), true);
|
|
1758
|
+
else { try { if (existsSync(tempPath)) unlinkSync(tempPath); } catch {} }
|
|
1223
1759
|
throw error;
|
|
1224
1760
|
} finally {
|
|
1225
|
-
|
|
1761
|
+
if (writer) writer.wipe();
|
|
1762
|
+
// Cancel a check still reading the copies before cleanup; a native I/O timeout also retries on exit.
|
|
1226
1763
|
if (integrity) {
|
|
1227
1764
|
integrity.cancel();
|
|
1228
1765
|
await integrity;
|
|
1229
1766
|
}
|
|
1230
|
-
|
|
1767
|
+
if (workerTimedOut) await waitForBackupCleanup(rm(work, { recursive: true, force: true }).catch(() => {}), true);
|
|
1768
|
+
else { try { rmSync(work, { recursive: true, force: true }); } catch {} }
|
|
1231
1769
|
}
|
|
1232
1770
|
}
|
|
1233
1771
|
|
|
1234
1772
|
function dateFromSnapshotName(name, stat) {
|
|
1235
|
-
const match = name.match(/^synabun-[a-z-]+-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)\.zip
|
|
1773
|
+
const match = name.match(/^synabun-[a-z-]+-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)\.zip(?:\.enc)?$/i);
|
|
1236
1774
|
if (!match) return stat.mtime;
|
|
1237
1775
|
const iso = match[1].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, 'T$1:$2:$3.$4Z');
|
|
1238
1776
|
const value = new Date(iso);
|
|
@@ -1244,25 +1782,34 @@ function kindFromName(name) {
|
|
|
1244
1782
|
return match?.[1]?.toLowerCase() || (name === 'synabun-auto-backup.zip' ? 'legacy' : 'unknown');
|
|
1245
1783
|
}
|
|
1246
1784
|
|
|
1247
|
-
export function listBackupSnapshots(folderPath) {
|
|
1248
|
-
if (!folderPath
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1785
|
+
export async function listBackupSnapshots(folderPath) {
|
|
1786
|
+
if (!folderPath) return [];
|
|
1787
|
+
let names;
|
|
1788
|
+
try { names = await readdir(folderPath); }
|
|
1789
|
+
catch (error) {
|
|
1790
|
+
if (error.code === 'ENOENT') return [];
|
|
1791
|
+
throw error;
|
|
1792
|
+
}
|
|
1793
|
+
const snapshots = [];
|
|
1794
|
+
// Metadata only: never open or inflate an archive. Sequential awaits keep filesystem work bounded.
|
|
1795
|
+
for (const name of names) {
|
|
1796
|
+
// A backup, plain (.zip) or encrypted (.zip.enc): told by the name here, by its first bytes when it is opened.
|
|
1797
|
+
const encrypted = name.endsWith(`.zip${BACKUP_ENC_EXTENSION}`);
|
|
1798
|
+
if ((!name.endsWith('.zip') && !encrypted) || !name.startsWith('synabun-')) continue;
|
|
1799
|
+
const path = resolve(folderPath, name);
|
|
1800
|
+
let info;
|
|
1801
|
+
try { info = await stat(path); }
|
|
1802
|
+
catch (error) {
|
|
1803
|
+
if (error.code === 'ENOENT') continue; // another retention pass/download may have removed it
|
|
1804
|
+
throw error;
|
|
1805
|
+
}
|
|
1806
|
+
const created = dateFromSnapshotName(name, info);
|
|
1807
|
+
snapshots.push({
|
|
1808
|
+
name, path, kind: kindFromName(name), pinned: name === 'synabun-auto-backup.zip',
|
|
1809
|
+
createdAt: created.toISOString(), createdMs: created.getTime(), sizeBytes: info.size, encrypted,
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
return snapshots.sort((a, b) => b.createdMs - a.createdMs);
|
|
1266
1813
|
}
|
|
1267
1814
|
|
|
1268
1815
|
function utcDay(dateMs) {
|
|
@@ -1276,15 +1823,15 @@ function utcWeek(dateMs) {
|
|
|
1276
1823
|
return date.toISOString().slice(0, 10);
|
|
1277
1824
|
}
|
|
1278
1825
|
|
|
1279
|
-
export function applyBackupRetention({
|
|
1826
|
+
export async function applyBackupRetention({
|
|
1280
1827
|
folderPath,
|
|
1281
1828
|
retention = DEFAULT_BACKUP_RETENTION,
|
|
1282
1829
|
incomingBytes = 0,
|
|
1283
1830
|
now = () => new Date(),
|
|
1284
|
-
remove = path =>
|
|
1831
|
+
remove = path => removeBackupFile(path),
|
|
1285
1832
|
} = {}) {
|
|
1286
1833
|
const policy = { ...DEFAULT_BACKUP_RETENTION, ...(retention || {}) };
|
|
1287
|
-
const snapshots = listBackupSnapshots(folderPath);
|
|
1834
|
+
const snapshots = await listBackupSnapshots(folderPath);
|
|
1288
1835
|
const currentMs = now().getTime();
|
|
1289
1836
|
const recentCutoff = currentMs - policy.recentHours * 60 * 60 * 1000;
|
|
1290
1837
|
const dailyCutoff = currentMs - policy.dailyDays * 24 * 60 * 60 * 1000;
|
|
@@ -1320,11 +1867,11 @@ export function applyBackupRetention({
|
|
|
1320
1867
|
const removed = [];
|
|
1321
1868
|
for (const item of snapshots) {
|
|
1322
1869
|
if (keep.has(item.path) || item.kind === 'manual' || item.kind === 'unknown') continue;
|
|
1323
|
-
remove(item.path);
|
|
1870
|
+
await remove(item.path);
|
|
1324
1871
|
removed.push(item.path);
|
|
1325
1872
|
}
|
|
1326
1873
|
|
|
1327
|
-
let retained = listBackupSnapshots(folderPath);
|
|
1874
|
+
let retained = await listBackupSnapshots(folderPath);
|
|
1328
1875
|
let totalBytes = retained.reduce((sum, item) => sum + item.sizeBytes, 0);
|
|
1329
1876
|
const normalizedIncomingBytes = Math.max(0, Number(incomingBytes) || 0);
|
|
1330
1877
|
const targetBytes = Math.max(0, policy.maxBytes - normalizedIncomingBytes);
|
|
@@ -1334,11 +1881,11 @@ export function applyBackupRetention({
|
|
|
1334
1881
|
.sort((a, b) => a.createdMs - b.createdMs);
|
|
1335
1882
|
for (const item of removable) {
|
|
1336
1883
|
if (totalBytes <= targetBytes) break;
|
|
1337
|
-
remove(item.path);
|
|
1884
|
+
await remove(item.path);
|
|
1338
1885
|
removed.push(item.path);
|
|
1339
1886
|
totalBytes -= item.sizeBytes;
|
|
1340
1887
|
}
|
|
1341
|
-
retained = listBackupSnapshots(folderPath);
|
|
1888
|
+
retained = await listBackupSnapshots(folderPath);
|
|
1342
1889
|
}
|
|
1343
1890
|
return {
|
|
1344
1891
|
retention: policy,
|
|
@@ -1445,3 +1992,11 @@ export function saveBackupConfig(path, value) {
|
|
|
1445
1992
|
}
|
|
1446
1993
|
return config;
|
|
1447
1994
|
}
|
|
1995
|
+
|
|
1996
|
+
if (parentPort && workerData?.verifiedBackupTask) {
|
|
1997
|
+
const tasks = { collect: collectVerifiedBackupInputs, copy: copyVerifiedDatabases, measure: measureBackupGroups, sweep: cleanupCrashedBackupArtifacts };
|
|
1998
|
+
Promise.resolve().then(() => tasks[workerData.verifiedBackupTask](workerData.options)).then(
|
|
1999
|
+
result => parentPort.postMessage({ result }),
|
|
2000
|
+
error => parentPort.postMessage({ error, code: error.code }),
|
|
2001
|
+
);
|
|
2002
|
+
}
|