synabun 2.4.0 → 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 +47 -0
- package/README.md +1 -1
- package/browser-extension/content.js +73 -11
- package/browser-extension/engine.js +196 -15
- package/browser-extension/manifest.json +4 -2
- package/browser-extension/popup-strings.js +10 -4
- package/browser-extension/popup-view.js +1 -1
- package/browser-extension/popup.css +1 -0
- package/browser-extension/popup.html +4 -1
- package/browser-extension/popup.js +22 -10
- package/browser-extension/protocol.js +102 -11
- package/browser-extension/service-worker.js +20 -4
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +25 -5
- package/lib/data-home-files.js +47 -0
- package/lib/data-home-migration.js +34 -58
- 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 +6 -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 +13 -8
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +35 -15
- 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 +23 -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 +33 -14
- 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 +266 -2
- package/neural-interface/i18n/pt-BR.json +267 -3
- package/neural-interface/lib/agents/builtins.json +207 -0
- package/neural-interface/lib/agents/registry.js +60 -15
- package/neural-interface/lib/agents/resolve.js +69 -10
- 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-brains/opencode.js +60 -11
- 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 +384 -119
- package/neural-interface/lib/assistant-persona.js +17 -5
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +181 -54
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +48 -34
- 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 +836 -322
- 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 +109 -24
- package/neural-interface/lib/browser-extension-bridge.js +42 -8
- 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 +34 -14
- package/neural-interface/lib/opencode-build-preflight.js +30 -8
- 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/peer-identity.js +13 -8
- 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 +70 -44
- 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 +196 -97
- package/neural-interface/lib/teams/schema.js +1 -1
- 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 +260 -0
- package/neural-interface/public/offline.html +4 -3
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
- package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
- 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/agents/studio/ax-ui.js +2 -2
- 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 +3 -2
- 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 +106 -38
- package/neural-interface/public/shared/assistant/asst-route.js +102 -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/cc-dropdown.js +21 -15
- 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 -51
- 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/owner-authority-view.js +4 -10
- package/neural-interface/public/shared/page-session.js +1 -1
- 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-ai-browser.js +5 -5
- 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/start-bridge.js +2 -2
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +354 -438
- 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 +185 -25
- package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
- 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-owner-authority.js +48 -25
- 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 +234 -67
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-sync.js +1 -0
- 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/sw.js +4 -3
- 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 +17 -4
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +507 -160
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
accessSync,
|
|
3
|
+
chmodSync,
|
|
3
4
|
closeSync,
|
|
4
5
|
copyFileSync,
|
|
5
6
|
constants as FS_CONSTANTS,
|
|
6
7
|
createReadStream,
|
|
7
8
|
existsSync,
|
|
8
|
-
lstatSync,
|
|
9
9
|
mkdtempSync,
|
|
10
10
|
mkdirSync,
|
|
11
11
|
openSync,
|
|
@@ -19,16 +19,27 @@ import {
|
|
|
19
19
|
unlinkSync,
|
|
20
20
|
writeFileSync,
|
|
21
21
|
} from 'node:fs';
|
|
22
|
+
import { chmod, copyFile, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
22
23
|
import { execFileSync } from 'node:child_process';
|
|
23
24
|
import { createHash } from 'node:crypto';
|
|
24
25
|
import { basename, dirname, extname, isAbsolute, join, parse as parsePath, relative, resolve, sep } from 'node:path';
|
|
25
26
|
import * as nodeSqlite from 'node:sqlite';
|
|
26
27
|
import { DatabaseSync } from 'node:sqlite';
|
|
27
|
-
import { Worker } from 'node:worker_threads';
|
|
28
|
+
import { parentPort, Worker, workerData } from 'node:worker_threads';
|
|
28
29
|
import archiver from 'archiver';
|
|
30
|
+
import { markActivity } from './loop-stall.js';
|
|
29
31
|
import { openZipArchive, readZipEntry, verifyBackupChecksums } from './backup-zip-reader.js';
|
|
30
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';
|
|
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
|
|
|
@@ -304,36 +361,34 @@ export function assertBackupDestinationMounted(folderPath, options) {
|
|
|
304
361
|
if (missing) throw new BackupDestinationUnavailableError({ ...missing, folderPath });
|
|
305
362
|
}
|
|
306
363
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
let entries;
|
|
325
|
-
try { entries = readdirSync(current).sort(); }
|
|
326
|
-
catch (error) {
|
|
327
|
-
if (error?.code === 'ENOENT') return;
|
|
328
|
-
throw error;
|
|
364
|
+
// De-duplicate as files are discovered. Later additional entries take precedence,
|
|
365
|
+
// as before, without constructing an argument list or a second subtree listing.
|
|
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 = {}) {
|
|
369
|
+
const entries = new Map();
|
|
370
|
+
const add = (diskPath, archivePath) => entries.set(archivePath.replace(/\\/g, '/'), { diskPath, archivePath });
|
|
371
|
+
const envPath = resolve(dataHome, '.env');
|
|
372
|
+
if (existsSync(envPath)) add(envPath, 'env.bak');
|
|
373
|
+
|
|
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();
|
|
378
|
+
if (!stat.isFile()) continue;
|
|
379
|
+
const rel = relative(root, path).replace(/\\/g, '/');
|
|
380
|
+
if (!filter || filter(rel)) add(path, rel ? `${archiveRoot}/${rel}` : archiveRoot);
|
|
329
381
|
}
|
|
330
|
-
for (const entry of entries) walk(join(current, entry));
|
|
331
382
|
}
|
|
332
|
-
|
|
333
|
-
|
|
383
|
+
for (const dir of BACKUP_DATA_DIRS) collect(resolve(dataHome, dir), dir, filters[dir], skipDirs[dir]);
|
|
384
|
+
for (const entry of additionalEntries) {
|
|
385
|
+
if (entry?.diskPath && entry?.archivePath) collect(entry.diskPath, entry.archivePath);
|
|
386
|
+
}
|
|
387
|
+
return Array.from(entries.values());
|
|
334
388
|
}
|
|
335
389
|
|
|
336
390
|
function backupFileSize(file) {
|
|
391
|
+
reportBackupWorkerProgress();
|
|
337
392
|
try { return statSync(file.diskPath).size; }
|
|
338
393
|
catch (error) {
|
|
339
394
|
if (error?.code === 'ENOENT') return 0;
|
|
@@ -357,38 +412,40 @@ export function backupAvailableBytes(folderPath) {
|
|
|
357
412
|
return Number(stats.bavail) * Number(stats.bsize);
|
|
358
413
|
}
|
|
359
414
|
|
|
360
|
-
|
|
361
|
-
folderPath,
|
|
415
|
+
function estimateBackupWorkingSpace({
|
|
362
416
|
files = [],
|
|
363
417
|
databasePath = null,
|
|
364
418
|
expectedArchiveBytes = 0,
|
|
365
419
|
freeSpaceReserveBytes = BACKUP_FREE_SPACE_RESERVE_BYTES,
|
|
366
|
-
getAvailableBytes = backupAvailableBytes,
|
|
367
420
|
} = {}) {
|
|
368
421
|
const primaryDatabaseBytes = databasePath && existsSync(databasePath) ? statSync(databasePath).size : 0;
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
422
|
+
let inputBytes = primaryDatabaseBytes;
|
|
423
|
+
let stagedMutableBytes = 0;
|
|
424
|
+
let sqliteSnapshotBytes = primaryDatabaseBytes;
|
|
425
|
+
for (const file of files) {
|
|
426
|
+
const size = backupFileSize(file);
|
|
427
|
+
inputBytes += size;
|
|
428
|
+
if (isSqliteBackupInput(file)) sqliteSnapshotBytes += size;
|
|
429
|
+
else if (isMutableBackupInput(file)) stagedMutableBytes += size;
|
|
430
|
+
}
|
|
376
431
|
const archiveBytes = Math.max(Number(expectedArchiveBytes) || 0, inputBytes);
|
|
377
432
|
const requiredBytes = Math.max(0, Number(freeSpaceReserveBytes) || 0)
|
|
378
433
|
+ stagedMutableBytes
|
|
379
434
|
+ sqliteSnapshotBytes
|
|
380
435
|
+ archiveBytes;
|
|
436
|
+
return { requiredBytes, archiveBytes, stagedMutableBytes, sqliteSnapshotBytes };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function checkWorkingSpace(folderPath, estimate, getAvailableBytes) {
|
|
381
440
|
const availableBytes = Number(getAvailableBytes(folderPath));
|
|
382
|
-
if (Number.isFinite(availableBytes) && availableBytes < requiredBytes) {
|
|
383
|
-
throw new BackupStorageError({ availableBytes, requiredBytes, folderPath });
|
|
441
|
+
if (Number.isFinite(availableBytes) && availableBytes < estimate.requiredBytes) {
|
|
442
|
+
throw new BackupStorageError({ availableBytes, requiredBytes: estimate.requiredBytes, folderPath });
|
|
384
443
|
}
|
|
385
|
-
return {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
sqliteSnapshotBytes,
|
|
391
|
-
};
|
|
444
|
+
return { availableBytes, ...estimate };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function assertBackupWorkingSpace({ folderPath, getAvailableBytes = backupAvailableBytes, ...inputs } = {}) {
|
|
448
|
+
return checkWorkingSpace(folderPath, estimateBackupWorkingSpace(inputs), getAvailableBytes);
|
|
392
449
|
}
|
|
393
450
|
|
|
394
451
|
/**
|
|
@@ -397,20 +454,27 @@ export function assertBackupWorkingSpace({
|
|
|
397
454
|
* so its partial archive is orphaned forever — a killed pre-update snapshot
|
|
398
455
|
* left hundreds of MB behind with nothing to reclaim it.
|
|
399
456
|
*/
|
|
400
|
-
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 } = {}) {
|
|
401
458
|
if (!existsSync(folderPath)) return [];
|
|
402
459
|
const removed = [];
|
|
403
460
|
let entries;
|
|
404
461
|
try { entries = readdirSync(folderPath); }
|
|
405
462
|
catch { return removed; }
|
|
406
463
|
for (const name of entries) {
|
|
407
|
-
|
|
464
|
+
reportBackupWorkerProgress();
|
|
465
|
+
const archiveTemp = name.match(/\.zip(?:\.enc)?(?:\.info\.json)?\.(\d+)\.tmp$/);
|
|
408
466
|
const isSqliteTemp = /^\.synabun-(?:db|extra-db)-.*\.tmp$/.test(name);
|
|
409
|
-
const
|
|
410
|
-
|
|
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;
|
|
411
471
|
const path = resolve(folderPath, name);
|
|
412
472
|
try {
|
|
413
|
-
|
|
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;
|
|
414
478
|
rmSync(path, { recursive: true, force: true });
|
|
415
479
|
removed.push(name);
|
|
416
480
|
} catch { /* another process may be mid-cleanup; leave it */ }
|
|
@@ -418,91 +482,253 @@ export function cleanupStaleBackupArtifacts(folderPath, { maxAgeMs = 60 * 60 * 1
|
|
|
418
482
|
return removed;
|
|
419
483
|
}
|
|
420
484
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
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.
|
|
425
517
|
try {
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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.
|
|
433
527
|
try {
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
// longer part of the state being backed up. Other failures are fatal.
|
|
439
|
-
if (error?.code !== 'ENOENT') throw error;
|
|
440
|
-
}
|
|
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 */ }
|
|
441
532
|
}
|
|
442
|
-
|
|
443
|
-
} catch (error) {
|
|
444
|
-
try { rmSync(stageDir, { recursive: true, force: true }); } catch {}
|
|
445
|
-
throw error;
|
|
533
|
+
if (gone.length) removed[folder] = [...(removed[folder] || []), ...gone];
|
|
446
534
|
}
|
|
535
|
+
return removed;
|
|
447
536
|
}
|
|
448
537
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
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 });
|
|
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;
|
|
458
587
|
}
|
|
459
|
-
if (stat.isSymbolicLink()) continue;
|
|
460
|
-
if (stat.isDirectory()) result.push(...collectFiles(entry.diskPath, entry.archivePath));
|
|
461
|
-
else if (stat.isFile()) result.push({ diskPath: entry.diskPath, archivePath: entry.archivePath });
|
|
462
588
|
}
|
|
463
|
-
return
|
|
589
|
+
return snapshots;
|
|
464
590
|
}
|
|
465
591
|
|
|
466
|
-
|
|
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 }) {
|
|
467
594
|
const { createWriteStream } = await import('node:fs');
|
|
468
|
-
|
|
469
|
-
|
|
595
|
+
throwIfCancelled(signal);
|
|
596
|
+
let onAbort = null;
|
|
597
|
+
try {
|
|
598
|
+
await new Promise((resolveWrite, reject) => {
|
|
599
|
+
const output = givenOutput || createWriteStream(tempPath, { flags: 'wx' });
|
|
470
600
|
const archive = archiver('zip', { zlib: { level } });
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
601
|
+
const remaining = files.values();
|
|
602
|
+
let failure;
|
|
603
|
+
function fail(error) {
|
|
604
|
+
if (failure) return;
|
|
605
|
+
failure = error;
|
|
606
|
+
archive.abort();
|
|
607
|
+
output.destroy();
|
|
608
|
+
}
|
|
609
|
+
onAbort = () => fail(new BackupCancelledError());
|
|
610
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
611
|
+
// Archiver queues a stat and a lazy stream for each file handed to it.
|
|
612
|
+
// Feed one member after the preceding entry has finished.
|
|
613
|
+
function appendNext() {
|
|
614
|
+
const next = remaining.next();
|
|
615
|
+
if (next.done) {
|
|
616
|
+
archive.finalize().catch(fail);
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
const file = next.value;
|
|
477
620
|
const store = INCOMPRESSIBLE_EXTENSIONS.has(extname(file.archivePath).toLowerCase());
|
|
478
621
|
archive.file(file.diskPath, { name: `${BACKUP_PREFIX}/${file.archivePath}`, store });
|
|
479
622
|
}
|
|
623
|
+
output.on('close', () => failure ? reject(failure) : resolveWrite());
|
|
624
|
+
output.on('error', fail);
|
|
625
|
+
archive.on('warning', error => error.code === 'ENOENT' ? appendNext() : fail(error));
|
|
626
|
+
archive.on('error', fail);
|
|
627
|
+
archive.on('entry', appendNext);
|
|
628
|
+
archive.pipe(output);
|
|
480
629
|
archive.append(JSON.stringify(manifest, null, 2), { name: `${BACKUP_PREFIX}/manifest.json` });
|
|
481
|
-
|
|
482
|
-
}
|
|
630
|
+
});
|
|
631
|
+
} finally {
|
|
632
|
+
if (onAbort) signal?.removeEventListener('abort', onAbort);
|
|
633
|
+
}
|
|
483
634
|
}
|
|
484
635
|
|
|
485
636
|
/**
|
|
486
637
|
* Reopen a finished archive and stream every manifest-listed entry through
|
|
487
638
|
* sha256. Streaming matters: reading the archive into memory failed every
|
|
488
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.
|
|
489
650
|
*/
|
|
490
|
-
export async function
|
|
491
|
-
|
|
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 });
|
|
492
663
|
try {
|
|
493
664
|
const manifestEntry = zip.getEntry(`${BACKUP_PREFIX}/manifest.json`);
|
|
494
665
|
if (!manifestEntry) throw new Error('Backup verification failed: manifest is missing');
|
|
495
666
|
const manifest = JSON.parse((await readZipEntry(zip, manifestEntry)).toString('utf-8'));
|
|
496
|
-
|
|
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);
|
|
497
672
|
return manifest;
|
|
673
|
+
} catch (error) {
|
|
674
|
+
if (signal?.aborted) throw new BackupCancelledError();
|
|
675
|
+
throw error;
|
|
498
676
|
} finally {
|
|
499
677
|
await zip.close();
|
|
500
678
|
}
|
|
501
679
|
}
|
|
502
680
|
|
|
503
|
-
/**
|
|
504
|
-
|
|
505
|
-
|
|
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 });
|
|
506
732
|
try {
|
|
507
733
|
const manifestEntry = zip.getEntry(`${BACKUP_PREFIX}/manifest.json`);
|
|
508
734
|
if (!manifestEntry) throw new Error('Backup verification failed: manifest is missing');
|
|
@@ -512,6 +738,80 @@ export async function readBackupArchiveManifest(path) {
|
|
|
512
738
|
}
|
|
513
739
|
}
|
|
514
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
|
+
|
|
515
815
|
/** Create, reopen, checksum-verify, and atomically publish one immutable ZIP. */
|
|
516
816
|
export async function createVerifiedBackup({
|
|
517
817
|
dataHome,
|
|
@@ -525,100 +825,112 @@ export async function createVerifiedBackup({
|
|
|
525
825
|
expectedArchiveBytes = 0,
|
|
526
826
|
freeSpaceReserveBytes = BACKUP_FREE_SPACE_RESERVE_BYTES,
|
|
527
827
|
getAvailableBytes = backupAvailableBytes,
|
|
828
|
+
checkIntegrity = checkSqliteIntegrity,
|
|
829
|
+
workerOptions = {},
|
|
528
830
|
onBeforeArchive = null,
|
|
529
831
|
onProgress = null,
|
|
530
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,
|
|
531
842
|
now = () => new Date(),
|
|
532
843
|
} = {}) {
|
|
533
844
|
// A large data home spends minutes in checksum/archive with no output. Phase
|
|
534
845
|
// reporting is what stops that from reading as a hang to the caller.
|
|
535
846
|
const report = typeof onProgress === 'function' ? onProgress : () => {};
|
|
536
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);
|
|
537
855
|
const createdAt = now();
|
|
538
856
|
assertBackupDestinationMounted(folderPath);
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const destination = resolve(folderPath, archiveNameFor(kind, createdAt));
|
|
857
|
+
await mkdir(folderPath, { recursive: true });
|
|
858
|
+
const destination = resolve(folderPath, archiveNameFor(kind, createdAt, !!encrypt));
|
|
542
859
|
const tempPath = `${destination}.${process.pid}.tmp`;
|
|
543
|
-
const sqliteTemp = resolve(folderPath, `.synabun-db-${process.pid}-${Date.now()}.tmp`);
|
|
544
|
-
const extraSqliteTemps = [];
|
|
545
860
|
if (existsSync(destination)) throw new Error(`Backup already exists: ${destination}`);
|
|
546
861
|
|
|
547
|
-
let sqliteSnapshot = null;
|
|
548
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;
|
|
549
866
|
try {
|
|
550
|
-
const files = [];
|
|
551
|
-
const envPath = resolve(dataHome, '.env');
|
|
552
|
-
if (existsSync(envPath)) files.push({ diskPath: envPath, archivePath: 'env.bak' });
|
|
553
|
-
// BACKUP_DATA_DIRS is the list other modules read (backupRoots): every folder copied here is on it.
|
|
554
|
-
const dataDirFilters = {
|
|
555
|
-
data: rel => !shouldSkipDataPath(rel),
|
|
556
|
-
'mcp-data': rel => !shouldSkipDataPath(rel)
|
|
557
|
-
&& !isDatabaseCopyArtifact(rel)
|
|
558
|
-
&& !/^memory\.db(?:-wal|-shm)?$/i.test(rel)
|
|
559
|
-
&& !/\.db-(?:wal|shm)$/i.test(rel),
|
|
560
|
-
};
|
|
561
|
-
for (const dir of BACKUP_DATA_DIRS) files.push(...collectFiles(resolve(dataHome, dir), dir, { filter: dataDirFilters[dir] }));
|
|
562
|
-
files.push(...normalizeAdditionalEntries(additionalEntries));
|
|
563
|
-
|
|
564
|
-
// De-duplicate before estimating work space so explicit additional entries
|
|
565
|
-
// cannot inflate the preflight or create ambiguous ZIP members.
|
|
566
|
-
const deduped = [...new Map(files.map(file => [
|
|
567
|
-
file.archivePath.replace(/\\/g, '/'),
|
|
568
|
-
file,
|
|
569
|
-
])).values()];
|
|
570
|
-
|
|
571
|
-
// Keep the upgrade path bounded: state is archived, generated media is not.
|
|
572
867
|
const leanSnapshot = UPGRADE_BACKUP_KINDS.has(kind);
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
const workingSpace =
|
|
580
|
-
folderPath,
|
|
581
|
-
|
|
582
|
-
databasePath,
|
|
583
|
-
expectedArchiveBytes,
|
|
584
|
-
freeSpaceReserveBytes,
|
|
585
|
-
getAvailableBytes,
|
|
586
|
-
});
|
|
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);
|
|
587
877
|
report({
|
|
588
878
|
phase: 'collect',
|
|
589
|
-
files:
|
|
879
|
+
files: files.length,
|
|
590
880
|
bytes: workingSpace.archiveBytes,
|
|
591
881
|
skippedFiles: excluded?.files ?? 0,
|
|
592
882
|
skippedBytes: excluded?.bytes ?? 0,
|
|
593
883
|
skippedReason: excluded?.reason ?? null,
|
|
594
884
|
});
|
|
595
885
|
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
files.
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
//
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
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' });
|
|
611
915
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
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 || []);
|
|
919
|
+
}
|
|
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 });
|
|
620
925
|
const checksums = {};
|
|
621
|
-
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'];
|
|
622
934
|
|
|
623
935
|
const manifest = {
|
|
624
936
|
version: BACKUP_MANIFEST_VERSION,
|
|
@@ -629,59 +941,76 @@ export async function createVerifiedBackup({
|
|
|
629
941
|
sourceFingerprint,
|
|
630
942
|
storage: 'sqlite',
|
|
631
943
|
database: sqliteSnapshot ? {
|
|
632
|
-
file:
|
|
944
|
+
file: sqliteSnapshot.archivePath,
|
|
633
945
|
sizeBytes: sqliteSnapshot.sizeBytes,
|
|
634
946
|
memoryCount: sqliteSnapshot.memoryCount,
|
|
635
|
-
integrity:
|
|
947
|
+
integrity: 'ok',
|
|
636
948
|
} : null,
|
|
637
949
|
files: finalFiles.map(file => file.archivePath),
|
|
638
950
|
checksums,
|
|
639
|
-
// A lean snapshot is not a whole-data-home backup. Recording
|
|
640
|
-
// keeps a restore from silently presenting it as one.
|
|
641
|
-
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 } : {}),
|
|
642
955
|
excluded,
|
|
643
956
|
verified: true,
|
|
644
957
|
verification: { algorithm: 'sha256', publication: 'verify-before-atomic-rename' },
|
|
645
958
|
};
|
|
646
959
|
if (typeof onBeforeArchive === 'function') await onBeforeArchive({ files: finalFiles, manifest });
|
|
647
|
-
|
|
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 });
|
|
648
964
|
// Level 1 on the blocking upgrade path: the remaining payload is mostly
|
|
649
965
|
// SQLite and JSON, where fast deflate still shrinks well.
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
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);
|
|
654
979
|
return {
|
|
655
980
|
path: destination,
|
|
656
981
|
name: basename(destination),
|
|
657
982
|
kind,
|
|
658
983
|
createdAt: createdAt.toISOString(),
|
|
659
|
-
sizeBytes:
|
|
984
|
+
sizeBytes: (await stat(destination)).size,
|
|
660
985
|
manifest: publishedManifest,
|
|
986
|
+
encrypted: !!encrypt,
|
|
987
|
+
...(writer ? { keyId: writer.keyId } : {}),
|
|
661
988
|
};
|
|
662
989
|
} catch (error) {
|
|
663
|
-
|
|
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);
|
|
664
999
|
throw error;
|
|
665
1000
|
} finally {
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
try { if (existsSync(path)) unlinkSync(path); } catch {}
|
|
669
|
-
}
|
|
670
|
-
if (stageDir) {
|
|
671
|
-
try { rmSync(stageDir, { recursive: true, force: true }); } catch {}
|
|
672
|
-
}
|
|
1001
|
+
if (writer) writer.wipe();
|
|
1002
|
+
if (stageDir) await waitForBackupCleanup(rm(stageDir, { recursive: true, force: true }).catch(() => {}), workerTimedOut);
|
|
673
1003
|
}
|
|
674
1004
|
}
|
|
675
1005
|
|
|
676
1006
|
// ── The pre-update snapshot: quick at any size ──
|
|
677
1007
|
//
|
|
678
|
-
//
|
|
679
|
-
//
|
|
680
|
-
// 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.
|
|
681
1010
|
// createUpgradeSnapshot() keeps what that snapshot promises (the state as of one commit, every byte in a ZIP the
|
|
682
1011
|
// restore paths read, every database copy passing the integrity check the restore runs, read back once and checked
|
|
683
|
-
// before it is published) and
|
|
684
|
-
//
|
|
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.
|
|
685
1014
|
//
|
|
686
1015
|
// The snapshot also records what it was taken from (`inputs` in its manifest): checkUpgradeSnapshotFreshness()
|
|
687
1016
|
// tells later, from any process, whether it still stands for the data as it is (lib/update-snapshot.js before the
|
|
@@ -705,8 +1034,10 @@ export function cloneMethodFor(source, targetDir, { platform = process.platform,
|
|
|
705
1034
|
}
|
|
706
1035
|
|
|
707
1036
|
function cloneFileNow(source, target, method) {
|
|
708
|
-
|
|
709
|
-
|
|
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 });
|
|
710
1041
|
}
|
|
711
1042
|
|
|
712
1043
|
const SQLITE_HEADER = Buffer.from('SQLite format 3\0', 'latin1');
|
|
@@ -736,25 +1067,6 @@ export function isSqliteDatabaseFile(path) {
|
|
|
736
1067
|
}
|
|
737
1068
|
}
|
|
738
1069
|
|
|
739
|
-
/** SHA-256 (hex) of a file, read in one pass on this thread (WAL files: small, and read while a lock is held). */
|
|
740
|
-
function hashFileNow(path) {
|
|
741
|
-
const digest = createHash('sha256');
|
|
742
|
-
const fd = openSync(path, 'r');
|
|
743
|
-
try {
|
|
744
|
-
const buffer = Buffer.allocUnsafe(4 * 1024 * 1024);
|
|
745
|
-
let position = 0;
|
|
746
|
-
for (;;) {
|
|
747
|
-
const read = readSync(fd, buffer, 0, buffer.length, position);
|
|
748
|
-
if (!read) break;
|
|
749
|
-
digest.update(buffer.subarray(0, read));
|
|
750
|
-
position += read;
|
|
751
|
-
}
|
|
752
|
-
} finally {
|
|
753
|
-
closeSync(fd);
|
|
754
|
-
}
|
|
755
|
-
return digest.digest('hex');
|
|
756
|
-
}
|
|
757
|
-
|
|
758
1070
|
/**
|
|
759
1071
|
* What tells a later reader, in any process, whether the SQLite database at `path` was written since: its file
|
|
760
1072
|
* (device, inode, size, modification and change times, and its first 100 bytes, where a rollback-journal database
|
|
@@ -768,7 +1080,7 @@ export function sqliteFingerprint(path) {
|
|
|
768
1080
|
const walPath = `${path}-wal`;
|
|
769
1081
|
try {
|
|
770
1082
|
const walSize = statSync(walPath).size;
|
|
771
|
-
if (walSize > 0) wal = { size: walSize, sha256:
|
|
1083
|
+
if (walSize > 0) wal = { size: walSize, sha256: hashFileSync(walPath) };
|
|
772
1084
|
} catch (error) {
|
|
773
1085
|
if (error?.code !== 'ENOENT') throw error;
|
|
774
1086
|
}
|
|
@@ -803,38 +1115,52 @@ export function sameSqliteFingerprint(a, b) {
|
|
|
803
1115
|
* can reset it while the lock is held.
|
|
804
1116
|
* backup anywhere else (or when the lock is not free within `busyTimeoutMs`), SQLite's online backup in
|
|
805
1117
|
* one step: one sequential read and write, from one read transaction, and no writer ever waits.
|
|
806
|
-
* 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.
|
|
807
1119
|
*
|
|
808
|
-
*
|
|
809
|
-
* so the
|
|
810
|
-
*
|
|
811
|
-
*
|
|
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,
|
|
812
1124
|
* and the memories of the `primary` database are counted (a query that fails there fails the copy). Resolves
|
|
813
1125
|
* { method, path, sizeBytes, memoryCount, pageCount, fingerprint }, or null when there is no database.
|
|
814
1126
|
*/
|
|
815
1127
|
export async function copySqliteDatabase(sourcePath, targetPath, {
|
|
816
1128
|
platform = process.platform, method: forced = null, busyTimeoutMs = 15_000, clone = cloneFileNow, primary = false,
|
|
1129
|
+
captureFingerprint = true, skipEmpty = false,
|
|
817
1130
|
} = {}) {
|
|
818
1131
|
if (!existsSync(sourcePath)) return null;
|
|
819
1132
|
for (const suffix of ['', '-wal', '-shm', '-journal']) rmSync(`${targetPath}${suffix}`, { force: true });
|
|
820
1133
|
const fallback = typeof nodeSqlite.backup === 'function' ? 'backup' : 'vacuum';
|
|
821
1134
|
let method = forced || cloneMethodFor(sourcePath, dirname(targetPath), { platform }) || fallback;
|
|
822
1135
|
let fingerprint = null;
|
|
1136
|
+
const readFingerprint = () => captureFingerprint ? sqliteFingerprint(sourcePath) : null;
|
|
823
1137
|
const source = new DatabaseSync(sourcePath);
|
|
824
1138
|
try {
|
|
825
|
-
//
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
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
|
+
}
|
|
830
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
|
+
}
|
|
831
1157
|
if (method === 'clone' || method === 'reflink') {
|
|
832
1158
|
let locked = false;
|
|
833
1159
|
let cloned = false;
|
|
834
1160
|
try {
|
|
835
1161
|
source.exec('BEGIN IMMEDIATE');
|
|
836
1162
|
locked = true;
|
|
837
|
-
fingerprint =
|
|
1163
|
+
fingerprint = readFingerprint();
|
|
838
1164
|
clone(sourcePath, targetPath, method);
|
|
839
1165
|
const wal = `${sourcePath}-wal`;
|
|
840
1166
|
if (existsSync(wal) && statSync(wal).size > 0) clone(wal, `${targetPath}-wal`, method);
|
|
@@ -848,11 +1174,11 @@ export async function copySqliteDatabase(sourcePath, targetPath, {
|
|
|
848
1174
|
if (!cloned) method = fallback;
|
|
849
1175
|
}
|
|
850
1176
|
if (method === 'backup') {
|
|
851
|
-
fingerprint =
|
|
1177
|
+
fingerprint = readFingerprint();
|
|
852
1178
|
// One step holds one read transaction for the whole copy: no restart, whatever the server writes.
|
|
853
1179
|
await nodeSqlite.backup(source, targetPath, { rate: 1_000_000_000 });
|
|
854
1180
|
} else if (method === 'vacuum') {
|
|
855
|
-
fingerprint =
|
|
1181
|
+
fingerprint = readFingerprint();
|
|
856
1182
|
source.exec(`VACUUM INTO '${escapeSqliteString(targetPath)}'`);
|
|
857
1183
|
}
|
|
858
1184
|
} finally {
|
|
@@ -886,26 +1212,138 @@ export async function copySqliteDatabase(sourcePath, targetPath, {
|
|
|
886
1212
|
}
|
|
887
1213
|
}
|
|
888
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
|
+
|
|
889
1335
|
/**
|
|
890
1336
|
* SQLite's PRAGMA integrity_check, the one `synabun restore-backup` runs, on each file in `paths`, on a thread of
|
|
891
1337
|
* its own (sqlite-integrity-worker.js): a 3.9 GB memory.db takes about 28 s, spent while the archive is written.
|
|
892
1338
|
* Resolves [{ path, ok, lines, ms }] (`lines`: SQLite's first findings when a file is not ok); `cancel()` on the
|
|
893
|
-
* promise stops the thread (it then rejects).
|
|
1339
|
+
* promise stops the thread (it then rejects). Each database gets a size-based inactivity budget.
|
|
894
1340
|
*/
|
|
895
|
-
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
|
+
} = {}) {
|
|
896
1345
|
if (!paths.length) return Object.assign(Promise.resolve([]), { cancel: () => {} });
|
|
897
|
-
|
|
898
|
-
const checking = new Promise((resolveCheck, reject) => {
|
|
899
|
-
let settled = false;
|
|
900
|
-
const settle = (fn, value) => { if (!settled) { settled = true; fn(value); } };
|
|
901
|
-
try { worker = spawnWorker({ paths }); }
|
|
902
|
-
catch (error) { reject(error); return; }
|
|
903
|
-
worker.once('message', (results) => settle(resolveCheck, results));
|
|
904
|
-
worker.once('error', (error) => settle(reject, error));
|
|
905
|
-
worker.once('exit', (code) => settle(reject, new Error(`the integrity check ended (exit ${code}) without a result`)));
|
|
906
|
-
});
|
|
907
|
-
checking.cancel = () => { try { worker?.terminate(); } catch { /* already gone */ } };
|
|
908
|
-
return checking;
|
|
1346
|
+
return watchBackupWorker('integrity', { paths }, { ...watchdog, spawnWorker });
|
|
909
1347
|
}
|
|
910
1348
|
|
|
911
1349
|
/** Raised when a database copy fails SQLite's integrity check: the snapshot is not published. */
|
|
@@ -970,9 +1408,6 @@ export function isUpgradeRuntimeFile(dir, relativePath) {
|
|
|
970
1408
|
* and shared-memory files belong to it (never archived on their own).
|
|
971
1409
|
*/
|
|
972
1410
|
function collectUpgradeInputs({ dataHome, additionalEntries = [], softLimitBytes = UPGRADE_SNAPSHOT_SOFT_LIMIT_BYTES }) {
|
|
973
|
-
const files = [];
|
|
974
|
-
const envPath = resolve(dataHome, '.env');
|
|
975
|
-
if (existsSync(envPath)) files.push({ diskPath: envPath, archivePath: 'env.bak' });
|
|
976
1411
|
const dataDirFilters = {
|
|
977
1412
|
data: rel => !shouldSkipDataPath(rel) && !isUpgradeRuntimeFile('data', rel),
|
|
978
1413
|
'mcp-data': rel => !shouldSkipDataPath(rel)
|
|
@@ -980,17 +1415,31 @@ function collectUpgradeInputs({ dataHome, additionalEntries = [], softLimitBytes
|
|
|
980
1415
|
&& !isDatabaseCopyArtifact(rel)
|
|
981
1416
|
&& !/^memory\.db(?:-wal|-shm|-journal)?$/i.test(rel),
|
|
982
1417
|
};
|
|
983
|
-
|
|
984
|
-
files.push(...normalizeAdditionalEntries(additionalEntries));
|
|
985
|
-
const deduped = [...new Map(files.map(file => [file.archivePath.replace(/\\/g, '/'), file])).values()];
|
|
1418
|
+
const deduped = collectBackupFiles(dataHome, dataDirFilters, additionalEntries);
|
|
986
1419
|
const { files: kept, excluded } = selectUpgradeSnapshotFiles(deduped, { softLimitBytes });
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
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) => {
|
|
990
1430
|
const lower = archivePath.toLowerCase();
|
|
991
|
-
|
|
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;
|
|
992
1433
|
};
|
|
993
|
-
|
|
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 };
|
|
994
1443
|
}
|
|
995
1444
|
|
|
996
1445
|
/** Where an input is, as the manifest records it: relative to the data home (forward slashes), absolute outside it. */
|
|
@@ -1011,6 +1460,19 @@ export async function checkUpgradeSnapshotFreshness({
|
|
|
1011
1460
|
} = {}) {
|
|
1012
1461
|
const recorded = manifest?.inputs?.entries;
|
|
1013
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
|
+
};
|
|
1014
1476
|
const current = new Map(collectUpgradeInputs({ dataHome, softLimitBytes: upgradeSoftLimitBytes }).inputs.map(file => [file.archivePath, file]));
|
|
1015
1477
|
if (existsSync(databasePath)) current.set('database/memory.db', { archivePath: 'database/memory.db', diskPath: databasePath, sqlite: true });
|
|
1016
1478
|
const before = new Map(recorded.filter(item => item && typeof item.entry === 'string').map(item => [item.entry, item]));
|
|
@@ -1033,7 +1495,7 @@ export async function checkUpgradeSnapshotFreshness({
|
|
|
1033
1495
|
}
|
|
1034
1496
|
let actual = null;
|
|
1035
1497
|
try { actual = `sha256:${await hashFile(file.diskPath)}`; } catch { /* gone or unreadable: changed */ }
|
|
1036
|
-
if (actual
|
|
1498
|
+
if (!sameContent(entry, actual) && differs(entry, path, 'changed')) break scan;
|
|
1037
1499
|
}
|
|
1038
1500
|
}
|
|
1039
1501
|
return changed.length
|
|
@@ -1064,8 +1526,10 @@ export async function checkUpgradeSnapshotFreshness({
|
|
|
1064
1526
|
* restore-backup` restore it as they restore any backup.
|
|
1065
1527
|
*
|
|
1066
1528
|
* onProgress({ phase: 'collect' | 'copy' | 'archive' | 'verify' | 'integrity', ... }): collect says how much (files,
|
|
1067
|
-
* bytes, skipped
|
|
1068
|
-
* 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').
|
|
1069
1533
|
*/
|
|
1070
1534
|
export async function createUpgradeSnapshot({
|
|
1071
1535
|
dataHome,
|
|
@@ -1082,28 +1546,37 @@ export async function createUpgradeSnapshot({
|
|
|
1082
1546
|
upgradeSoftLimitBytes = UPGRADE_SNAPSHOT_SOFT_LIMIT_BYTES,
|
|
1083
1547
|
copyDatabase = copySqliteDatabase,
|
|
1084
1548
|
checkIntegrity = checkSqliteIntegrity,
|
|
1549
|
+
// As for createVerifiedBackup: left out, the snapshot is encrypted when the owner turned encryption on.
|
|
1550
|
+
encryption = undefined,
|
|
1085
1551
|
now = () => new Date(),
|
|
1086
1552
|
} = {}) {
|
|
1087
|
-
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 */ } };
|
|
1088
1554
|
if (!dataHome || !folderPath) throw new Error('dataHome and folderPath are required');
|
|
1089
1555
|
if (!UPGRADE_BACKUP_KINDS.has(kind)) throw new Error(`An upgrade snapshot is ${[...UPGRADE_BACKUP_KINDS].join(' or ')}, not ${kind}`);
|
|
1090
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);
|
|
1091
1559
|
const createdAt = now();
|
|
1092
1560
|
assertBackupDestinationMounted(folderPath);
|
|
1093
1561
|
mkdirSync(folderPath, { recursive: true });
|
|
1094
1562
|
cleanupStaleBackupArtifacts(folderPath);
|
|
1095
|
-
const destination = resolve(folderPath, archiveNameFor(kind, createdAt));
|
|
1563
|
+
const destination = resolve(folderPath, archiveNameFor(kind, createdAt, !!encrypt));
|
|
1096
1564
|
if (existsSync(destination)) throw new Error(`Backup already exists: ${destination}`);
|
|
1097
1565
|
const tempPath = `${destination}.${process.pid}.tmp`;
|
|
1098
|
-
|
|
1099
|
-
|
|
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;
|
|
1100
1572
|
const timings = {};
|
|
1101
1573
|
const mark = (name, since) => { timings[name] = Date.now() - since; };
|
|
1102
1574
|
// The integrity check of the database copies, once they exist: { results, ms } or { error, ms }, never a rejection.
|
|
1103
1575
|
let integrity = null;
|
|
1576
|
+
let workerTimedOut = false;
|
|
1104
1577
|
try {
|
|
1105
1578
|
let since = Date.now();
|
|
1106
|
-
const { inputs: kept, excluded } = collectUpgradeInputs({ dataHome, additionalEntries, softLimitBytes: upgradeSoftLimitBytes });
|
|
1579
|
+
const { inputs: kept, excluded, skippedEmpty } = collectUpgradeInputs({ dataHome, additionalEntries, softLimitBytes: upgradeSoftLimitBytes });
|
|
1107
1580
|
const databaseBytes = existsSync(databasePath) ? statSync(databasePath).size : 0;
|
|
1108
1581
|
const walBytes = existsSync(`${databasePath}-wal`) ? statSync(`${databasePath}-wal`).size : 0;
|
|
1109
1582
|
const keptBytes = kept.reduce((sum, file) => sum + backupFileSize(file), 0);
|
|
@@ -1114,6 +1587,8 @@ export async function createUpgradeSnapshot({
|
|
|
1114
1587
|
skippedFiles: excluded?.files ?? 0,
|
|
1115
1588
|
skippedBytes: excluded?.bytes ?? 0,
|
|
1116
1589
|
skippedReason: excluded?.reason ?? null,
|
|
1590
|
+
skippedEmptyDatabases: skippedEmpty.databases,
|
|
1591
|
+
skippedEmptyDatabaseFiles: skippedEmpty.files,
|
|
1117
1592
|
});
|
|
1118
1593
|
|
|
1119
1594
|
// Room for it: the archive holds everything once; a database that cannot be cloned is copied first.
|
|
@@ -1166,6 +1641,7 @@ export async function createUpgradeSnapshot({
|
|
|
1166
1641
|
if (error?.code === 'ENOENT') continue;
|
|
1167
1642
|
throw error;
|
|
1168
1643
|
}
|
|
1644
|
+
if (encrypt && process.platform !== 'win32') chmodSync(staged, 0o600);
|
|
1169
1645
|
entries.push({ diskPath: staged, archivePath: file.archivePath, store });
|
|
1170
1646
|
recorded.push({ entry: file.archivePath, path: inputPath(dataHome, file.diskPath) });
|
|
1171
1647
|
}
|
|
@@ -1214,10 +1690,12 @@ export async function createUpgradeSnapshot({
|
|
|
1214
1690
|
verification: { algorithm: 'sha256', publication: 'verify-before-atomic-rename', writer: 'one-pass', integrity: 'integrity_check' },
|
|
1215
1691
|
}, null, 2);
|
|
1216
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 });
|
|
1217
1695
|
await writeZipArchive(tempPath, [
|
|
1218
1696
|
...entries.map(entry => ({ name: `${BACKUP_PREFIX}/${entry.archivePath}`, diskPath: entry.diskPath, store: entry.store })),
|
|
1219
1697
|
{ name: `${BACKUP_PREFIX}/manifest.json`, data: manifestFor },
|
|
1220
|
-
], { 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) }) });
|
|
1221
1699
|
mark('archive', since);
|
|
1222
1700
|
|
|
1223
1701
|
since = Date.now();
|
|
@@ -1225,6 +1703,8 @@ export async function createUpgradeSnapshot({
|
|
|
1225
1703
|
let reportedAt = 0;
|
|
1226
1704
|
report({ phase: 'verify', done: 0, total });
|
|
1227
1705
|
const publishedManifest = await verifyBackupArchive(tempPath, {
|
|
1706
|
+
fileKey: writer ? writer.fileKey : null,
|
|
1707
|
+
authKey: writer ? writer.authKey : null,
|
|
1228
1708
|
onBytes: (bytes) => {
|
|
1229
1709
|
checked += bytes;
|
|
1230
1710
|
if (checked - reportedAt >= 64 * 1024 * 1024 || checked >= total) { reportedAt = checked; report({ phase: 'verify', done: checked, total }); }
|
|
@@ -1238,6 +1718,7 @@ export async function createUpgradeSnapshot({
|
|
|
1238
1718
|
timings.integrity = verdict.ms;
|
|
1239
1719
|
mark('integrityWait', since);
|
|
1240
1720
|
if (verdict.error) {
|
|
1721
|
+
if (verdict.error.code === 'BACKUP_WORKER_TIMEOUT') throw verdict.error;
|
|
1241
1722
|
throw Object.assign(new Error(`SQLite's integrity check of the copies could not run: ${verdict.error?.message || verdict.error}`), { code: 'EINTEGRITY' });
|
|
1242
1723
|
}
|
|
1243
1724
|
for (const [index, result] of copies.entries()) {
|
|
@@ -1247,7 +1728,12 @@ export async function createUpgradeSnapshot({
|
|
|
1247
1728
|
report({ phase: 'integrity', state: 'ok' });
|
|
1248
1729
|
// The copies are in the archive and checked: their room goes back.
|
|
1249
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);
|
|
1250
1735
|
renameSync(tempPath, destination);
|
|
1736
|
+
if (withInfo) renameSync(tempInfoPath, backupInfoPath(destination));
|
|
1251
1737
|
return {
|
|
1252
1738
|
path: destination,
|
|
1253
1739
|
name: basename(destination),
|
|
@@ -1255,25 +1741,36 @@ export async function createUpgradeSnapshot({
|
|
|
1255
1741
|
createdAt: createdAt.toISOString(),
|
|
1256
1742
|
sizeBytes: statSync(destination).size,
|
|
1257
1743
|
manifest: publishedManifest,
|
|
1744
|
+
encrypted: !!encrypt,
|
|
1258
1745
|
stamp: backupFileStamp(destination),
|
|
1259
1746
|
database: database ? { method: database.method, sizeBytes: database.sizeBytes, memoryCount: database.memoryCount, integrity: 'ok' } : null,
|
|
1260
1747
|
timings: { ...timings, total: Date.now() - started },
|
|
1261
1748
|
};
|
|
1262
1749
|
} catch (error) {
|
|
1263
|
-
|
|
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 {} }
|
|
1264
1759
|
throw error;
|
|
1265
1760
|
} finally {
|
|
1266
|
-
|
|
1761
|
+
if (writer) writer.wipe();
|
|
1762
|
+
// Cancel a check still reading the copies before cleanup; a native I/O timeout also retries on exit.
|
|
1267
1763
|
if (integrity) {
|
|
1268
1764
|
integrity.cancel();
|
|
1269
1765
|
await integrity;
|
|
1270
1766
|
}
|
|
1271
|
-
|
|
1767
|
+
if (workerTimedOut) await waitForBackupCleanup(rm(work, { recursive: true, force: true }).catch(() => {}), true);
|
|
1768
|
+
else { try { rmSync(work, { recursive: true, force: true }); } catch {} }
|
|
1272
1769
|
}
|
|
1273
1770
|
}
|
|
1274
1771
|
|
|
1275
1772
|
function dateFromSnapshotName(name, stat) {
|
|
1276
|
-
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);
|
|
1277
1774
|
if (!match) return stat.mtime;
|
|
1278
1775
|
const iso = match[1].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, 'T$1:$2:$3.$4Z');
|
|
1279
1776
|
const value = new Date(iso);
|
|
@@ -1285,25 +1782,34 @@ function kindFromName(name) {
|
|
|
1285
1782
|
return match?.[1]?.toLowerCase() || (name === 'synabun-auto-backup.zip' ? 'legacy' : 'unknown');
|
|
1286
1783
|
}
|
|
1287
1784
|
|
|
1288
|
-
export function listBackupSnapshots(folderPath) {
|
|
1289
|
-
if (!folderPath
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
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);
|
|
1307
1813
|
}
|
|
1308
1814
|
|
|
1309
1815
|
function utcDay(dateMs) {
|
|
@@ -1317,15 +1823,15 @@ function utcWeek(dateMs) {
|
|
|
1317
1823
|
return date.toISOString().slice(0, 10);
|
|
1318
1824
|
}
|
|
1319
1825
|
|
|
1320
|
-
export function applyBackupRetention({
|
|
1826
|
+
export async function applyBackupRetention({
|
|
1321
1827
|
folderPath,
|
|
1322
1828
|
retention = DEFAULT_BACKUP_RETENTION,
|
|
1323
1829
|
incomingBytes = 0,
|
|
1324
1830
|
now = () => new Date(),
|
|
1325
|
-
remove = path =>
|
|
1831
|
+
remove = path => removeBackupFile(path),
|
|
1326
1832
|
} = {}) {
|
|
1327
1833
|
const policy = { ...DEFAULT_BACKUP_RETENTION, ...(retention || {}) };
|
|
1328
|
-
const snapshots = listBackupSnapshots(folderPath);
|
|
1834
|
+
const snapshots = await listBackupSnapshots(folderPath);
|
|
1329
1835
|
const currentMs = now().getTime();
|
|
1330
1836
|
const recentCutoff = currentMs - policy.recentHours * 60 * 60 * 1000;
|
|
1331
1837
|
const dailyCutoff = currentMs - policy.dailyDays * 24 * 60 * 60 * 1000;
|
|
@@ -1361,11 +1867,11 @@ export function applyBackupRetention({
|
|
|
1361
1867
|
const removed = [];
|
|
1362
1868
|
for (const item of snapshots) {
|
|
1363
1869
|
if (keep.has(item.path) || item.kind === 'manual' || item.kind === 'unknown') continue;
|
|
1364
|
-
remove(item.path);
|
|
1870
|
+
await remove(item.path);
|
|
1365
1871
|
removed.push(item.path);
|
|
1366
1872
|
}
|
|
1367
1873
|
|
|
1368
|
-
let retained = listBackupSnapshots(folderPath);
|
|
1874
|
+
let retained = await listBackupSnapshots(folderPath);
|
|
1369
1875
|
let totalBytes = retained.reduce((sum, item) => sum + item.sizeBytes, 0);
|
|
1370
1876
|
const normalizedIncomingBytes = Math.max(0, Number(incomingBytes) || 0);
|
|
1371
1877
|
const targetBytes = Math.max(0, policy.maxBytes - normalizedIncomingBytes);
|
|
@@ -1375,11 +1881,11 @@ export function applyBackupRetention({
|
|
|
1375
1881
|
.sort((a, b) => a.createdMs - b.createdMs);
|
|
1376
1882
|
for (const item of removable) {
|
|
1377
1883
|
if (totalBytes <= targetBytes) break;
|
|
1378
|
-
remove(item.path);
|
|
1884
|
+
await remove(item.path);
|
|
1379
1885
|
removed.push(item.path);
|
|
1380
1886
|
totalBytes -= item.sizeBytes;
|
|
1381
1887
|
}
|
|
1382
|
-
retained = listBackupSnapshots(folderPath);
|
|
1888
|
+
retained = await listBackupSnapshots(folderPath);
|
|
1383
1889
|
}
|
|
1384
1890
|
return {
|
|
1385
1891
|
retention: policy,
|
|
@@ -1486,3 +1992,11 @@ export function saveBackupConfig(path, value) {
|
|
|
1486
1992
|
}
|
|
1487
1993
|
return config;
|
|
1488
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
|
+
}
|