synabun 2.4.1 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +1 -1
- package/browser-extension/content.js +56 -14
- package/browser-extension/engine.js +158 -8
- package/browser-extension/manifest.json +3 -1
- package/browser-extension/protocol.js +91 -6
- package/browser-extension/service-worker.js +13 -5
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +24 -4
- package/lib/data-home-files.js +4 -2
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +5 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +11 -7
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +27 -9
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +22 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +26 -9
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +263 -1
- package/neural-interface/i18n/pt-BR.json +264 -2
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +257 -95
- package/neural-interface/lib/assistant-persona.js +16 -4
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +131 -47
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +39 -33
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +788 -233
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +89 -13
- package/neural-interface/lib/browser-extension-bridge.js +18 -7
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +28 -7
- package/neural-interface/lib/opencode-build-preflight.js +18 -1
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +31 -43
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +194 -95
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +233 -24
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +1 -1
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +105 -38
- package/neural-interface/public/shared/assistant/asst-route.js +100 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -52
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +341 -437
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +124 -17
- package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +224 -65
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +5 -1
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +477 -139
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// DOWNLOAD BACKUP — into a folder the owner chose
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// Settings → Backups → Download full backup. The server builds the verified archive (createVerifiedBackup of
|
|
6
|
+
// backup-service.js: staged, checksummed, read back, then renamed into place) directly in a folder of this
|
|
7
|
+
// computer, instead of sending a multi-GB response a browser tab had to hold in memory before it could save it.
|
|
8
|
+
//
|
|
9
|
+
// defaultBackupDownloadFolder(homeDir) ~/Downloads, resolved here, never by the page
|
|
10
|
+
// validateBackupDownloadFolder(path, { … }) the folder as it will be used, or a BackupDestinationError
|
|
11
|
+
// createBackupDownloadService({ … }) the remembered folder and the one job
|
|
12
|
+
// backupDownloadHandlers(service, { revealer }) the four route handlers server.js registers
|
|
13
|
+
//
|
|
14
|
+
// One job at a time, and it runs apart from the request that started it: the page starts it, then asks for its
|
|
15
|
+
// state (GET /api/system/backup/job). The job goes through the caller's `serialize` (server.js
|
|
16
|
+
// serializeBackupOperation), so it never overlaps a scheduled backup; while it waits for one it says `queued`.
|
|
17
|
+
// The folder is remembered in DATA_HOME/data/backup-download.json ({ folderPath }); without one it is ~/Downloads.
|
|
18
|
+
// Nothing here takes a path to open or reveal from a request: reveal shows the last finished backup (or the
|
|
19
|
+
// folder), both known to the server.
|
|
20
|
+
|
|
21
|
+
import { accessSync, constants as FS_CONSTANTS, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
22
|
+
import { randomUUID } from 'node:crypto';
|
|
23
|
+
import os from 'node:os';
|
|
24
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
25
|
+
|
|
26
|
+
/** A folder that cannot take the backup. `code` names why; `status` is the HTTP answer (400). */
|
|
27
|
+
export class BackupDestinationError extends Error {
|
|
28
|
+
constructor(code, message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = 'BackupDestinationError';
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.status = 400;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function defaultBackupDownloadFolder(homeDir = os.homedir()) {
|
|
37
|
+
return resolve(homeDir, 'Downloads');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The folder a path really is (links followed, the file system's own spelling), or the path when it cannot be asked.
|
|
41
|
+
function realFolder(path) {
|
|
42
|
+
try { return realpathSync.native(path); }
|
|
43
|
+
catch { return resolve(path); }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isInside(path, root) {
|
|
47
|
+
const rel = relative(root, path);
|
|
48
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The folder a backup can be written into, as an absolute path. Refused (BackupDestinationError): no path, a
|
|
53
|
+
* relative one, a folder that is not there, a file, a folder this process cannot write in, a folder the backup
|
|
54
|
+
* itself copies from (`sourceRoots`: the archive and its working files would be read into this backup and every
|
|
55
|
+
* later one), and anything inside the data home but its `backups` folder (SynaBun's live folders; the two
|
|
56
|
+
* `*-staging` folders there belong to the browser download and to restore).
|
|
57
|
+
* @param {string} folderPath
|
|
58
|
+
* @param {{ sourceRoots?: string[], dataHome?: string | null }} [o]
|
|
59
|
+
*/
|
|
60
|
+
export function validateBackupDownloadFolder(folderPath, { sourceRoots = [], dataHome = null } = {}) {
|
|
61
|
+
if (typeof folderPath !== 'string' || !folderPath.trim()) throw new BackupDestinationError('FOLDER_REQUIRED', 'Choose a folder for the backup.');
|
|
62
|
+
const asked = folderPath.trim();
|
|
63
|
+
if (asked.includes('\0') || !isAbsolute(asked)) throw new BackupDestinationError('FOLDER_NOT_ABSOLUTE', `The backup folder must be a full path: ${asked.replace(/\0/g, '')}`);
|
|
64
|
+
const target = resolve(asked);
|
|
65
|
+
let stats;
|
|
66
|
+
try { stats = statSync(target); }
|
|
67
|
+
catch { throw new BackupDestinationError('FOLDER_MISSING', `The backup folder does not exist: ${target}`); }
|
|
68
|
+
if (!stats.isDirectory()) throw new BackupDestinationError('FOLDER_NOT_DIRECTORY', `Not a folder: ${target}`);
|
|
69
|
+
try { accessSync(target, FS_CONSTANTS.W_OK | FS_CONSTANTS.X_OK); }
|
|
70
|
+
catch { throw new BackupDestinationError('FOLDER_NOT_WRITABLE', `SynaBun cannot write in ${target}. Choose another folder.`); }
|
|
71
|
+
const actual = realFolder(target);
|
|
72
|
+
for (const root of sourceRoots) {
|
|
73
|
+
if (root && isInside(actual, realFolder(root))) {
|
|
74
|
+
throw new BackupDestinationError('FOLDER_IS_BACKUP_SOURCE', `${target} is inside a folder the backup copies (${resolve(root)}). Choose a folder outside it.`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (dataHome) {
|
|
78
|
+
const home = realFolder(dataHome);
|
|
79
|
+
if (isInside(actual, home)) {
|
|
80
|
+
const [first, second] = relative(home, actual).split(sep);
|
|
81
|
+
if (first !== 'backups' || /-staging$/.test(second || '')) {
|
|
82
|
+
throw new BackupDestinationError('FOLDER_IN_DATA_HOME', `${target} is one of SynaBun's own data folders. Choose a folder outside ${resolve(dataHome)}.`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return target;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The remembered folder and the one download-backup job.
|
|
91
|
+
*
|
|
92
|
+
* @param {object} o
|
|
93
|
+
* @param {string} o.configPath where the folder is remembered ({ folderPath })
|
|
94
|
+
* @param {(job: { folderPath: string, onProgress: (event: object) => void, signal: AbortSignal }) => Promise<{ path: string, name: string, sizeBytes: number, manifest?: object }>} o.createBackup
|
|
95
|
+
* builds the verified archive in `folderPath` (createVerifiedBackup, kind `manual`); `signal` aborts it
|
|
96
|
+
* @param {(operation: () => Promise<any>) => Promise<any>} [o.serialize] one backup at a time (serializeBackupOperation)
|
|
97
|
+
* @param {() => boolean} [o.isBusy] another backup is being made right now
|
|
98
|
+
* @param {() => string[]} [o.sourceRoots] the folders a backup copies from
|
|
99
|
+
* @param {string | null} [o.dataHome]
|
|
100
|
+
* @param {() => string} [o.homeDir]
|
|
101
|
+
* @param {() => Date} [o.now]
|
|
102
|
+
* @param {(line: string) => void} [o.log]
|
|
103
|
+
*/
|
|
104
|
+
export function createBackupDownloadService({
|
|
105
|
+
configPath, createBackup, serialize = (operation) => operation(), isBusy = () => false,
|
|
106
|
+
sourceRoots = () => [], dataHome = null, homeDir = () => os.homedir(), now = () => new Date(), log = () => {},
|
|
107
|
+
} = {}) {
|
|
108
|
+
if (!configPath || typeof createBackup !== 'function') throw new Error('configPath and createBackup are required');
|
|
109
|
+
let job = null;
|
|
110
|
+
|
|
111
|
+
const validate = (folderPath) => validateBackupDownloadFolder(folderPath, { sourceRoots: sourceRoots(), dataHome });
|
|
112
|
+
|
|
113
|
+
function savedFolder() {
|
|
114
|
+
try {
|
|
115
|
+
const value = JSON.parse(readFileSync(configPath, 'utf-8'))?.folderPath;
|
|
116
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
117
|
+
} catch { return null; }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Where the next backup goes: the remembered folder, else ~/Downloads (made by the first backup when missing). */
|
|
121
|
+
function destination() {
|
|
122
|
+
const saved = savedFolder();
|
|
123
|
+
const folderPath = saved || defaultBackupDownloadFolder(homeDir());
|
|
124
|
+
let error = null;
|
|
125
|
+
if (saved || existsSync(folderPath)) {
|
|
126
|
+
try { validate(folderPath); } catch (cause) { error = cause.message; }
|
|
127
|
+
}
|
|
128
|
+
return { folderPath, isDefault: !saved, error };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function setDestination(folderPath) {
|
|
132
|
+
const target = validate(folderPath);
|
|
133
|
+
mkdirSync(dirname(configPath), { recursive: true });
|
|
134
|
+
const temp = `${configPath}.${process.pid}.tmp`;
|
|
135
|
+
try {
|
|
136
|
+
writeFileSync(temp, JSON.stringify({ folderPath: target }, null, 2) + '\n', 'utf-8');
|
|
137
|
+
renameSync(temp, configPath);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
try { if (existsSync(temp)) unlinkSync(temp); } catch { /* nothing to remove */ }
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
return destination();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// createVerifiedBackup reports a phase as it begins, except `collect`, which it reports once the files are known.
|
|
146
|
+
function note(current, event) {
|
|
147
|
+
if (!event || typeof event !== 'object') return;
|
|
148
|
+
if (Number.isFinite(event.files)) current.files = event.files;
|
|
149
|
+
if (Number.isFinite(event.bytes)) current.bytes = event.bytes;
|
|
150
|
+
if (typeof event.tempPath === 'string') current.tempPath = event.tempPath;
|
|
151
|
+
current.phase = event.phase === 'collect' ? 'copy' : event.phase;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function view(current) {
|
|
155
|
+
let writtenBytes = null;
|
|
156
|
+
if (current.state === 'running' && current.tempPath) {
|
|
157
|
+
try { writtenBytes = statSync(current.tempPath).size; } catch { writtenBytes = null; }
|
|
158
|
+
}
|
|
159
|
+
const { id, state, phase, folderPath, startedAt, finishedAt, files, bytes, path, name, sizeBytes, error, groups, cancelling, encrypted } = current;
|
|
160
|
+
return { id, state, phase, folderPath, startedAt, finishedAt, files, bytes, writtenBytes, path, name, sizeBytes, error, groups, cancelling, encrypted };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Starts the backup and returns at once. A second one while it runs is refused: BACKUP_RUNNING (409). */
|
|
164
|
+
function start() {
|
|
165
|
+
if (job?.state === 'running') throw Object.assign(new Error('A backup is already running.'), { code: 'BACKUP_RUNNING', status: 409 });
|
|
166
|
+
const chosen = destination();
|
|
167
|
+
if (chosen.isDefault && !existsSync(chosen.folderPath)) mkdirSync(chosen.folderPath, { recursive: true });
|
|
168
|
+
const folderPath = validate(chosen.folderPath);
|
|
169
|
+
const current = {
|
|
170
|
+
id: randomUUID(), state: 'running', phase: isBusy() ? 'queued' : 'collect', folderPath,
|
|
171
|
+
startedAt: now().toISOString(), finishedAt: null, files: null, bytes: null, tempPath: null,
|
|
172
|
+
path: null, name: null, sizeBytes: null, error: null, finished: null,
|
|
173
|
+
// The groups the finished archive holds (its manifest's own word), and whether a cancel was asked for.
|
|
174
|
+
// `encrypted`: whether the finished archive is password-protected (null until it is finished).
|
|
175
|
+
groups: null, cancelling: false, encrypted: null, abort: new AbortController(),
|
|
176
|
+
};
|
|
177
|
+
job = current;
|
|
178
|
+
current.finished = Promise.resolve()
|
|
179
|
+
.then(() => serialize(() => {
|
|
180
|
+
// Cancelled while it waited for another backup: it never starts.
|
|
181
|
+
if (current.abort.signal.aborted) throw Object.assign(new Error('The backup was cancelled.'), { code: 'BACKUP_CANCELLED' });
|
|
182
|
+
current.phase = 'collect';
|
|
183
|
+
return createBackup({ folderPath, onProgress: (event) => note(current, event), signal: current.abort.signal });
|
|
184
|
+
}))
|
|
185
|
+
.then((backup) => {
|
|
186
|
+
const groups = backup.manifest?.groups;
|
|
187
|
+
Object.assign(current, {
|
|
188
|
+
state: 'done', path: backup.path, name: backup.name, sizeBytes: backup.sizeBytes, encrypted: backup.encrypted === true,
|
|
189
|
+
groups: groups && Array.isArray(groups.included) ? { included: [...groups.included], excluded: Array.isArray(groups.excluded) ? [...groups.excluded] : [] } : null,
|
|
190
|
+
});
|
|
191
|
+
log(`[backup] Download backup: ${backup.path} (${(backup.sizeBytes / 1024 / 1024).toFixed(1)} MB${backup.encrypted ? ', encrypted' : ''})`);
|
|
192
|
+
}, (error) => {
|
|
193
|
+
if (error?.code === 'BACKUP_CANCELLED' || current.abort.signal.aborted) {
|
|
194
|
+
Object.assign(current, { state: 'cancelled', error: null });
|
|
195
|
+
log('[backup] Download backup cancelled: nothing was saved');
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
Object.assign(current, { state: 'failed', error: error?.message || String(error) });
|
|
199
|
+
log(`[backup] Download backup failed: ${current.error}`);
|
|
200
|
+
})
|
|
201
|
+
.finally(() => { Object.assign(current, { phase: null, tempPath: null, cancelling: false, finishedAt: now().toISOString() }); });
|
|
202
|
+
return view(current);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Stop the running backup. It ends at its next step: nothing is saved, and the archive under way and the staged
|
|
207
|
+
* copies are removed (createVerifiedBackup's own cleanup). NOTHING_RUNNING (409) when there is none.
|
|
208
|
+
*/
|
|
209
|
+
function cancel() {
|
|
210
|
+
if (job?.state !== 'running') throw Object.assign(new Error('No backup is running.'), { code: 'NOTHING_RUNNING', status: 409 });
|
|
211
|
+
job.cancelling = true;
|
|
212
|
+
job.abort.abort();
|
|
213
|
+
return view(job);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** What reveal shows: the last backup this server finished, while it is still there; else the folder. */
|
|
217
|
+
function revealTarget() {
|
|
218
|
+
if (job?.state === 'done' && job.path && existsSync(job.path)) return job.path;
|
|
219
|
+
const { folderPath } = destination();
|
|
220
|
+
return existsSync(folderPath) ? folderPath : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
destination, setDestination, start, cancel, revealTarget,
|
|
225
|
+
snapshot: () => ({ ok: true, destination: destination(), job: job ? view(job) : null, busy: !!isBusy() }),
|
|
226
|
+
/** Settles when the running job ended (tests, shutdown). */
|
|
227
|
+
idle: () => (job?.finished || Promise.resolve()),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The route handlers: GET job (the state), PUT destination ({ folderPath }), POST job (start; 202, or 409 with the
|
|
233
|
+
* state while one runs), POST job/cancel (202; 409 when none runs), POST reveal (no path in the request). Every answer but a refusal is the service's snapshot.
|
|
234
|
+
* @param {ReturnType<typeof createBackupDownloadService>} service
|
|
235
|
+
* @param {{ revealer?: { available: () => boolean, reveal: (path: string) => Promise<boolean> } | null }} [o]
|
|
236
|
+
*/
|
|
237
|
+
export function backupDownloadHandlers(service, { revealer = null } = {}) {
|
|
238
|
+
const canReveal = () => { try { return !!revealer?.available?.(); } catch { return false; } };
|
|
239
|
+
const state = () => ({ ...service.snapshot(), canReveal: canReveal() });
|
|
240
|
+
const refuse = (res, error) => {
|
|
241
|
+
const status = Number(error?.status) || 500;
|
|
242
|
+
let rest = {};
|
|
243
|
+
if (error?.code === 'BACKUP_RUNNING') { try { rest = state(); } catch { rest = {}; } }
|
|
244
|
+
return res.status(status).json({ ...rest, ok: false, error: error?.message || String(error), code: error?.code || null });
|
|
245
|
+
};
|
|
246
|
+
return {
|
|
247
|
+
status(req, res) {
|
|
248
|
+
try { res.json(state()); } catch (error) { refuse(res, error); }
|
|
249
|
+
},
|
|
250
|
+
setDestination(req, res) {
|
|
251
|
+
try { service.setDestination(req.body?.folderPath); res.json(state()); } catch (error) { refuse(res, error); }
|
|
252
|
+
},
|
|
253
|
+
start(req, res) {
|
|
254
|
+
try { service.start(); res.status(202).json(state()); } catch (error) { refuse(res, error); }
|
|
255
|
+
},
|
|
256
|
+
cancel(req, res) {
|
|
257
|
+
try { service.cancel(); res.status(202).json(state()); } catch (error) { refuse(res, error); }
|
|
258
|
+
},
|
|
259
|
+
async reveal(req, res) {
|
|
260
|
+
try {
|
|
261
|
+
const target = service.revealTarget();
|
|
262
|
+
if (!target) return res.status(404).json({ ok: false, code: 'NOTHING_TO_SHOW', error: 'The backup folder is not there any more.' });
|
|
263
|
+
if (!canReveal() || !(await revealer.reveal(target))) return res.status(501).json({ ok: false, code: 'NO_REVEAL', error: 'This system has no file manager to show it in.' });
|
|
264
|
+
res.json({ ok: true, path: target });
|
|
265
|
+
} catch (error) { refuse(res, error); }
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// BACKUP ENCRYPTION — the owner's key and the password routes
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// Settings → Memory & backups → Backups → Password protection (docs/backup-encryption.md). Off until the owner sets
|
|
6
|
+
// a password. While it is on, every backup SynaBun makes (on request, on schedule, before an update) is written
|
|
7
|
+
// encrypted, or not at all: backup-service.js asks backupRecipientFor(dataHome) itself, so no caller can forget to.
|
|
8
|
+
//
|
|
9
|
+
// What is kept: DATA_HOME/data/backup-encryption.json, mode 0600, { version, recipient, createdAt, changedAt }. The
|
|
10
|
+
// recipient is a public key, the private key wrapped by the password, and the authentication key that proves a backup
|
|
11
|
+
// was made here (backup-crypto.js); the password and the unwrapped private key are never written anywhere. A scheduled
|
|
12
|
+
// backup needs the public and authentication keys only. The file is in no backup and no restore writes it
|
|
13
|
+
// (backup-groups.js isBackupEncryptionFile): a restored backup must not bring back an older password.
|
|
14
|
+
//
|
|
15
|
+
// backupRecipientFor(dataHome) null when encryption is off; the recipient when it is on; a
|
|
16
|
+
// BackupEncryptionError when the file is there and cannot be used
|
|
17
|
+
// (the backup then fails: it never falls back to plaintext)
|
|
18
|
+
// createPasswordAttemptLimiter() wrong passwords cost time, more each time
|
|
19
|
+
// createBackupEncryptionService({ dataHome }) status, enable, change (the same keys under a new password),
|
|
20
|
+
// disable, adopt
|
|
21
|
+
// backupEncryptionHandlers(service) the four routes server.js registers
|
|
22
|
+
//
|
|
23
|
+
// No function here logs, returns or throws a password, and no error message is built from one.
|
|
24
|
+
|
|
25
|
+
import { randomBytes } from 'node:crypto';
|
|
26
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from 'node:fs';
|
|
27
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
28
|
+
import { authKeyOf, BackupEncryptionError, createRecipient, normalizePassword, readRecipient, rewrapRecipient, unlockRecipient, MIN_PASSWORD_LENGTH } from './backup-crypto.js';
|
|
29
|
+
import { BACKUP_ENCRYPTION_FILE } from './backup-groups.js';
|
|
30
|
+
|
|
31
|
+
export const BACKUP_ENCRYPTION_VERSION = 1;
|
|
32
|
+
/**
|
|
33
|
+
* What this server's backup encryption can do, said in every status answer and in the answer that keeps an encrypted
|
|
34
|
+
* upload. The page works with a server only while `auth-key` is listed: `public/` is read from disk at any time and
|
|
35
|
+
* `lib/` only at a start, so a page can meet a server from before the authentication key, whose backups anybody
|
|
36
|
+
* holding one could forge and whose key file this code cannot use. Such a server answers without the list.
|
|
37
|
+
*/
|
|
38
|
+
export const BACKUP_ENCRYPTION_CAPABILITIES = Object.freeze(['auth-key']);
|
|
39
|
+
|
|
40
|
+
export function backupEncryptionPath(dataHome) {
|
|
41
|
+
return resolve(dataHome, 'data', BACKUP_ENCRYPTION_FILE);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The key file of `dataHome`: null when there is none (encryption is off), else { recipient, keyId, createdAt,
|
|
46
|
+
* changedAt }. A file that is there and cannot be read as one is an error, never "off": BACKUP_ENC_KEY_UNREADABLE.
|
|
47
|
+
*/
|
|
48
|
+
export function readBackupEncryption(dataHome) {
|
|
49
|
+
const path = backupEncryptionPath(dataHome);
|
|
50
|
+
let text;
|
|
51
|
+
try { text = readFileSync(path, 'utf8'); }
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error?.code === 'ENOENT') return null;
|
|
54
|
+
throw new BackupEncryptionError('BACKUP_ENC_KEY_UNREADABLE', `Backup encryption is on, but its key file cannot be read (${error?.code || 'error'}): ${path}`, { status: 500 });
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const stored = JSON.parse(text);
|
|
58
|
+
if (!stored || typeof stored !== 'object' || stored.version !== BACKUP_ENCRYPTION_VERSION) throw new Error('unknown version');
|
|
59
|
+
const read = readRecipient(stored.recipient);
|
|
60
|
+
authKeyOf(stored.recipient).fill(0);
|
|
61
|
+
// A file another program made readable to others is made private again; a failure to do so changes nothing here.
|
|
62
|
+
try { if (process.platform !== 'win32' && (statSync(path).mode & 0o077) !== 0) chmodSync(path, 0o600); } catch { /* read-only volume */ }
|
|
63
|
+
return {
|
|
64
|
+
recipient: stored.recipient,
|
|
65
|
+
keyId: read.keyId,
|
|
66
|
+
createdAt: typeof stored.createdAt === 'string' ? stored.createdAt : null,
|
|
67
|
+
changedAt: typeof stored.changedAt === 'string' ? stored.changedAt : null,
|
|
68
|
+
};
|
|
69
|
+
} catch {
|
|
70
|
+
throw new BackupEncryptionError('BACKUP_ENC_KEY_UNREADABLE', `Backup encryption is on, but its key file is damaged: ${path}. No backup is made until it is repaired or encryption is set up again.`, { status: 500 });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Who a new backup of `dataHome` is encrypted for: null (encryption is off) or the recipient. Throws as readBackupEncryption. */
|
|
75
|
+
export function backupRecipientFor(dataHome) {
|
|
76
|
+
return readBackupEncryption(dataHome)?.recipient ?? null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function writeKeyFile(dataHome, value) {
|
|
80
|
+
const path = backupEncryptionPath(dataHome);
|
|
81
|
+
const folder = dirname(path);
|
|
82
|
+
mkdirSync(folder, { recursive: true });
|
|
83
|
+
// What a crash left of an earlier write: it holds the wrapped keys and must neither stay nor block this one.
|
|
84
|
+
const prefix = `${basename(path)}.`;
|
|
85
|
+
for (const name of readdirSync(folder)) {
|
|
86
|
+
if (name.startsWith(prefix) && name.endsWith('.tmp')) rmSync(resolve(folder, name), { force: true });
|
|
87
|
+
}
|
|
88
|
+
const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
89
|
+
try {
|
|
90
|
+
const fd = openSync(temp, 'wx', 0o600);
|
|
91
|
+
try {
|
|
92
|
+
const bytes = Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
93
|
+
let at = 0;
|
|
94
|
+
while (at < bytes.length) at += writeSync(fd, bytes, at, bytes.length - at);
|
|
95
|
+
fsyncSync(fd);
|
|
96
|
+
} finally { closeSync(fd); }
|
|
97
|
+
if (process.platform !== 'win32') chmodSync(temp, 0o600);
|
|
98
|
+
renameSync(temp, path);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
rmSync(temp, { force: true });
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Wrong passwords cost time. The first `free` in a row are answered at once; each one after that locks every
|
|
107
|
+
* password route for `baseMs`, doubling, up to `maxMs`. A right password clears it. One limiter for the whole
|
|
108
|
+
* server: the settings routes and the restore's unlock share it, so there is one budget of guesses, not one per route.
|
|
109
|
+
*
|
|
110
|
+
* `attempt(operation)` is how a password is tried: one at a time (each costs up to scrypt's memory, and guesses sent
|
|
111
|
+
* together must not all pass the check before the first has failed), at most `maxQueued` waiting. `clears: false` is
|
|
112
|
+
* for a password that opened a file this installation has no reason to trust: anybody can make a file with a password
|
|
113
|
+
* they know, and opening it must not wipe the count of wrong guesses at the owner's own key.
|
|
114
|
+
*/
|
|
115
|
+
export function createPasswordAttemptLimiter({ free = 5, baseMs = 30_000, maxMs = 15 * 60_000, maxQueued = 8, now = () => Date.now() } = {}) {
|
|
116
|
+
let failures = 0;
|
|
117
|
+
let lockedUntil = 0;
|
|
118
|
+
let queued = 0;
|
|
119
|
+
let tail = Promise.resolve();
|
|
120
|
+
const refuse = (seconds) => Object.assign(new BackupEncryptionError('TOO_MANY_ATTEMPTS', `Too many wrong passwords. Try again in ${seconds >= 120 ? `${Math.ceil(seconds / 60)} minutes` : `${seconds} seconds`}.`, { status: 429 }), { retryAfterSeconds: seconds });
|
|
121
|
+
/** Throws TOO_MANY_ATTEMPTS (429, `retryAfterSeconds`) while locked. */
|
|
122
|
+
const check = () => {
|
|
123
|
+
const wait = lockedUntil - now();
|
|
124
|
+
if (wait > 0) throw refuse(Math.ceil(wait / 1000));
|
|
125
|
+
};
|
|
126
|
+
const fail = () => {
|
|
127
|
+
failures += 1;
|
|
128
|
+
if (failures >= free) lockedUntil = now() + Math.min(maxMs, baseMs * 2 ** Math.min(20, failures - free));
|
|
129
|
+
};
|
|
130
|
+
const succeed = () => { failures = 0; lockedUntil = 0; };
|
|
131
|
+
return {
|
|
132
|
+
check,
|
|
133
|
+
fail,
|
|
134
|
+
succeed,
|
|
135
|
+
state: () => ({ failures, lockedUntil }),
|
|
136
|
+
attempt(operation, { clears = true } = {}) {
|
|
137
|
+
if (queued >= maxQueued) return Promise.reject(refuse(5));
|
|
138
|
+
queued += 1;
|
|
139
|
+
const run = tail.then(async () => {
|
|
140
|
+
check();
|
|
141
|
+
try {
|
|
142
|
+
const result = await operation();
|
|
143
|
+
if (clears) succeed();
|
|
144
|
+
return result;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error?.code === 'WRONG_PASSWORD') fail();
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}).finally(() => { queued -= 1; });
|
|
150
|
+
tail = run.then(() => {}, () => {});
|
|
151
|
+
return run;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The owner's backup encryption for one data home.
|
|
158
|
+
*
|
|
159
|
+
* @param {object} o
|
|
160
|
+
* @param {string} o.dataHome
|
|
161
|
+
* @param {ReturnType<typeof createPasswordAttemptLimiter>} [o.limiter]
|
|
162
|
+
* @param {{ N: number, r: number, p: number }} [o.kdf] scrypt for a new key (tests lower it)
|
|
163
|
+
* @param {() => Date} [o.now]
|
|
164
|
+
* @param {(line: string) => void} [o.log] what happened, never what was typed
|
|
165
|
+
*/
|
|
166
|
+
export function createBackupEncryptionService({ dataHome, limiter = createPasswordAttemptLimiter(), kdf = undefined, now = () => new Date(), log = () => {} } = {}) {
|
|
167
|
+
if (!dataHome) throw new Error('dataHome is required');
|
|
168
|
+
// One password operation at a time: each derives a key with scrypt (128 MiB while it runs).
|
|
169
|
+
let tail = Promise.resolve();
|
|
170
|
+
const oneAtATime = (operation) => {
|
|
171
|
+
const run = tail.then(operation, operation);
|
|
172
|
+
tail = run.catch(() => {});
|
|
173
|
+
return run;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// What is wrong with a key file that cannot be used, and which file it is, belongs in the log: Settings says it
|
|
177
|
+
// in the owner's language from `code` and shows neither the sentence nor the path. Written once per sentence, not
|
|
178
|
+
// at every look of an open Settings; `error` stays in the answer for a page from before and for a command line.
|
|
179
|
+
let stoppedLogged = null;
|
|
180
|
+
function status() {
|
|
181
|
+
let stored;
|
|
182
|
+
const base = { ok: true, capabilities: [...BACKUP_ENCRYPTION_CAPABILITIES], minPasswordLength: MIN_PASSWORD_LENGTH };
|
|
183
|
+
try { stored = readBackupEncryption(dataHome); }
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (stoppedLogged !== error.message) {
|
|
186
|
+
stoppedLogged = error.message;
|
|
187
|
+
try { log(`[backup] Backups are stopped (${error.code || 'error'}): ${error.message}`); } catch { /* a log that fails changes no answer */ }
|
|
188
|
+
}
|
|
189
|
+
return { ...base, enabled: true, usable: false, error: error.message, code: error.code };
|
|
190
|
+
}
|
|
191
|
+
stoppedLogged = null;
|
|
192
|
+
if (!stored) return { ...base, enabled: false, usable: true };
|
|
193
|
+
return { ...base, enabled: true, usable: true, keyId: stored.keyId, createdAt: stored.createdAt, changedAt: stored.changedAt };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Resolves when `password` opens the stored key; else the limiter's or the password's refusal. Keeps no key. */
|
|
197
|
+
async function checkStoredPassword(password) {
|
|
198
|
+
limiter.check();
|
|
199
|
+
const stored = readBackupEncryption(dataHome);
|
|
200
|
+
if (!stored) throw new BackupEncryptionError('NOT_ENABLED', 'Backup encryption is not on.', { status: 409 });
|
|
201
|
+
normalizePassword(password).fill(0);
|
|
202
|
+
try {
|
|
203
|
+
const { privateKey, authKey } = await limiter.attempt(() => unlockRecipient(stored.recipient, password));
|
|
204
|
+
privateKey.fill(0);
|
|
205
|
+
authKey.fill(0);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (error?.code === 'WRONG_PASSWORD') throw new BackupEncryptionError('WRONG_PASSWORD', 'That is not the current backup password.', { status: 401 });
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function store(password, createdAt = null) {
|
|
213
|
+
const recipient = await createRecipient(password, kdf ? { kdf } : {});
|
|
214
|
+
const stamp = now().toISOString();
|
|
215
|
+
writeKeyFile(dataHome, { version: BACKUP_ENCRYPTION_VERSION, recipient, createdAt: createdAt || stamp, changedAt: stamp });
|
|
216
|
+
return recipient;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return {
|
|
220
|
+
status,
|
|
221
|
+
limiter,
|
|
222
|
+
/**
|
|
223
|
+
* Turn encryption on with a new key pair. ALREADY_ENABLED (409) when it is on: changing the password is `change`.
|
|
224
|
+
* A key file that cannot be used is replaced: it stops every backup and no password can open it, and nothing is
|
|
225
|
+
* lost with it, because each backup's header carries its own wrapped keys. The result is encrypted either way.
|
|
226
|
+
*/
|
|
227
|
+
enable: (password) => oneAtATime(async () => {
|
|
228
|
+
if (existsSync(backupEncryptionPath(dataHome))) {
|
|
229
|
+
let usable = true;
|
|
230
|
+
try { readBackupEncryption(dataHome); } catch { usable = false; }
|
|
231
|
+
if (usable) throw new BackupEncryptionError('ALREADY_ENABLED', 'Backup encryption is already on. Change the password instead.', { status: 409 });
|
|
232
|
+
}
|
|
233
|
+
const recipient = await store(password);
|
|
234
|
+
log(`[backup] Backup encryption turned on (key ${recipient.keyId})`);
|
|
235
|
+
return status();
|
|
236
|
+
}),
|
|
237
|
+
/**
|
|
238
|
+
* A new password: the same key pair and the same authentication key, wrapped again (backup-crypto.js
|
|
239
|
+
* rewrapRecipient). The keys do not change, so nothing made before is cut off: older backups keep opening with
|
|
240
|
+
* the password of their day, and the record beside an encrypted upgrade snapshot still compares. Whoever knows
|
|
241
|
+
* an old password and holds a backup made under it holds these keys too; new keys are made by turning
|
|
242
|
+
* encryption off and on again.
|
|
243
|
+
*/
|
|
244
|
+
change: (currentPassword, newPassword) => oneAtATime(async () => {
|
|
245
|
+
normalizePassword(newPassword, { forNew: true }).fill(0);
|
|
246
|
+
limiter.check();
|
|
247
|
+
const before = readBackupEncryption(dataHome);
|
|
248
|
+
if (!before) throw new BackupEncryptionError('NOT_ENABLED', 'Backup encryption is not on.', { status: 409 });
|
|
249
|
+
normalizePassword(currentPassword).fill(0);
|
|
250
|
+
let recipient;
|
|
251
|
+
try { recipient = await limiter.attempt(() => rewrapRecipient(before.recipient, currentPassword, newPassword, kdf ? { kdf } : {})); }
|
|
252
|
+
catch (error) {
|
|
253
|
+
if (error?.code === 'WRONG_PASSWORD') throw new BackupEncryptionError('WRONG_PASSWORD', 'That is not the current backup password.', { status: 401 });
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
const stamp = now().toISOString();
|
|
257
|
+
writeKeyFile(dataHome, { version: BACKUP_ENCRYPTION_VERSION, recipient, createdAt: before.createdAt || stamp, changedAt: stamp });
|
|
258
|
+
log(`[backup] Backup password changed (key ${before.keyId}, kept)`);
|
|
259
|
+
return status();
|
|
260
|
+
}),
|
|
261
|
+
/** Turn encryption off: later backups are plain. Earlier ones stay encrypted. */
|
|
262
|
+
disable: (currentPassword) => oneAtATime(async () => {
|
|
263
|
+
await checkStoredPassword(currentPassword);
|
|
264
|
+
rmSync(backupEncryptionPath(dataHome), { force: true });
|
|
265
|
+
log('[backup] Backup encryption turned off');
|
|
266
|
+
return status();
|
|
267
|
+
}),
|
|
268
|
+
/**
|
|
269
|
+
* After a restore of an encrypted backup on an installation that has no key: keep that backup's recipient, so
|
|
270
|
+
* the backups this installation goes on to make are encrypted as the restored ones were (same password). An
|
|
271
|
+
* installation that has a key keeps its own. `recipient` comes from a backup the password opened, with its
|
|
272
|
+
* authentication key (source.recipientForAdoption()). Returns true when the recipient was taken.
|
|
273
|
+
*/
|
|
274
|
+
adopt(recipient) {
|
|
275
|
+
if (existsSync(backupEncryptionPath(dataHome))) return false;
|
|
276
|
+
const read = readRecipient(recipient);
|
|
277
|
+
authKeyOf(recipient).fill(0);
|
|
278
|
+
const stamp = now().toISOString();
|
|
279
|
+
writeKeyFile(dataHome, { version: BACKUP_ENCRYPTION_VERSION, recipient, createdAt: stamp, changedAt: stamp });
|
|
280
|
+
log(`[backup] Backup encryption kept from the restored backup (key ${read.keyId})`);
|
|
281
|
+
return true;
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The route handlers. GET status; POST enable { password, acknowledged: true }; POST change { currentPassword,
|
|
288
|
+
* newPassword }; POST disable { currentPassword }. A password travels in a JSON body only, is used, and is gone:
|
|
289
|
+
* no answer and no log line holds one.
|
|
290
|
+
* @param {ReturnType<typeof createBackupEncryptionService>} service
|
|
291
|
+
*/
|
|
292
|
+
export function backupEncryptionHandlers(service) {
|
|
293
|
+
const refuse = (res, error) => {
|
|
294
|
+
const known = error instanceof BackupEncryptionError;
|
|
295
|
+
const status = known ? error.status : 500;
|
|
296
|
+
if (error?.retryAfterSeconds) res.set('Retry-After', String(error.retryAfterSeconds));
|
|
297
|
+
// An unexpected failure is answered by its code alone: its message could quote a path or an argument.
|
|
298
|
+
return res.status(status).json({ ok: false, code: known ? error.code : 'ENCRYPTION_FAILED', error: known ? error.message : 'Backup encryption could not be changed.', ...(error?.retryAfterSeconds ? { retryAfterSeconds: error.retryAfterSeconds } : {}) });
|
|
299
|
+
};
|
|
300
|
+
const text = (value) => (typeof value === 'string' ? value : '');
|
|
301
|
+
return {
|
|
302
|
+
status(req, res) {
|
|
303
|
+
try { res.json(service.status()); } catch (error) { refuse(res, error); }
|
|
304
|
+
},
|
|
305
|
+
async enable(req, res) {
|
|
306
|
+
try {
|
|
307
|
+
if (req.body?.acknowledged !== true) throw new BackupEncryptionError('ACKNOWLEDGE_REQUIRED', 'Confirm that a lost password cannot be recovered.');
|
|
308
|
+
res.json(await service.enable(text(req.body?.password)));
|
|
309
|
+
} catch (error) { refuse(res, error); }
|
|
310
|
+
},
|
|
311
|
+
async change(req, res) {
|
|
312
|
+
try { res.json(await service.change(text(req.body?.currentPassword), text(req.body?.newPassword))); } catch (error) { refuse(res, error); }
|
|
313
|
+
},
|
|
314
|
+
async disable(req, res) {
|
|
315
|
+
try { res.json(await service.disable(text(req.body?.currentPassword))); } catch (error) { refuse(res, error); }
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
}
|