diff --git a/docs/settings.md b/docs/settings.md index 0f96a07d..0abe75d2 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -988,10 +988,14 @@ If this option is enabled, PouchDB will hold the connection open for 60 seconds, Setting key: configPassphraseStore +Choose how the passphrase for sensitive configuration items is provided. **Default** uses the existing default key. **Use a custom passphrase** uses the value of `configPassphrase` and saves that key on this device. **Ask an passphrase at every launch** requests a masked passphrase at start-up and caches a successfully entered key in memory for that launch. + +Apply this setting and its passphrase together. Applying them re-encrypts the saved sensitive values with the selected passphrase and changes how LiveSync obtains that passphrase in one operation. If Apply fails, the edited values stay available for another attempt. Re-encryption preserves the plaintext values: it does not change the E2EE passphrase, the ID key, or Vault contents. + #### Passphrase of sensitive configuration items Setting key: configPassphrase -This passphrase will not be copied to another device. It will be set to `Default` until you configure it again. +This passphrase is not copied to another device. With **Use a custom passphrase**, the selected mode is stored in the configuration but the key remains on this device. If protected settings need to be decrypted and another device does not have the key, LiveSync asks for the passphrase during start-up. After the protected settings validate it, the key is saved on that device. ### 4. Developer diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 17407675..388c55a3 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -117,6 +117,12 @@ When a notice identifies an unknown feature, update this device and every other ## Setup and settings questions +### LiveSync asks for a configuration encryption passphrase at start-up + +When **Use a custom passphrase** is selected and this device has no usable saved key, enter the passphrase which protects the sensitive configuration. LiveSync validates it against the saved settings, then saves the validated key on this device before continuing start-up. **Ask an passphrase at every launch** requests a masked passphrase at start-up and caches a successfully entered key in memory for that launch. + +For the custom-key recovery prompt used by **Use a custom passphrase**, cancelling or closing the prompt stops this start-up attempt and preserves the encrypted configuration. Start Obsidian again to retry. A headless command-line process cannot complete that interactive recovery prompt, so it declines to load protected settings when recovery input is required. + ### Share a configuration with another device Generate an encrypted Setup URI from a working device. This preserves the intended remote profiles and selections while allowing the additional device to keep its own device-specific name. Store the URI and its passphrase separately. diff --git a/package-lock.json b/package-lock.json index 26be2de9..74b5f7b3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,7 @@ "@smithy/types": "^4.14.3", "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", - "@vrtmrz/livesync-commonlib": "0.1.36", + "@vrtmrz/livesync-commonlib": "0.1.38", "@vrtmrz/obsidian-plugin-kit": "0.1.4", "@vrtmrz/ui-interactions": "0.1.2", "diff-match-patch": "^1.0.5", @@ -31,7 +31,7 @@ "markdown-it": "^14.3.2", "minimatch": "^10.2.5", "obsidian": "^1.13.1", - "octagonal-wheels": "^0.1.54", + "octagonal-wheels": "^0.1.55", "qrcode-generator": "^1.4.4", "xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2" }, @@ -4320,7 +4320,7 @@ "version": "8.69.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.69.0.tgz", "integrity": "sha512-K3VrubUPhlo9VDBS6QdI8YB5j7ClpqLRdefcz6PFrhnwicehBweqQ9Evhl4l+FYz0HdDmMqIiSX0aldGRYtDCA==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4567,9 +4567,9 @@ } }, "node_modules/@vrtmrz/livesync-commonlib": { - "version": "0.1.36", - "resolved": "https://registry.npmjs.org/@vrtmrz/livesync-commonlib/-/livesync-commonlib-0.1.36.tgz", - "integrity": "sha512-YEVEM3Uq0YnqMP70hOFhmfkyS2X3Ptp/t43EH/6yc/NirQhpTYfYV6hLEuXok5LEw2gkWV7G6wMiYGlEjFCTig==", + "version": "0.1.38", + "resolved": "https://registry.npmjs.org/@vrtmrz/livesync-commonlib/-/livesync-commonlib-0.1.38.tgz", + "integrity": "sha512-dXE1P6DbjxWwhX2tKnUPLgw6CTyln922GJAQjkA8kcK+sfj8q/PfWC4pgo3/SP6Obor+1y/S7nfVo2ofbUPDjw==", "license": "MIT", "dependencies": { "@aws-sdk/client-s3": "^3.808.0", @@ -4585,7 +4585,7 @@ "idb": "^8.0.3", "markdown-it": "^14.2.0", "minimatch": "^10.2.5", - "octagonal-wheels": "^0.1.53", + "octagonal-wheels": "^0.1.55", "pouchdb-adapter-http": "^9.0.0", "pouchdb-adapter-idb": "^9.0.0", "pouchdb-adapter-indexeddb": "^9.0.0", @@ -9629,9 +9629,9 @@ "license": "MIT" }, "node_modules/octagonal-wheels": { - "version": "0.1.54", - "resolved": "https://registry.npmjs.org/octagonal-wheels/-/octagonal-wheels-0.1.54.tgz", - "integrity": "sha512-Je3ancYhjKX7UY2K19T/qTjG8C9nK8YVrACr5naIf78mN4bbjQkYyWmlj+ooifV/moWVsQrp4fEWz/7mv6It3A==", + "version": "0.1.55", + "resolved": "https://registry.npmjs.org/octagonal-wheels/-/octagonal-wheels-0.1.55.tgz", + "integrity": "sha512-mHsQv/h4Tw4ZGJCmTxXFlgeRvPuL9s47C0arD8Njqld+DKr3ppaWjVteEBP+9bWFSOpv/a1u2yY3LYNFGmuexg==", "license": "MIT", "dependencies": { "idb": "^8.0.3" @@ -11107,6 +11107,35 @@ "node": ">= 0.4" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/string.prototype.matchall": { "version": "4.0.12", "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz", @@ -11205,35 +11234,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/strip-bom": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", @@ -11408,21 +11408,6 @@ } } }, - "node_modules/svelte-check/node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/svelte-eslint-parser": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/svelte-eslint-parser/-/svelte-eslint-parser-1.8.0.tgz", diff --git a/package.json b/package.json index ea74620e..71ccfdfe 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "test:e2e:obsidian:document-history-nav": "tsx test/e2e-obsidian/scripts/document-history-nav.ts", "test:e2e:obsidian:document-history-restore": "tsx test/e2e-obsidian/scripts/document-history-restore.ts", "test:e2e:obsidian:settings-ui": "tsx test/e2e-obsidian/scripts/settings-ui.ts", + "test:e2e:obsidian:configuration-encryption": "tsx test/e2e-obsidian/scripts/configuration-encryption.ts", "test:e2e:obsidian:review-harness": "tsx test/e2e-obsidian/scripts/review-harness.ts", "test:e2e:obsidian:p2p-pane": "tsx test/e2e-obsidian/scripts/p2p-pane.ts", "test:e2e:obsidian:vault-reflection": "tsx test/e2e-obsidian/scripts/vault-reflection.ts", @@ -192,7 +193,7 @@ "@smithy/types": "^4.14.3", "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", - "@vrtmrz/livesync-commonlib": "0.1.36", + "@vrtmrz/livesync-commonlib": "0.1.38", "@vrtmrz/obsidian-plugin-kit": "0.1.4", "@vrtmrz/ui-interactions": "0.1.2", "diff-match-patch": "^1.0.5", @@ -200,7 +201,7 @@ "markdown-it": "^14.3.2", "minimatch": "^10.2.5", "obsidian": "^1.13.1", - "octagonal-wheels": "^0.1.54", + "octagonal-wheels": "^0.1.55", "qrcode-generator": "^1.4.4", "xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2" }, diff --git a/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.ts b/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.ts index 5bf463d1..02caffa8 100644 --- a/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.ts +++ b/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.ts @@ -133,7 +133,7 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { applySetting(keys: AllSettingItemKey[]) { for (const k of keys) { if (!this.isDirty(k)) continue; - if (k in OnDialogSettingsDefault) { + if (this.isConfigurationEncryptionSetting(k) || k in OnDialogSettingsDefault) { // //@ts-ignore // this.initialSettings[k] = this.editingSettings[k]; continue; @@ -141,21 +141,21 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { this.copySettingValue(this.core.settings, this.editingSettings, k); this.copySettingValue(this.initialSettings, this.core.settings, k); } - keys.forEach((e) => this.refreshSetting(e)); + keys.forEach((e) => { + if (this.isConfigurationEncryptionSetting(e) && this.isDirty(e)) return; + this.refreshSetting(e); + }); } - applyAllSettings() { + async applyAllSettings() { const changedKeys = (Object.keys(this.editingSettings ?? {}) as AllSettingItemKey[]).filter((e) => this.isDirty(e) ); + await this.saveConfigurationEncryptionIfDirty(changedKeys); this.applySetting(changedKeys); this.reloadAllSettings(); } async saveLocalSetting(key: keyof typeof OnDialogSettingsDefault) { - if (key == "configPassphrase") { - compatGlobal.localStorage.setItem("ls-setting-passphrase", this.editingSettings?.[key] ?? ""); - return await Promise.resolve(); - } if (key == "deviceAndVaultName") { this.services.setting.setDeviceAndVaultName(this.editingSettings?.[key] ?? ""); this.services.setting.saveDeviceAndVaultName(); @@ -168,10 +168,10 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { */ async saveSettings(keys: AllSettingItemKey[]) { let hasChanged = false; - const appliedKeys = [] as AllSettingItemKey[]; - for (const k of keys) { - if (!this.isDirty(k)) continue; - appliedKeys.push(k); + const appliedKeys = keys.filter((k) => this.isDirty(k)); + await this.saveConfigurationEncryptionIfDirty(appliedKeys); + for (const k of appliedKeys) { + if (this.isConfigurationEncryptionSetting(k)) continue; if (k in OnDialogSettingsDefault) { await this.saveLocalSetting(k as keyof OnDialogSettings); this.copySettingValue(this.initialSettings, this.editingSettings, k); @@ -192,7 +192,32 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { .map((e) => Promise.resolve(e.handler(this.editingSettings[e.key]))); await Promise.all(handlers); // } - keys.forEach((e) => this.refreshSetting(e)); + keys.forEach((e) => { + if (this.isConfigurationEncryptionSetting(e) && this.isDirty(e)) return; + this.refreshSetting(e); + }); + } + + private isConfigurationEncryptionSetting(key: AllSettingItemKey): boolean { + return key === "configPassphraseStore" || key === "configPassphrase"; + } + + private async saveConfigurationEncryptionIfDirty(keys: AllSettingItemKey[]): Promise { + if (!keys.some((key) => this.isConfigurationEncryptionSetting(key) && this.isDirty(key))) { + return; + } + + const appliedConfigurationEncryption = { + configPassphraseStore: this.editingSettings.configPassphraseStore, + configPassphrase: this.editingSettings.configPassphrase, + }; + await this.services.setting.changeConfigurationEncryption( + appliedConfigurationEncryption.configPassphraseStore, + appliedConfigurationEncryption.configPassphrase + ); + + this.copySettingValue(this.initialSettings, appliedConfigurationEncryption, "configPassphraseStore"); + this.copySettingValue(this.initialSettings, appliedConfigurationEncryption, "configPassphrase"); } /** @@ -272,10 +297,35 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { * Reread all settings and request invalidate */ reloadAllSettings(skipUpdate: boolean = false) { + const previousSettings = this._editingSettings; + const previousSnapshot = this.initialSettings; + const pendingConfigurationEncryption = + previousSettings && previousSnapshot + ? { + configPassphraseStore: isObjectDifferent( + previousSettings.configPassphraseStore, + previousSnapshot.configPassphraseStore + ) + ? { value: previousSettings.configPassphraseStore } + : undefined, + configPassphrase: isObjectDifferent( + previousSettings.configPassphrase, + previousSnapshot.configPassphrase + ) + ? { value: previousSettings.configPassphrase } + : undefined, + } + : undefined; const localSetting = this.reloadAllLocalSettings(); this._editingSettings = { ...this.core.settings, ...localSetting }; this._editingSettings = { ...this.editingSettings, ...this.computeAllLocalSettings() }; this.initialSettings = { ...this.editingSettings }; + if (pendingConfigurationEncryption?.configPassphraseStore) { + this._editingSettings.configPassphraseStore = pendingConfigurationEncryption.configPassphraseStore.value; + } + if (pendingConfigurationEncryption?.configPassphrase) { + this._editingSettings.configPassphrase = pendingConfigurationEncryption.configPassphrase.value; + } if (!skipUpdate) this.requestUpdate(); } @@ -1020,7 +1070,7 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { if (!this.editingSettings.encrypt) { this.editingSettings.passphrase = ""; } - this.applyAllSettings(); + await this.applyAllSettings(); await this.services.setting.suspendAllSync(); await this.services.setting.suspendExtraSync(); this.reloadAllSettings(); diff --git a/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.unit.spec.ts b/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.unit.spec.ts index 3f39d081..04332958 100644 --- a/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.unit.spec.ts +++ b/src/modules/features/SettingDialogue/ObsidianLiveSyncSettingTab.unit.spec.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { DEFAULT_SETTINGS, LOG_LEVEL_NOTICE, REMOTE_COUCHDB } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { REMOTE_RESOURCE_KINDS } from "@vrtmrz/livesync-commonlib/replication"; +import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; const settingsInitialisationMocks = vi.hoisted(() => ({ applySettingsWithInitialisationChoice: vi.fn(), @@ -75,6 +76,8 @@ beforeEach(() => { settingsInitialisationMocks.applySettingsWithInitialisationChoice.mockReset(); loggerMocks.Logger.mockClear(); vi.mocked($msg).mockClear(); + vi.mocked(compatGlobal.localStorage.getItem).mockReset().mockReturnValue(null); + vi.mocked(compatGlobal.localStorage.setItem).mockReset(); }); describe("ObsidianLiveSyncSettingTab passphrase verification", () => { @@ -260,6 +263,9 @@ describe("ObsidianLiveSyncSettingTab Fresh Start Wipe", () => { describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => { function createSettingsTab() { const saveSettingData = vi.fn(async () => undefined); + const suspendAllSync = vi.fn(async () => undefined); + const suspendExtraSync = vi.fn(async () => undefined); + const performRebuildDB = vi.fn(async () => undefined); const confirmWithMessage = vi.fn(); const plugin = { app: {}, @@ -276,8 +282,13 @@ describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => { setting: { saveSettingData, getDeviceAndVaultName: vi.fn(() => ""), + suspendAllSync, + suspendExtraSync, }, }, + rebuilder: { + $performRebuildDB: performRebuildDB, + }, }, }; const tab = new ObsidianLiveSyncSettingTab({} as never, plugin as never); @@ -294,7 +305,15 @@ describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => { vi.spyOn(tab, "isPassphraseValid").mockResolvedValue(true); vi.spyOn(tab, "checkWorkingPassphrase").mockResolvedValue(true); const closeSetting = vi.spyOn(tab, "closeSetting").mockImplementation(() => undefined); - return { tab, saveSettingData, confirmWithMessage, closeSetting }; + return { + tab, + saveSettingData, + suspendAllSync, + suspendExtraSync, + performRebuildDB, + confirmWithMessage, + closeSetting, + }; } it("keeps pending settings in the editing buffer when initialisation and the fallback are cancelled", async () => { @@ -365,6 +384,49 @@ describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => { expect(tab.core.settings.handleFilenameCaseSensitive).toBe(false); expect(closeSetting).not.toHaveBeenCalled(); }); + + it("does not apply unrelated settings or start a rebuild when configuration encryption fails", async () => { + const { tab, saveSettingData, suspendAllSync, suspendExtraSync, performRebuildDB, closeSetting } = + createSettingsTab(); + const failure = new Error("configuration encryption could not be saved"); + const changeConfigurationEncryption = vi.fn(async () => { + throw failure; + }); + Object.assign(tab.core.services.setting, { changeConfigurationEncryption }); + const savedStore = "LOCALSTORAGE"; + const editedStore = "ASK_AT_LAUNCH"; + tab.core.settings.encrypt = false; + tab.core.settings.configPassphraseStore = savedStore; + tab.initialSettings!.configPassphraseStore = savedStore; + tab.editingSettings.configPassphraseStore = editedStore; + tab.initialSettings!.configPassphrase = "old custom passphrase"; + tab.editingSettings.configPassphrase = "new custom passphrase"; + tab.editingSettings.handleFilenameCaseSensitive = true; + const applySetting = vi.spyOn(tab, "applySetting"); + const reloadAllSettings = vi.spyOn(tab, "reloadAllSettings"); + const saveAllDirtySettings = vi.spyOn(tab, "saveAllDirtySettings"); + + await expect(tab.rebuildDB("localOnly")).rejects.toBe(failure); + + expect(changeConfigurationEncryption).toHaveBeenCalledOnce(); + expect(changeConfigurationEncryption).toHaveBeenCalledWith(editedStore, "new custom passphrase"); + expect(applySetting).not.toHaveBeenCalled(); + expect(tab.core.settings.handleFilenameCaseSensitive).toBe(false); + expect(tab.initialSettings!.handleFilenameCaseSensitive).toBe(false); + expect(tab.editingSettings.handleFilenameCaseSensitive).toBe(true); + expect(tab.core.settings.configPassphraseStore).toBe(savedStore); + expect(tab.initialSettings!.configPassphraseStore).toBe(savedStore); + expect(tab.initialSettings!.configPassphrase).toBe("old custom passphrase"); + expect(tab.editingSettings.configPassphraseStore).toBe(editedStore); + expect(tab.editingSettings.configPassphrase).toBe("new custom passphrase"); + expect(suspendAllSync).not.toHaveBeenCalled(); + expect(suspendExtraSync).not.toHaveBeenCalled(); + expect(reloadAllSettings).not.toHaveBeenCalled(); + expect(saveAllDirtySettings).not.toHaveBeenCalled(); + expect(saveSettingData).not.toHaveBeenCalled(); + expect(closeSetting).not.toHaveBeenCalled(); + expect(performRebuildDB).not.toHaveBeenCalled(); + }); }); describe("ObsidianLiveSyncSettingTab declarative settings boundary", () => { @@ -463,4 +525,82 @@ describe("ObsidianLiveSyncSettingTab declarative settings boundary", () => { expect(first).not.toHaveBeenCalled(); expect(replacement).toHaveBeenCalledOnce(); }); + + it("saves a custom configuration passphrase edit through the setting service", async () => { + const { tab } = createSettingsTab(); + const changeConfigurationEncryption = vi.fn(async () => { + vi.mocked(compatGlobal.localStorage.getItem).mockReturnValue("new custom passphrase"); + }); + Object.assign(tab.core.services.setting, { changeConfigurationEncryption }); + const store = "LOCALSTORAGE"; + tab.editingSettings.configPassphraseStore = store; + tab.initialSettings!.configPassphraseStore = store; + tab.editingSettings.configPassphrase = "new custom passphrase"; + tab.initialSettings!.configPassphrase = "old custom passphrase"; + vi.mocked(compatGlobal.localStorage.setItem).mockClear(); + + await tab.saveSettings(["configPassphrase"]); + + expect(changeConfigurationEncryption).toHaveBeenCalledOnce(); + expect(changeConfigurationEncryption).toHaveBeenCalledWith(store, "new custom passphrase"); + expect(compatGlobal.localStorage.setItem).not.toHaveBeenCalled(); + expect(tab.initialSettings!.configPassphrase).toBe("new custom passphrase"); + }); + + it("keeps a later passphrase edit dirty while an earlier Apply is pending", async () => { + const { tab } = createSettingsTab(); + let resolveApply!: () => void; + const changeConfigurationEncryption = vi.fn( + () => + new Promise((resolve) => { + resolveApply = resolve; + }) + ); + Object.assign(tab.core.services.setting, { changeConfigurationEncryption }); + tab.editingSettings.configPassphraseStore = "LOCALSTORAGE"; + tab.initialSettings!.configPassphraseStore = "LOCALSTORAGE"; + tab.initialSettings!.configPassphrase = "previous passphrase"; + tab.editingSettings.configPassphrase = "passphrase A"; + vi.mocked(compatGlobal.localStorage.getItem).mockReturnValue("passphrase A"); + + const apply = tab.saveSettings(["configPassphrase"]); + expect(changeConfigurationEncryption).toHaveBeenCalledWith("LOCALSTORAGE", "passphrase A"); + + tab.editingSettings.configPassphrase = "passphrase B"; + resolveApply(); + await apply; + tab.reloadAllSettings(); + + expect(tab.initialSettings!.configPassphrase).toBe("passphrase A"); + expect(tab.editingSettings.configPassphrase).toBe("passphrase B"); + expect(tab.isDirty("configPassphrase")).toBe(true); + }); + + it("keeps both configuration encryption edits pending when applying them fails", async () => { + const { tab } = createSettingsTab(); + const failure = new Error("configuration encryption could not be saved"); + const changeConfigurationEncryption = vi.fn(async () => { + throw failure; + }); + Object.assign(tab.core.services.setting, { changeConfigurationEncryption }); + const savedStore = "LOCALSTORAGE"; + const editedStore = "ASK_AT_LAUNCH"; + tab.core.settings.configPassphraseStore = savedStore; + tab.initialSettings!.configPassphraseStore = savedStore; + tab.editingSettings.configPassphraseStore = editedStore; + tab.initialSettings!.configPassphrase = "old custom passphrase"; + tab.editingSettings.configPassphrase = "new custom passphrase"; + vi.mocked(compatGlobal.localStorage.setItem).mockClear(); + + await expect(tab.saveSettings(["configPassphraseStore", "configPassphrase"])).rejects.toBe(failure); + + expect(changeConfigurationEncryption).toHaveBeenCalledOnce(); + expect(changeConfigurationEncryption).toHaveBeenCalledWith(editedStore, "new custom passphrase"); + expect(compatGlobal.localStorage.setItem).not.toHaveBeenCalled(); + expect(tab.core.settings.configPassphraseStore).toBe(savedStore); + expect(tab.initialSettings!.configPassphraseStore).toBe(savedStore); + expect(tab.initialSettings!.configPassphrase).toBe("old custom passphrase"); + expect(tab.editingSettings.configPassphraseStore).toBe(editedStore); + expect(tab.editingSettings.configPassphrase).toBe("new custom passphrase"); + }); }); diff --git a/src/modules/main/ModuleLiveSyncMain.unit.spec.ts b/src/modules/main/ModuleLiveSyncMain.unit.spec.ts index 1fc7a139..bbb744ce 100644 --- a/src/modules/main/ModuleLiveSyncMain.unit.spec.ts +++ b/src/modules/main/ModuleLiveSyncMain.unit.spec.ts @@ -17,9 +17,66 @@ vi.mock("@/common/translation", () => ({ setLang: vi.fn(), })); +vi.mock("@vrtmrz/livesync-commonlib/compat/worker/bgWorker", () => ({ + initialiseWorkerModule: vi.fn(), +})); + import { ModuleLiveSyncMain } from "./ModuleLiveSyncMain.ts"; describe("ModuleLiveSyncMain", () => { + it.each(["unlock", "cancel"] as const)( + "keeps database and settings lifecycle behind a pending configuration load: %s", + async (outcome) => { + let unlock!: () => void; + let cancel!: (error: Error) => void; + const loadSettings = vi.fn( + () => + new Promise((resolve, reject) => { + unlock = resolve; + cancel = reject; + }) + ); + const appLifecycle = { + onWireUpEvents: vi.fn(async () => true), + onInitialise: vi.fn(async () => true), + onSettingLoaded: vi.fn(async () => true), + onLoaded: vi.fn(async () => true), + }; + const openDatabase = vi.fn(async () => undefined); + const services = { + context: { events: {} }, + setting: { loadSettings }, + appLifecycle, + database: { openDatabase }, + databaseEvents: {}, + replicator: {}, + }; + const host = { services, core: { services, addOns: [] }, _log: vi.fn() }; + const pending = ModuleLiveSyncMain.prototype._onLiveSyncLoad.call(host as never); + await vi.waitFor(() => expect(loadSettings).toHaveBeenCalledOnce()); + expect(appLifecycle.onSettingLoaded).not.toHaveBeenCalled(); + expect(openDatabase).not.toHaveBeenCalled(); + expect(appLifecycle.onLoaded).not.toHaveBeenCalled(); + + if (outcome === "cancel") { + const rejected = expect(pending).rejects.toThrow("synthetic cancelled configuration load"); + cancel(new Error("synthetic cancelled configuration load")); + await rejected; + expect(appLifecycle.onSettingLoaded).not.toHaveBeenCalled(); + expect(openDatabase).not.toHaveBeenCalled(); + expect(appLifecycle.onLoaded).not.toHaveBeenCalled(); + } else { + unlock(); + await expect(pending).resolves.toBe(true); + expect(appLifecycle.onSettingLoaded).toHaveBeenCalledOnce(); + expect(openDatabase).toHaveBeenCalledOnce(); + expect(appLifecycle.onSettingLoaded.mock.invocationCallOrder[0]).toBeLessThan( + openDatabase.mock.invocationCallOrder[0] + ); + } + } + ); + it("reports a database preparation failure at the application boundary", async () => { const initialiseDatabase = vi.fn(async () => false); const log = vi.fn(); diff --git a/test/e2e-obsidian/README.md b/test/e2e-obsidian/README.md index daf382c5..6d14b597 100644 --- a/test/e2e-obsidian/README.md +++ b/test/e2e-obsidian/README.md @@ -74,6 +74,7 @@ After changing plug-in source, use the focused wrapper rather than invoking a sc ```bash npm run test:e2e:obsidian:focused -- settings-ui +npm run test:e2e:obsidian:focused -- configuration-encryption npm run test:e2e:obsidian:focused -- two-vault-sync npm run test:e2e:obsidian:focused -- stale-file-restart npm run test:e2e:obsidian:focused -- folder-batch @@ -111,6 +112,8 @@ The underlying `test:e2e:obsidian:` scripts remain available for an im `test:e2e:obsidian:onboarding-invitation` starts an unconfigured temporary Vault with no plug-in data and verifies that startup selects Commonlib's new-Vault recommendations, offers the setup wizard without opening it, and does not scan Vault files automatically. It checks the invitation action and introduction in mobile test mode, then reopens the wizard from Quick Setup in either settings interface. This scenario owns the unconfigured-startup boundary only; configured compatibility review remains covered by `settings-ui`, and the setup workflows remain covered by their dedicated scenarios. +`configuration-encryption` needs no remote service. It applies a custom configuration key through the settings interface, restarts the same isolated Vault, and applies a change to only the custom string. It then copies the encrypted settings into a fresh profile without that key and checks masked input, wrong-input retry, cancellation without a settings write or database initialisation, re-enabling for another attempt, access to the settings tab, and restoration after a further restart. Connection, E2EE, profile, and independent ID values must remain unchanged. These checks establish ordinary Apply and restart behaviour, without simulating process termination between the device-key and settings writes. + `test:e2e:obsidian:dialog-mounts` starts a temporary real Obsidian session and exercises remote selection and CouchDB settings through `SetupManager`, plus Setup URI entry through the registered command. It verifies the compatibility pause and remote-size review, the distinction between a central data-storage server and P2P signalling, the explicit tested and untested CouchDB save actions, the internal-API warning, the Setup URI controls, automatic adjustment when differences are limited to compatible chunk settings, and both manual configuration-mismatch routes. The same session opens the live log and generated full report, reaches the `Hatch` recovery controls, writes and removes its own persistent log, and runs the missing-chunk recreation and file-verification actions against the empty disposable Vault. It captures representative desktop and mobile dialogues, checks the mobile layout and vertically stacked actions, closes each route through its normal controls, and verifies that each mounted operation settles without an error. It does not apply a remote configuration, contact a remote service, or claim to repair a deliberately damaged database. `test:e2e:obsidian:settings-ui` starts with a pending compatibility review and verifies the dedicated pause summary, its detailed explanation, and the explicit resume action in a temporary real Obsidian session. It captures the desktop summary and the iPhone-sized summary and detail dialogues; the mobile checks cover viewport containment, horizontal overflow, safe-area containment, and the close control's touch target. It confirms that the acknowledged internal version advances only after the review is accepted, and checks that the Change Log contains no acknowledgement control. It then enables Advanced mode and persists one numeric Advanced setting. On Obsidian before 1.13, this covers the imperative settings fallback used by the `SettingSpec` proof. On Obsidian 1.13 or later, it verifies the task-oriented landing order, the separate Synchronisation group containing Remote Configuration and Sync Settings, and the General Settings group containing Appearance, Logging, and Extra menus. It reopens and cancels onboarding from Quick Setup, opens all 14 nested settings pages, searches globally for the Advanced control, captures the landing page, search result, Advanced page, and mobile landing page, and verifies that the value remains after the settings dialogue is closed and reopened. The mobile landing check confirms that Remote Configuration is reachable without initial scrolling. Finally, it selects the Synchronisation Settings page and verifies that the deletion panel still exposes the effective 'Keep empty folder' setting without presenting the legacy `trashInsteadDelete` control, whose value no longer changes Obsidian deletion behaviour. diff --git a/test/e2e-obsidian/scripts/configuration-encryption.ts b/test/e2e-obsidian/scripts/configuration-encryption.ts new file mode 100644 index 00000000..2db9d6b5 --- /dev/null +++ b/test/e2e-obsidian/scripts/configuration-encryption.ts @@ -0,0 +1,395 @@ +import assert from "node:assert/strict"; +import { mkdir, readFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { Locator, Page } from "playwright"; +import { evalObsidianJson } from "../runner/cli.ts"; +import { discoverObsidianCli, requireObsidianBinary } from "../runner/environment.ts"; +import { createE2eObsidianDeviceLocalState, waitForLiveSyncCoreReady } from "../runner/liveSyncWorkflow.ts"; +import { startObsidianLiveSyncSession, type ObsidianLiveSyncSession } from "../runner/session.ts"; +import { openLiveSyncSettings, waitForVisibleObsidianDialogue, withObsidianPage } from "../runner/ui.ts"; +import { createTemporaryVault } from "../runner/vault.ts"; + +const coreExpression = "app.plugins.plugins['obsidian-livesync'].core"; +const firstKey = "synthetic-first-configuration-key"; +const secondKey = "synthetic-second-configuration-key"; +const diagnosticsDirectory = process.env.E2E_OBSIDIAN_DIAGNOSTICS_DIR ?? "/tmp/obsidian-livesync-e2e"; +const screenshots: string[] = []; +const saveFailureMessage = + "Configuration encryption could not be saved. Verify the saved settings and device key before retrying."; +const secrets = { + couchDB_URI: "https://synthetic.invalid", + couchDB_PASSWORD: "synthetic-connection-password", + passphrase: "%synthetic-e2ee-passphrase", + idDerivationKey: "ab".repeat(32), + profile: "sls+http://synthetic-user:synthetic-password@synthetic.invalid/?db=synthetic-database", +}; + +async function readSecrets(cli: string, session: ObsidianLiveSyncSession): Promise { + return await evalObsidianJson( + cli, + `(()=>{ + const settings=${coreExpression}.services.setting.currentSettings(); + return JSON.stringify({couchDB_URI:settings.couchDB_URI,couchDB_PASSWORD:settings.couchDB_PASSWORD, + passphrase:settings.passphrase,idDerivationKey:settings.idDerivationKey, + profile:settings.remoteConfigurations.inactive.uri}); + })()`, + session.cliEnv + ); +} + +async function capture(locator: Locator, filename: string): Promise { + await mkdir(diagnosticsDirectory, { recursive: true }); + const path = join(diagnosticsDirectory, filename); + await locator.screenshot({ path, animations: "disabled", caret: "hide" }); + screenshots.push(path); +} + +async function assertPendingLoad( + cli: string, + env: NodeJS.ProcessEnv, + expectedKey: string | null = null +): Promise { + const state = await evalObsidianJson( + cli, + `(()=>{ + const core=${coreExpression}; + return JSON.stringify({databaseReady:core.services.database.isDatabaseReady(), + tabRegistered:core.modules.some(module=>!!module.settingTab), + key:localStorage.getItem('ls-setting-passphrase')}); + })()`, + env + ); + assert.deepEqual(state, { databaseReady: false, tabRegistered: false, key: expectedKey }); +} + +async function applyCustomKey(session: ObsidianLiveSyncSession, key: string, changeMode: boolean): Promise { + await withObsidianPage(session.remoteDebuggingPort, async (page) => { + try { + const navigator = await openLiveSyncSettings(page); + const root = await navigator.openPage("Power users"); + if (changeMode) { + await root + .locator(".setting-item") + .filter({ hasText: "Encrypting sensitive configuration items" }) + .getByRole("combobox") + .selectOption("LOCALSTORAGE"); + } + await root.locator('input[type="password"]:visible').fill(key); + await capture( + navigator.dialogue, + changeMode ? "02-custom-before-apply.png" : "04-custom-key-only-edit.png" + ); + await root.getByRole("button", { name: "Apply", exact: true }).click(); + await page.waitForFunction(`(()=>{ + const core=${coreExpression}; + const tab=core.modules.find(module=>module.settingTab)?.settingTab; + return tab && !tab.isDirty('configPassphrase') && !tab.isDirty('configPassphraseStore') && + core.settings.configPassphraseStore==='LOCALSTORAGE' && + localStorage.getItem('ls-setting-passphrase')===${JSON.stringify(key)}; + })()`); + await capture(navigator.dialogue, changeMode ? "03-custom-applied.png" : "05-custom-key-only-applied.png"); + await navigator.close(); + } catch (error) { + await mkdir(diagnosticsDirectory, { recursive: true }); + await page.screenshot({ + path: join(diagnosticsDirectory, "configuration-apply.failure.png"), + fullPage: true, + }); + throw error; + } + }); +} + +async function assertDefaultSettings(session: ObsidianLiveSyncSession): Promise { + await withObsidianPage(session.remoteDebuggingPort, async (page) => { + assert.equal(await page.locator('.modal-container input[type="password"]').count(), 0); + const navigator = await openLiveSyncSettings(page); + const root = await navigator.openPage("Power users"); + const store = root + .locator(".setting-item") + .filter({ hasText: "Encrypting sensitive configuration items" }) + .getByRole("combobox"); + assert.equal(await store.inputValue(), ""); + assert.equal(await root.locator('input[type="password"]:visible').isDisabled(), true); + await capture(navigator.dialogue, "01-default-after-restart.png"); + await navigator.close(); + }); +} + +async function assertRejectedEmptyKey(cli: string, session: ObsidianLiveSyncSession, dataPath: string): Promise { + const before = await readFile(dataPath, "utf8"); + await withObsidianPage(session.remoteDebuggingPort, async (page) => { + const navigator = await openLiveSyncSettings(page); + const root = await navigator.openPage("Power users"); + await root.locator('input[type="password"]:visible').fill(""); + await root.getByRole("button", { name: "Apply", exact: true }).click(); + let notice: Locator | undefined; + const deadline = Date.now() + 5000; + while (Date.now() < deadline && !notice) { + for (const candidate of page.context().pages()) { + const matching = candidate.locator(".notice").filter({ hasText: saveFailureMessage }).last(); + if (await matching.isVisible()) { + notice = matching; + break; + } + } + if (!notice) await new Promise((resolve) => setTimeout(resolve, 100)); + } + assert.ok(notice, "The rejected Apply did not display its failure notice"); + await capture(notice, "06-apply-failure-notice.png"); + const state = await evalObsidianJson( + cli, + `(()=>{ + const core=${coreExpression}; + const tab=core.modules.find(module=>module.settingTab)?.settingTab; + return JSON.stringify({key:localStorage.getItem('ls-setting-passphrase'), + store:core.settings.configPassphraseStore,dirty:tab.isDirty('configPassphrase')}); + })()`, + session.cliEnv + ); + assert.deepEqual(state, { key: secondKey, store: "LOCALSTORAGE", dirty: true }); + assert.equal(await readFile(dataPath, "utf8"), before); + await capture(navigator.dialogue, "07-apply-failure-edits-retained.png"); + await root.locator('input[type="password"]:visible').fill(secondKey); + await navigator.close(); + }); +} + +async function submitKey(page: Page, title: string, key: string): Promise { + const dialogue = await waitForVisibleObsidianDialogue(page, title); + await dialogue.locator('input[type="password"]').fill(key); + await dialogue.getByRole("button", { name: "OK", exact: true }).click(); +} + +async function applyAskMode(session: ObsidianLiveSyncSession): Promise { + await withObsidianPage(session.remoteDebuggingPort, async (page) => { + const navigator = await openLiveSyncSettings(page); + const root = await navigator.openPage("Power users"); + await root + .locator(".setting-item") + .filter({ hasText: "Encrypting sensitive configuration items" }) + .getByRole("combobox") + .selectOption("ASK_AT_LAUNCH"); + await root.getByRole("button", { name: "Apply", exact: true }).click(); + await submitKey(page, "Configuration passphrase", secondKey); + await page.waitForFunction(`(()=>{ + const core=${coreExpression}; + const tab=core.modules.find(module=>module.settingTab)?.settingTab; + return tab && !tab.isDirty('configPassphraseStore') && core.settings.configPassphraseStore==='ASK_AT_LAUNCH'; + })()`); + await navigator.close(); + }); +} + +async function main(): Promise { + const binary = requireObsidianBinary(); + const cli = discoverObsidianCli(); + if (!cli.binary) throw new Error(`Could not find obsidian-cli. Checked: ${cli.checked.join(", ")}`); + const cliBinary = cli.binary; + const firstVault = await createTemporaryVault("obsidian-livesync-configuration-source-"); + let secondVault: Awaited> | undefined; + let session: ObsidianLiveSyncSession | undefined; + try { + session = await startObsidianLiveSyncSession({ + binary, + cliBinary, + vault: firstVault, + pluginData: { + doctorProcessedVersion: "1.0.35", + isConfigured: true, + remoteType: "", + usePowerUserMode: true, + liveSync: false, + periodicReplication: false, + syncOnStart: false, + syncOnSave: false, + syncOnFileOpen: false, + syncOnEditorSave: false, + syncAfterMerge: false, + displayLanguage: "", + notifyThresholdOfRemoteStorageSize: -1, + }, + localStorageEntries: createE2eObsidianDeviceLocalState(firstVault.name), + }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + await evalObsidianJson( + cliBinary, + `(async()=>{ + const core=${coreExpression}; + await core.services.setting.applyPartial({encrypt:true,idDerivationVersion:1, + idDerivationKey:${JSON.stringify(secrets.idDerivationKey)},passphrase:${JSON.stringify(secrets.passphrase)}, + couchDB_URI:${JSON.stringify(secrets.couchDB_URI)},couchDB_DBNAME:'synthetic-database', + couchDB_PASSWORD:${JSON.stringify(secrets.couchDB_PASSWORD)},activeConfigurationId:'', + remoteConfigurations:{inactive:{id:'inactive',name:'Synthetic profile', + uri:${JSON.stringify(secrets.profile)},isEncrypted:false}}},true); + return JSON.stringify(true); + })()`, + session.cliEnv + ); + await session.app.stop(); + session = undefined; + session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: firstVault }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + await evalObsidianJson( + cliBinary, + `(async()=>{ + await ${coreExpression}.services.setting.saveSettingData(); + return JSON.stringify(true); + })()`, + session.cliEnv + ); + await session.app.stop(); + session = undefined; + session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: firstVault }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + await assertDefaultSettings(session); + console.log( + "Configuration encryption: Default save and restart preserved all protected values without a key prompt." + ); + await applyCustomKey(session, firstKey, true); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + console.log("Configuration encryption: mode and custom key applied through the settings interface."); + await session.app.stop(); + session = undefined; + + session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: firstVault }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + await applyCustomKey(session, secondKey, false); + console.log("Configuration encryption: restart and custom-key-only Apply preserved all protected values."); + const sourceDataPath = join(firstVault.path, ".obsidian/plugins/obsidian-livesync/data.json"); + const encryptedData = await readFile(sourceDataPath, "utf8"); + const saved = JSON.parse(encryptedData) as Record; + assert.equal(saved.configPassphraseStore, "LOCALSTORAGE"); + assert.equal(saved.idDerivationKey, ""); + assert.equal(saved.passphrase, ""); + assert.equal(saved.couchDB_PASSWORD, ""); + for (const value of Object.values(secrets)) assert.equal(encryptedData.includes(value), false); + await assertRejectedEmptyKey(cliBinary, session, sourceDataPath); + console.log( + "Configuration encryption: rejected empty-key Apply displayed a notice and retained the device key, saved data, and pending edit." + ); + await session.app.stop(); + session = undefined; + + secondVault = await createTemporaryVault("obsidian-livesync-configuration-copy-"); + const copyDataPath = join(secondVault.path, ".obsidian/plugins/obsidian-livesync/data.json"); + session = await startObsidianLiveSyncSession({ + binary, + cliBinary, + vault: secondVault, + pluginData: saved, + localStorageEntries: createE2eObsidianDeviceLocalState(secondVault.name), + lifecycle: { + afterPluginLoad: async ({ remoteDebuggingPort, cliEnv }) => { + await withObsidianPage(remoteDebuggingPort, async (page) => { + try { + const missingKey = await waitForVisibleObsidianDialogue(page, "Configuration passphrase"); + const missingInput = missingKey.locator('input[type="password"]'); + assert.equal(await missingInput.getAttribute("type"), "password"); + await missingInput.fill("synthetic-wrong-key"); + await capture(missingKey.locator(".modal"), "08-missing-custom-key.png"); + await assertPendingLoad(cliBinary, cliEnv); + const beforeInput = await readFile(copyDataPath, "utf8"); + await submitKey(page, "Configuration passphrase", "synthetic-wrong-key"); + const retry = await waitForVisibleObsidianDialogue( + page, + "Configuration could not be decrypted" + ); + await retry.locator('input[type="password"]').fill(secondKey); + await capture(retry.locator(".modal"), "09-wrong-key-retry.png"); + await assertPendingLoad(cliBinary, cliEnv); + assert.equal(await readFile(copyDataPath, "utf8"), beforeInput); + await retry.getByRole("button", { name: "Cancel", exact: true }).click(); + await retry.waitFor({ state: "hidden" }); + await assertPendingLoad(cliBinary, cliEnv); + assert.equal(await readFile(copyDataPath, "utf8"), beforeInput); + + await evalObsidianJson( + cliBinary, + `(async()=>{ + await app.plugins.disablePlugin('obsidian-livesync'); + await app.plugins.enablePlugin('obsidian-livesync'); + return JSON.stringify(true); + })()`, + cliEnv + ); + await submitKey(page, "Configuration passphrase", secondKey); + } catch (error) { + await mkdir(diagnosticsDirectory, { recursive: true }); + await page.screenshot({ + path: join(diagnosticsDirectory, "configuration-unlock.failure.png"), + fullPage: true, + }); + throw error; + } + }); + }, + }, + }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + await withObsidianPage(session.remoteDebuggingPort, async (page) => { + const navigator = await openLiveSyncSettings(page); + await navigator.openPage("Power users"); + await capture(navigator.dialogue, "10-unlocked-settings.png"); + await navigator.close(); + }); + await session.app.stop(); + session = undefined; + + session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: secondVault }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + console.log( + "Configuration encryption: Apply and custom-key-only Apply survive restart; copied settings unlock after wrong input, cancellation, and retry; the validated key survives another restart." + ); + await applyAskMode(session); + await session.app.stop(); + session = undefined; + session = await startObsidianLiveSyncSession({ + binary, + cliBinary, + vault: secondVault, + lifecycle: { + afterPluginLoad: async ({ remoteDebuggingPort, cliEnv }) => { + await withObsidianPage(remoteDebuggingPort, async (page) => { + const dialogue = await waitForVisibleObsidianDialogue(page, "Configuration passphrase"); + const input = dialogue.locator('input[type="password"]'); + assert.equal(await input.getAttribute("type"), "password"); + await input.fill(secondKey); + await assertPendingLoad(cliBinary, cliEnv, secondKey); + await capture(dialogue.locator(".modal"), "11-ask-at-launch-masked.png"); + await dialogue.getByRole("button", { name: "OK", exact: true }).click(); + }); + }, + }, + }); + await waitForLiveSyncCoreReady(cliBinary, session.cliEnv); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + await evalObsidianJson( + cliBinary, + `(async()=>{ + await ${coreExpression}.services.setting.saveSettingData(); + return JSON.stringify(true); + })()`, + session.cliEnv + ); + assert.deepEqual(await readSecrets(cliBinary, session), secrets); + console.log( + "Configuration encryption: ASK input was masked and the validated key was reused for an ordinary save in this launch." + ); + console.log(`Configuration encryption screenshots: ${JSON.stringify(screenshots)}`); + } finally { + if (session) await session.app.stop(); + await firstVault.dispose(); + if (secondVault) await secondVault.dispose(); + } +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.stack : error); + process.exitCode = 1; +}); diff --git a/test/e2e-obsidian/scripts/run-focused.ts b/test/e2e-obsidian/scripts/run-focused.ts index 84e3b733..090e50be 100644 --- a/test/e2e-obsidian/scripts/run-focused.ts +++ b/test/e2e-obsidian/scripts/run-focused.ts @@ -13,6 +13,7 @@ const focusedScenarios = new Set([ "document-history-nav", "document-history-restore", "settings-ui", + "configuration-encryption", "review-harness", "p2p-pane", "vault-reflection", diff --git a/updates.md b/updates.md index f94c2092..d2145a78 100644 --- a/updates.md +++ b/updates.md @@ -12,6 +12,13 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi ## Unreleased +### Configuration Encryption + +#### Fixed + +- We now apply the settings for protecting sensitive configuration together, so a successful Apply keeps the saved settings under the selected passphrase. If Apply fails, the edits remain available to retry. (#1238) +- We can now enter a missing or unusable custom configuration passphrase at start-up to unlock protected settings. Cancelling the custom-key recovery prompt preserves the encrypted configuration and stops that start-up attempt; headless command-line start-up cannot complete that prompt when recovery input is required. (#1239) + ## 1.0.35 5th October, 2026