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
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// BACKUP ENCRYPTION — the container format and its keys
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// An encrypted backup is the backup's ZIP inside one authenticated container (docs/backup-encryption.md is the
|
|
6
|
+
// reference; this file is the code of it). Node's own crypto only.
|
|
7
|
+
//
|
|
8
|
+
// file = prefix(16) || header JSON || header MAC(32) || chunk*
|
|
9
|
+
// prefix = "SYNBKENC" || version(1) || 0x000000 || uint32be(header JSON length)
|
|
10
|
+
// chunk = AES-256-GCM(payloadKey, nonce, plaintext ≤ chunkSize, aad = header MAC) || tag(16)
|
|
11
|
+
// nonce = noncePrefix(7) || uint32be(chunk index) || 0x01 for the last chunk, 0x00 for every other
|
|
12
|
+
//
|
|
13
|
+
// Keys. The owner's password never encrypts a backup. It wraps (scrypt, then AES-256-GCM) the private half of an
|
|
14
|
+
// X25519 key pair together with a random authentication key; a backup gets a random file key that is wrapped to the
|
|
15
|
+
// public half (an ephemeral X25519 key, HKDF, AES-256-GCM), so a backup is made without the password and opened only
|
|
16
|
+
// with it. Each backup's header carries that wrapped block as it was when the backup was made: the file and the
|
|
17
|
+
// password of that day open it anywhere. A new password wraps the same two keys again (rewrapRecipient): the keys
|
|
18
|
+
// themselves change only when encryption is turned off and on.
|
|
19
|
+
//
|
|
20
|
+
// Why the authentication key: a public key lets anybody encrypt. Without a secret the writer holds, whoever has one
|
|
21
|
+
// backup could take its public header and write a new file that the real password opens and every check accepts. The
|
|
22
|
+
// header MAC is therefore keyed by the authentication key too. It sits in the data home's 0600 key file (a scheduled
|
|
23
|
+
// backup needs it and has no password) and inside the password-wrapped block (a restore on a new machine gets it from
|
|
24
|
+
// the password). It can sign a backup and can decrypt nothing.
|
|
25
|
+
//
|
|
26
|
+
// payloadKey = HKDF-SHA256(fileKey, info "synabun-backup/v1/payload")
|
|
27
|
+
// macKey = HKDF-SHA256(authKey || fileKey, info "synabun-backup/v1/header-mac")
|
|
28
|
+
// header MAC = HMAC-SHA256(macKey, prefix || header JSON) every chunk's associated data
|
|
29
|
+
//
|
|
30
|
+
// What a reader checks before it allocates or derives anything: the magic and version, the header's length
|
|
31
|
+
// (MAX_HEADER_BYTES), the chunk size (MIN/MAX_CHUNK_SIZE), the scrypt parameters (SCRYPT_LIMITS) and the length of
|
|
32
|
+
// every key and nonce. Reordered, missing, added or changed bytes fail a chunk's tag: the index and the last-chunk
|
|
33
|
+
// mark are in its nonce, and the number of chunks is the file's size.
|
|
34
|
+
//
|
|
35
|
+
// This file holds no I/O of its own beyond reading a header; backup-crypto-io.js writes and reads the files.
|
|
36
|
+
|
|
37
|
+
import {
|
|
38
|
+
createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey, diffieHellman,
|
|
39
|
+
generateKeyPairSync, hkdfSync, randomBytes, scrypt, timingSafeEqual,
|
|
40
|
+
} from 'node:crypto';
|
|
41
|
+
import { open } from 'node:fs/promises';
|
|
42
|
+
|
|
43
|
+
export const BACKUP_ENC_MAGIC = Buffer.from('SYNBKENC', 'latin1');
|
|
44
|
+
export const BACKUP_ENC_VERSION = 1;
|
|
45
|
+
export const BACKUP_ENC_EXTENSION = '.enc';
|
|
46
|
+
export const PREFIX_BYTES = 16;
|
|
47
|
+
export const MAC_BYTES = 32;
|
|
48
|
+
export const TAG_BYTES = 16;
|
|
49
|
+
export const MAX_HEADER_BYTES = 16 * 1024;
|
|
50
|
+
export const DEFAULT_CHUNK_SIZE = 1024 * 1024;
|
|
51
|
+
export const MIN_CHUNK_SIZE = 4096;
|
|
52
|
+
export const MAX_CHUNK_SIZE = 4 * 1024 * 1024;
|
|
53
|
+
/** A nonce counts chunks in 32 bits. */
|
|
54
|
+
export const MAX_CHUNKS = 0xffffffff;
|
|
55
|
+
/** scrypt as a new key is wrapped: 128 MiB, about a third of a second on a current laptop. */
|
|
56
|
+
export const DEFAULT_SCRYPT = Object.freeze({ N: 131072, r: 8, p: 1 });
|
|
57
|
+
/** What a reader accepts before it derives: a power of two for N, and at most 1 GiB of scrypt memory. */
|
|
58
|
+
export const SCRYPT_LIMITS = Object.freeze({ minN: 16384, maxN: 1048576, minR: 8, maxR: 16, minP: 1, maxP: 4, maxMemoryBytes: 1024 * 1024 * 1024 });
|
|
59
|
+
export const MIN_PASSWORD_LENGTH = 8;
|
|
60
|
+
export const MAX_PASSWORD_LENGTH = 1024;
|
|
61
|
+
|
|
62
|
+
const INFO_PAYLOAD = 'synabun-backup/v1/payload';
|
|
63
|
+
const INFO_HEADER_MAC = 'synabun-backup/v1/header-mac';
|
|
64
|
+
const INFO_FILE_KEY = 'synabun-backup/v1/file-key';
|
|
65
|
+
const INFO_SNAPSHOT_RECORD = 'synabun-backup/v1/snapshot-record';
|
|
66
|
+
const AAD_PRIVATE_KEY = 'synabun-backup/v1/private-key';
|
|
67
|
+
const PKCS8_X25519 = Buffer.from('302e020100300506032b656e04220420', 'hex');
|
|
68
|
+
const SPKI_X25519 = Buffer.from('302a300506032b656e032100', 'hex');
|
|
69
|
+
const ZERO_NONCE = Buffer.alloc(12);
|
|
70
|
+
const KEY_BYTES = 32;
|
|
71
|
+
/** What the password wraps: the X25519 private key, then the authentication key. */
|
|
72
|
+
const WRAPPED_KEYS_BYTES = KEY_BYTES * 2;
|
|
73
|
+
|
|
74
|
+
/** Every failure of this module. `code` says which; a message never holds a password or a key. */
|
|
75
|
+
export class BackupEncryptionError extends Error {
|
|
76
|
+
constructor(code, message, { status = 400 } = {}) {
|
|
77
|
+
super(message);
|
|
78
|
+
this.name = 'BackupEncryptionError';
|
|
79
|
+
this.code = code;
|
|
80
|
+
this.status = status;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const fail = (code, message, options) => new BackupEncryptionError(code, message, options);
|
|
85
|
+
const damaged = (what) => fail('BACKUP_ENC_DAMAGED', `This encrypted backup is damaged or was changed: ${what}.`);
|
|
86
|
+
|
|
87
|
+
function b64(value, bytes, what) {
|
|
88
|
+
if (typeof value !== 'string' || value.length > bytes * 2 + 8 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) throw damaged(`${what} is not readable`);
|
|
89
|
+
const buffer = Buffer.from(value, 'base64');
|
|
90
|
+
if (buffer.length !== bytes) throw damaged(`${what} has the wrong length`);
|
|
91
|
+
return buffer;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function hkdf(key, info, salt = Buffer.alloc(0)) {
|
|
95
|
+
return Buffer.from(hkdfSync('sha256', key, salt, Buffer.from(info, 'utf8'), 32));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function seal(key, nonce, plaintext, aad) {
|
|
99
|
+
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
100
|
+
cipher.setAAD(aad);
|
|
101
|
+
return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The plaintext, or null when the tag does not hold. */
|
|
105
|
+
function unseal(key, nonce, sealed, aad) {
|
|
106
|
+
if (sealed.length < TAG_BYTES) return null;
|
|
107
|
+
const decipher = createDecipheriv('aes-256-gcm', key, nonce);
|
|
108
|
+
decipher.setAAD(aad);
|
|
109
|
+
decipher.setAuthTag(sealed.subarray(sealed.length - TAG_BYTES));
|
|
110
|
+
try { return Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - TAG_BYTES)), decipher.final()]); }
|
|
111
|
+
catch { return null; }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── The password ──
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The password as it is derived from: a string, NFKC, between MIN_ and MAX_PASSWORD_LENGTH characters.
|
|
118
|
+
* `forNew`: the length rule of a password being set; one that opens an existing backup only has to be a string.
|
|
119
|
+
*/
|
|
120
|
+
export function normalizePassword(password, { forNew = false } = {}) {
|
|
121
|
+
if (typeof password !== 'string' || !password.length) throw fail('PASSWORD_REQUIRED', 'Enter the backup password.');
|
|
122
|
+
if (password.length > MAX_PASSWORD_LENGTH) throw fail('PASSWORD_TOO_LONG', `A backup password has at most ${MAX_PASSWORD_LENGTH} characters.`);
|
|
123
|
+
const normal = password.normalize('NFKC');
|
|
124
|
+
if (forNew && [...normal].length < MIN_PASSWORD_LENGTH) throw fail('PASSWORD_TOO_SHORT', `A backup password needs at least ${MIN_PASSWORD_LENGTH} characters.`);
|
|
125
|
+
return Buffer.from(normal, 'utf8');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The scrypt parameters of a header or key file, checked against SCRYPT_LIMITS before anything is derived. */
|
|
129
|
+
export function checkScryptParams(kdf) {
|
|
130
|
+
const { N, r, p } = kdf || {};
|
|
131
|
+
const L = SCRYPT_LIMITS;
|
|
132
|
+
const whole = (value) => Number.isInteger(value) && value > 0;
|
|
133
|
+
if (kdf?.kdf !== 'scrypt' || !whole(N) || !whole(r) || !whole(p)) throw damaged('its key settings are not readable');
|
|
134
|
+
if (N < L.minN || N > L.maxN || (N & (N - 1)) !== 0 || r < L.minR || r > L.maxR || p < L.minP || p > L.maxP || 128 * N * r > L.maxMemoryBytes) {
|
|
135
|
+
throw fail('BACKUP_ENC_UNSUPPORTED', 'This encrypted backup asks for key settings SynaBun does not accept.');
|
|
136
|
+
}
|
|
137
|
+
return { N, r, p };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function derivePasswordKey(passwordBytes, salt, { N, r, p }) {
|
|
141
|
+
return new Promise((resolveKey, reject) => {
|
|
142
|
+
// Asynchronous: scrypt runs on the thread pool, never on the thread that calls it.
|
|
143
|
+
scrypt(passwordBytes, salt, 32, { N, r, p, maxmem: 128 * N * r + 64 * 1024 * 1024 }, (error, key) => error ? reject(error) : resolveKey(key));
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ── The key pair ──
|
|
148
|
+
|
|
149
|
+
function publicKeyOf(privateRaw) {
|
|
150
|
+
const key = createPrivateKey({ key: Buffer.concat([PKCS8_X25519, privateRaw]), format: 'der', type: 'pkcs8' });
|
|
151
|
+
return createPublicKey(key).export({ format: 'der', type: 'spki' }).subarray(SPKI_X25519.length);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function sharedSecret(privateRaw, publicRaw) {
|
|
155
|
+
const shared = diffieHellman({
|
|
156
|
+
privateKey: createPrivateKey({ key: Buffer.concat([PKCS8_X25519, privateRaw]), format: 'der', type: 'pkcs8' }),
|
|
157
|
+
publicKey: createPublicKey({ key: Buffer.concat([SPKI_X25519, publicRaw]), format: 'der', type: 'spki' }),
|
|
158
|
+
});
|
|
159
|
+
if (shared.every(byte => byte === 0)) throw damaged('its key exchange is not valid');
|
|
160
|
+
return shared;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** A short public name of a key pair: the first 8 bytes of SHA-256 of its public key, in hex. */
|
|
164
|
+
export function keyIdOf(publicRaw) {
|
|
165
|
+
return createHash('sha256').update(publicRaw).digest('hex').slice(0, 16);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The 32-byte authentication key of a recipient as the key file holds it. A recipient read from a backup's header has
|
|
170
|
+
* none (a header never carries it in the clear): BACKUP_ENC_KEY_UNREADABLE, so nothing can be written for it.
|
|
171
|
+
*/
|
|
172
|
+
export function authKeyOf(recipient) {
|
|
173
|
+
const missing = () => fail('BACKUP_ENC_KEY_UNREADABLE', 'Backup encryption has no usable authentication key. Set it up again in Settings → Backups.', { status: 500 });
|
|
174
|
+
if (typeof recipient?.authKey !== 'string') throw missing();
|
|
175
|
+
try { return b64(recipient.authKey, KEY_BYTES, 'its authentication key'); }
|
|
176
|
+
catch { throw missing(); }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** A keyed digest for the record beside an encrypted upgrade snapshot: it can be compared, and says nothing of a file. */
|
|
180
|
+
export function snapshotRecordDigest(authKey, text) {
|
|
181
|
+
const key = hkdf(authKey, INFO_SNAPSHOT_RECORD);
|
|
182
|
+
try { return createHmac('sha256', key).update(text, 'utf8').digest('hex'); }
|
|
183
|
+
finally { key.fill(0); }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* A new key pair whose private half only `password` opens, with a new authentication key. Resolves the recipient as
|
|
188
|
+
* the key file stores it: { type, keyId, publicKey, wrappedPrivateKey: { kdf, N, r, p, salt, nonce, ciphertext },
|
|
189
|
+
* authKey } (base64). A backup's header carries all of it but `authKey`. Neither the password nor the private key is
|
|
190
|
+
* in it, or anywhere after this returns.
|
|
191
|
+
*/
|
|
192
|
+
export async function createRecipient(password, { kdf = DEFAULT_SCRYPT } = {}) {
|
|
193
|
+
const passwordBytes = normalizePassword(password, { forNew: true });
|
|
194
|
+
const params = checkScryptParams({ kdf: 'scrypt', ...kdf });
|
|
195
|
+
const { privateKey } = generateKeyPairSync('x25519');
|
|
196
|
+
const privateRaw = privateKey.export({ format: 'der', type: 'pkcs8' }).subarray(PKCS8_X25519.length);
|
|
197
|
+
const publicRaw = publicKeyOf(privateRaw);
|
|
198
|
+
const authKey = randomBytes(KEY_BYTES);
|
|
199
|
+
const wrappedKeys = Buffer.concat([privateRaw, authKey]);
|
|
200
|
+
const salt = randomBytes(16);
|
|
201
|
+
const nonce = randomBytes(12);
|
|
202
|
+
const passwordKey = await derivePasswordKey(passwordBytes, salt, params);
|
|
203
|
+
try {
|
|
204
|
+
const ciphertext = seal(passwordKey, nonce, wrappedKeys, Buffer.concat([Buffer.from(AAD_PRIVATE_KEY, 'utf8'), publicRaw]));
|
|
205
|
+
return {
|
|
206
|
+
type: 'x25519-scrypt',
|
|
207
|
+
keyId: keyIdOf(publicRaw),
|
|
208
|
+
publicKey: publicRaw.toString('base64'),
|
|
209
|
+
wrappedPrivateKey: { kdf: 'scrypt', ...params, salt: salt.toString('base64'), nonce: nonce.toString('base64'), ciphertext: ciphertext.toString('base64') },
|
|
210
|
+
authKey: authKey.toString('base64'),
|
|
211
|
+
};
|
|
212
|
+
} finally {
|
|
213
|
+
passwordKey.fill(0); privateRaw.fill(0); passwordBytes.fill(0); authKey.fill(0); wrappedKeys.fill(0);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A recipient read from a header or the key file, every field checked; the raw public key comes with it. */
|
|
218
|
+
export function readRecipient(recipient) {
|
|
219
|
+
if (!recipient || typeof recipient !== 'object' || recipient.type !== 'x25519-scrypt') throw fail('BACKUP_ENC_UNSUPPORTED', 'This encrypted backup uses a kind of key SynaBun does not know.');
|
|
220
|
+
const publicRaw = b64(recipient.publicKey, 32, 'its public key');
|
|
221
|
+
const wrapped = recipient.wrappedPrivateKey;
|
|
222
|
+
const params = checkScryptParams(wrapped);
|
|
223
|
+
return {
|
|
224
|
+
publicRaw,
|
|
225
|
+
keyId: keyIdOf(publicRaw),
|
|
226
|
+
params,
|
|
227
|
+
salt: b64(wrapped?.salt, 16, 'its key salt'),
|
|
228
|
+
nonce: b64(wrapped?.nonce, 12, 'its key nonce'),
|
|
229
|
+
ciphertext: b64(wrapped?.ciphertext, WRAPPED_KEYS_BYTES + TAG_BYTES, 'its wrapped key'),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The keys of `recipient`, opened with `password`: { privateKey, authKey } (32 raw bytes each: the caller zeroes them
|
|
235
|
+
* when done). WRONG_PASSWORD when the password does not open them. The private key that comes out must be the one the
|
|
236
|
+
* public key belongs to.
|
|
237
|
+
*/
|
|
238
|
+
export async function unlockRecipient(recipient, password) {
|
|
239
|
+
const read = readRecipient(recipient);
|
|
240
|
+
const passwordBytes = normalizePassword(password);
|
|
241
|
+
const passwordKey = await derivePasswordKey(passwordBytes, read.salt, read.params);
|
|
242
|
+
try {
|
|
243
|
+
const opened = unseal(passwordKey, read.nonce, read.ciphertext, Buffer.concat([Buffer.from(AAD_PRIVATE_KEY, 'utf8'), read.publicRaw]));
|
|
244
|
+
if (!opened) throw fail('WRONG_PASSWORD', 'That password does not open this backup.', { status: 401 });
|
|
245
|
+
const privateKey = Buffer.alloc(KEY_BYTES);
|
|
246
|
+
const authKey = Buffer.alloc(KEY_BYTES);
|
|
247
|
+
opened.copy(privateKey, 0, 0, KEY_BYTES);
|
|
248
|
+
opened.copy(authKey, 0, KEY_BYTES, WRAPPED_KEYS_BYTES);
|
|
249
|
+
opened.fill(0);
|
|
250
|
+
if (!timingSafeEqual(publicKeyOf(privateKey), read.publicRaw)) {
|
|
251
|
+
privateKey.fill(0); authKey.fill(0);
|
|
252
|
+
throw damaged('its key pair does not match');
|
|
253
|
+
}
|
|
254
|
+
return { privateKey, authKey };
|
|
255
|
+
} finally {
|
|
256
|
+
passwordKey.fill(0); passwordBytes.fill(0);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* `recipient` under a new password: the same key pair and the same authentication key, wrapped again (a new salt and
|
|
262
|
+
* nonce). Nothing a backup depends on changes: backups made before keep opening with the password of their day
|
|
263
|
+
* (their headers carry the block as it was), new ones carry this block, and all of them are signed by the one
|
|
264
|
+
* authentication key. WRONG_PASSWORD when `currentPassword` does not open the stored block. Resolves the recipient as
|
|
265
|
+
* the key file stores it; its `authKey` is the one the password wrapped, so a key file whose clear copy was changed
|
|
266
|
+
* is put right by it.
|
|
267
|
+
*/
|
|
268
|
+
export async function rewrapRecipient(recipient, currentPassword, newPassword, { kdf = DEFAULT_SCRYPT } = {}) {
|
|
269
|
+
const read = readRecipient(recipient);
|
|
270
|
+
const newBytes = normalizePassword(newPassword, { forNew: true });
|
|
271
|
+
let keys = null;
|
|
272
|
+
let wrappedKeys = null;
|
|
273
|
+
let passwordKey = null;
|
|
274
|
+
try {
|
|
275
|
+
const params = checkScryptParams({ kdf: 'scrypt', ...kdf });
|
|
276
|
+
keys = await unlockRecipient(recipient, currentPassword);
|
|
277
|
+
wrappedKeys = Buffer.concat([keys.privateKey, keys.authKey]);
|
|
278
|
+
const salt = randomBytes(16);
|
|
279
|
+
const nonce = randomBytes(12);
|
|
280
|
+
passwordKey = await derivePasswordKey(newBytes, salt, params);
|
|
281
|
+
const ciphertext = seal(passwordKey, nonce, wrappedKeys, Buffer.concat([Buffer.from(AAD_PRIVATE_KEY, 'utf8'), read.publicRaw]));
|
|
282
|
+
return {
|
|
283
|
+
type: 'x25519-scrypt',
|
|
284
|
+
keyId: read.keyId,
|
|
285
|
+
publicKey: read.publicRaw.toString('base64'),
|
|
286
|
+
wrappedPrivateKey: { kdf: 'scrypt', ...params, salt: salt.toString('base64'), nonce: nonce.toString('base64'), ciphertext: ciphertext.toString('base64') },
|
|
287
|
+
authKey: keys.authKey.toString('base64'),
|
|
288
|
+
};
|
|
289
|
+
} finally {
|
|
290
|
+
newBytes.fill(0); passwordKey?.fill(0); wrappedKeys?.fill(0); keys?.privateKey.fill(0); keys?.authKey.fill(0);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ── The header ──
|
|
295
|
+
|
|
296
|
+
function fileKeyWrapKey(shared, ephemeralPublic, recipientPublic) {
|
|
297
|
+
return hkdf(shared, INFO_FILE_KEY, Buffer.concat([ephemeralPublic, recipientPublic]));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function prefixFor(headerLength) {
|
|
301
|
+
const prefix = Buffer.alloc(PREFIX_BYTES);
|
|
302
|
+
BACKUP_ENC_MAGIC.copy(prefix, 0);
|
|
303
|
+
prefix.writeUInt8(BACKUP_ENC_VERSION, 8);
|
|
304
|
+
prefix.writeUInt32BE(headerLength, 12);
|
|
305
|
+
return prefix;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function sessionFor(fileKey, noncePrefix, chunkSize, mac) {
|
|
309
|
+
return { payloadKey: hkdf(fileKey, INFO_PAYLOAD), noncePrefix, chunkSize, aad: mac };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function headerMac(authKey, fileKey, start) {
|
|
313
|
+
const ikm = Buffer.concat([authKey, fileKey]);
|
|
314
|
+
const key = hkdf(ikm, INFO_HEADER_MAC);
|
|
315
|
+
try { return createHmac('sha256', key).update(start).digest(); }
|
|
316
|
+
finally { ikm.fill(0); key.fill(0); }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The start of a new encrypted backup for `recipient` (its public key and authentication key: no password is asked).
|
|
321
|
+
* Returns { bytes, fileKey, authKey, session, header }: `bytes` is what the file begins with (prefix, header JSON,
|
|
322
|
+
* MAC), `fileKey` the random key of this one file and `authKey` a copy of the authentication key (both kept by the
|
|
323
|
+
* caller only until the file is verified), `session` what sealChunk / openChunk take.
|
|
324
|
+
*/
|
|
325
|
+
export function createBackupHeader(recipient, { chunkSize = DEFAULT_CHUNK_SIZE, now = () => new Date() } = {}) {
|
|
326
|
+
const read = readRecipient(recipient);
|
|
327
|
+
const authKey = authKeyOf(recipient);
|
|
328
|
+
if (!Number.isInteger(chunkSize) || chunkSize < MIN_CHUNK_SIZE || chunkSize > MAX_CHUNK_SIZE) throw new RangeError(`chunkSize must be between ${MIN_CHUNK_SIZE} and ${MAX_CHUNK_SIZE}`);
|
|
329
|
+
const fileKey = randomBytes(32);
|
|
330
|
+
const ephemeral = generateKeyPairSync('x25519');
|
|
331
|
+
const ephemeralPrivate = ephemeral.privateKey.export({ format: 'der', type: 'pkcs8' }).subarray(PKCS8_X25519.length);
|
|
332
|
+
const ephemeralPublic = ephemeral.publicKey.export({ format: 'der', type: 'spki' }).subarray(SPKI_X25519.length);
|
|
333
|
+
const shared = sharedSecret(ephemeralPrivate, read.publicRaw);
|
|
334
|
+
const wrapKey = fileKeyWrapKey(shared, ephemeralPublic, read.publicRaw);
|
|
335
|
+
const noncePrefix = randomBytes(7);
|
|
336
|
+
const header = {
|
|
337
|
+
v: BACKUP_ENC_VERSION,
|
|
338
|
+
cipher: 'AES-256-GCM',
|
|
339
|
+
chunkSize,
|
|
340
|
+
noncePrefix: noncePrefix.toString('base64'),
|
|
341
|
+
created: now().toISOString(),
|
|
342
|
+
recipient: { type: recipient.type, keyId: read.keyId, publicKey: recipient.publicKey, wrappedPrivateKey: { ...recipient.wrappedPrivateKey } },
|
|
343
|
+
// The wrap key is used once (a new ephemeral key per file), so its nonce is fixed.
|
|
344
|
+
fileKey: { ephemeralPublicKey: ephemeralPublic.toString('base64'), ciphertext: seal(wrapKey, ZERO_NONCE, fileKey, Buffer.from(INFO_FILE_KEY, 'utf8')).toString('base64') },
|
|
345
|
+
};
|
|
346
|
+
shared.fill(0); wrapKey.fill(0); ephemeralPrivate.fill(0);
|
|
347
|
+
const json = Buffer.from(JSON.stringify(header), 'utf8');
|
|
348
|
+
if (json.length > MAX_HEADER_BYTES) throw new Error('The backup header is too large');
|
|
349
|
+
const start = Buffer.concat([prefixFor(json.length), json]);
|
|
350
|
+
const mac = headerMac(authKey, fileKey, start);
|
|
351
|
+
return { bytes: Buffer.concat([start, mac]), fileKey, authKey, session: sessionFor(fileKey, noncePrefix, chunkSize, mac), header };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** True when `bytes` (at least 8) begin as an encrypted backup does. */
|
|
355
|
+
export function hasEncryptedBackupMagic(bytes) {
|
|
356
|
+
return Buffer.isBuffer(bytes) && bytes.length >= BACKUP_ENC_MAGIC.length && bytes.subarray(0, BACKUP_ENC_MAGIC.length).equals(BACKUP_ENC_MAGIC);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* The header of an encrypted backup, read through `readAt(position, length)` (a Buffer of exactly that length, or
|
|
361
|
+
* shorter at the end of the file). Nothing here trusts the file: every length is bounded before it is read.
|
|
362
|
+
* Resolves { header, recipient (readRecipient), start (prefix + JSON), mac, dataOffset, chunkSize, noncePrefix }.
|
|
363
|
+
*/
|
|
364
|
+
export async function readBackupHeader(readAt) {
|
|
365
|
+
const prefix = await readAt(0, PREFIX_BYTES);
|
|
366
|
+
if (!hasEncryptedBackupMagic(prefix)) throw fail('BACKUP_NOT_ENCRYPTED', 'This file is not an encrypted SynaBun backup.');
|
|
367
|
+
if (prefix.length < PREFIX_BYTES) throw damaged('it ends inside its header');
|
|
368
|
+
const version = prefix.readUInt8(8);
|
|
369
|
+
if (version < 1) throw damaged('its format version is not readable');
|
|
370
|
+
if (version > BACKUP_ENC_VERSION) throw fail('BACKUP_ENC_UNSUPPORTED', `This backup was encrypted by a newer SynaBun (format ${version}). Update SynaBun to restore it.`);
|
|
371
|
+
const length = prefix.readUInt32BE(12);
|
|
372
|
+
if (length < 2 || length > MAX_HEADER_BYTES) throw damaged('its header has an impossible length');
|
|
373
|
+
const rest = await readAt(PREFIX_BYTES, length + MAC_BYTES);
|
|
374
|
+
if (rest.length < length + MAC_BYTES) throw damaged('it ends inside its header');
|
|
375
|
+
let header;
|
|
376
|
+
try { header = JSON.parse(rest.subarray(0, length).toString('utf8')); } catch { throw damaged('its header is not readable'); }
|
|
377
|
+
if (!header || typeof header !== 'object' || header.v !== BACKUP_ENC_VERSION || header.cipher !== 'AES-256-GCM') throw fail('BACKUP_ENC_UNSUPPORTED', 'This encrypted backup uses a format SynaBun does not know.');
|
|
378
|
+
const chunkSize = header.chunkSize;
|
|
379
|
+
if (!Number.isInteger(chunkSize) || chunkSize < MIN_CHUNK_SIZE || chunkSize > MAX_CHUNK_SIZE) throw damaged('its chunk size is out of range');
|
|
380
|
+
return {
|
|
381
|
+
header,
|
|
382
|
+
recipient: readRecipient(header.recipient),
|
|
383
|
+
start: Buffer.concat([prefix, rest.subarray(0, length)]),
|
|
384
|
+
mac: Buffer.from(rest.subarray(length)),
|
|
385
|
+
dataOffset: PREFIX_BYTES + length + MAC_BYTES,
|
|
386
|
+
chunkSize,
|
|
387
|
+
noncePrefix: b64(header.noncePrefix, 7, 'its nonce prefix'),
|
|
388
|
+
ephemeralPublic: b64(header.fileKey?.ephemeralPublicKey, 32, 'its file key'),
|
|
389
|
+
wrappedFileKey: b64(header.fileKey?.ciphertext, 32 + TAG_BYTES, 'its file key'),
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** The header of the file at `path` (readBackupHeader over the file). */
|
|
394
|
+
export async function readBackupHeaderFile(path) {
|
|
395
|
+
const handle = await open(path, 'r');
|
|
396
|
+
try {
|
|
397
|
+
return await readBackupHeader(async (position, length) => {
|
|
398
|
+
const buffer = Buffer.alloc(length);
|
|
399
|
+
const { bytesRead } = await handle.read(buffer, 0, length, position);
|
|
400
|
+
return buffer.subarray(0, bytesRead);
|
|
401
|
+
});
|
|
402
|
+
} finally {
|
|
403
|
+
await handle.close();
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** True when the file at `path` begins as an encrypted backup does. False for a file that cannot be read. */
|
|
408
|
+
export async function isEncryptedBackupFile(path) {
|
|
409
|
+
let handle;
|
|
410
|
+
try {
|
|
411
|
+
handle = await open(path, 'r');
|
|
412
|
+
const buffer = Buffer.alloc(BACKUP_ENC_MAGIC.length);
|
|
413
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
414
|
+
return hasEncryptedBackupMagic(buffer.subarray(0, bytesRead));
|
|
415
|
+
} catch { return false; }
|
|
416
|
+
finally { await handle?.close().catch(() => {}); }
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** The file key of a parsed header (readBackupHeader), opened with the private key. */
|
|
420
|
+
export function unwrapFileKey(parsed, privateRaw) {
|
|
421
|
+
const shared = sharedSecret(privateRaw, parsed.ephemeralPublic);
|
|
422
|
+
const wrapKey = fileKeyWrapKey(shared, parsed.ephemeralPublic, parsed.recipient.publicRaw);
|
|
423
|
+
try {
|
|
424
|
+
const fileKey = unseal(wrapKey, ZERO_NONCE, parsed.wrappedFileKey, Buffer.from(INFO_FILE_KEY, 'utf8'));
|
|
425
|
+
if (!fileKey) throw damaged('its file key does not open');
|
|
426
|
+
return fileKey;
|
|
427
|
+
} finally { shared.fill(0); wrapKey.fill(0); }
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The session of a parsed header for `fileKey` and `authKey`: the header's MAC is checked first, so a header changed
|
|
432
|
+
* in any byte (the chunk size, the nonce prefix, the recipient), or a whole file written by somebody who does not hold
|
|
433
|
+
* the authentication key, is refused before a chunk is read.
|
|
434
|
+
*/
|
|
435
|
+
export function openBackupSession(parsed, fileKey, authKey) {
|
|
436
|
+
if (!Buffer.isBuffer(fileKey) || fileKey.length !== KEY_BYTES) throw new TypeError('fileKey must be 32 bytes');
|
|
437
|
+
if (!Buffer.isBuffer(authKey) || authKey.length !== KEY_BYTES) throw new TypeError('authKey must be 32 bytes');
|
|
438
|
+
const mac = headerMac(authKey, fileKey, parsed.start);
|
|
439
|
+
if (!timingSafeEqual(mac, parsed.mac)) throw damaged('its header does not match its key');
|
|
440
|
+
return sessionFor(fileKey, parsed.noncePrefix, parsed.chunkSize, mac);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** The file key, authentication key and session of the backup whose header is `parsed`, opened with `password`. */
|
|
444
|
+
export async function unlockBackupHeader(parsed, password) {
|
|
445
|
+
const { privateKey, authKey } = await unlockRecipient(parsed.header.recipient, password);
|
|
446
|
+
let fileKey = null;
|
|
447
|
+
try {
|
|
448
|
+
fileKey = unwrapFileKey(parsed, privateKey);
|
|
449
|
+
return { fileKey, authKey, session: openBackupSession(parsed, fileKey, authKey) };
|
|
450
|
+
} catch (error) {
|
|
451
|
+
fileKey?.fill(0);
|
|
452
|
+
authKey.fill(0);
|
|
453
|
+
throw error;
|
|
454
|
+
} finally { privateKey.fill(0); }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// ── The chunks ──
|
|
458
|
+
|
|
459
|
+
function chunkNonce(session, index, last) {
|
|
460
|
+
if (!Number.isInteger(index) || index < 0 || index >= MAX_CHUNKS) throw new RangeError('chunk index out of range');
|
|
461
|
+
const nonce = Buffer.alloc(12);
|
|
462
|
+
session.noncePrefix.copy(nonce, 0);
|
|
463
|
+
nonce.writeUInt32BE(index, 7);
|
|
464
|
+
nonce.writeUInt8(last ? 1 : 0, 11);
|
|
465
|
+
return nonce;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Chunk `index` of the plaintext, sealed (ciphertext then its 16-byte tag). `last`: it is the file's final chunk. */
|
|
469
|
+
export function sealChunk(session, index, last, plaintext) {
|
|
470
|
+
if (plaintext.length > session.chunkSize) throw new RangeError('a chunk is larger than the chunk size');
|
|
471
|
+
return seal(session.payloadKey, chunkNonce(session, index, last), plaintext, session.aad);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** The plaintext of chunk `index`, or a BACKUP_ENC_DAMAGED error: wrong place, wrong last mark, or changed bytes. */
|
|
475
|
+
export function openChunk(session, index, last, sealed) {
|
|
476
|
+
const plaintext = unseal(session.payloadKey, chunkNonce(session, index, last), sealed, session.aad);
|
|
477
|
+
if (!plaintext) throw damaged(`part ${index + 1} does not pass its check`);
|
|
478
|
+
return plaintext;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Where the chunks of a file are: { chunks, plaintextSize, lastSealedSize } for a payload of `payloadBytes` (the
|
|
483
|
+
* file's size less the header). A payload that no whole file could have is refused here, before any chunk is read:
|
|
484
|
+
* shorter than one tag, or ending in a chunk with a tag and no data after another chunk.
|
|
485
|
+
*/
|
|
486
|
+
export function chunkLayout(payloadBytes, chunkSize) {
|
|
487
|
+
const sealedSize = chunkSize + TAG_BYTES;
|
|
488
|
+
if (!Number.isSafeInteger(payloadBytes) || payloadBytes < TAG_BYTES) throw damaged('it ends before its first part');
|
|
489
|
+
const chunks = Math.ceil(payloadBytes / sealedSize);
|
|
490
|
+
if (chunks > MAX_CHUNKS) throw damaged('it holds more parts than a backup can');
|
|
491
|
+
const lastSealedSize = payloadBytes - (chunks - 1) * sealedSize;
|
|
492
|
+
if (lastSealedSize < TAG_BYTES || (lastSealedSize === TAG_BYTES && chunks > 1)) throw damaged('its last part is cut short');
|
|
493
|
+
return { chunks, plaintextSize: payloadBytes - chunks * TAG_BYTES, lastSealedSize, sealedSize };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Turns a stream of plaintext into sealed chunks, in order. `push(bytes)` returns the sealed chunks that are now
|
|
498
|
+
* complete (possibly none: the last chunk of a file is only known at `finish()`, which returns the rest). Synchronous;
|
|
499
|
+
* the writer of backup-crypto-worker.js runs it on a thread of its own.
|
|
500
|
+
*/
|
|
501
|
+
export function createChunkSealer(session) {
|
|
502
|
+
let held = Buffer.alloc(0);
|
|
503
|
+
let index = 0;
|
|
504
|
+
let finished = false;
|
|
505
|
+
return {
|
|
506
|
+
push(bytes) {
|
|
507
|
+
if (finished) throw new Error('the backup was already finished');
|
|
508
|
+
held = held.length ? Buffer.concat([held, bytes]) : bytes;
|
|
509
|
+
const out = [];
|
|
510
|
+
// A full chunk is sealed only once a byte after it exists: until then it may be the last one.
|
|
511
|
+
while (held.length > session.chunkSize) {
|
|
512
|
+
out.push(sealChunk(session, index++, false, held.subarray(0, session.chunkSize)));
|
|
513
|
+
held = held.subarray(session.chunkSize);
|
|
514
|
+
}
|
|
515
|
+
return out;
|
|
516
|
+
},
|
|
517
|
+
finish() {
|
|
518
|
+
if (finished) throw new Error('the backup was already finished');
|
|
519
|
+
finished = true;
|
|
520
|
+
const last = sealChunk(session, index++, true, held);
|
|
521
|
+
held = Buffer.alloc(0);
|
|
522
|
+
return [last];
|
|
523
|
+
},
|
|
524
|
+
};
|
|
525
|
+
}
|