Merge pull request #1245 from vrtmrz/fix/configuration-encryption-apply

Preserve configuration encryption edits when applying settings
This commit is contained in:
vorotamoroz
2026-10-13 21:37:05 +09:00
committed by GitHub
20 changed files with 1639 additions and 948 deletions
+5 -1
View File
@@ -988,10 +988,14 @@ If this option is enabled, PouchDB will hold the connection open for 60 seconds,
Setting key: configPassphraseStore 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 #### Passphrase of sensitive configuration items
Setting key: configPassphrase 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 ### 4. Developer
+6
View File
@@ -117,6 +117,12 @@ When a notice identifies an unknown feature, update this device and every other
## Setup and settings questions ## 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 ### 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. 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.
+2 -5
View File
@@ -106,13 +106,10 @@ export const obsidianRules = {
* @type {(base:string) => import("eslint").Linter.RulesRecord} * @type {(base:string) => import("eslint").Linter.RulesRecord}
*/ */
export const ImportAliasRules = (base) => ({ export const ImportAliasRules = (base) => ({
"@dword-design/import-alias/prefer-alias": [ "livesync-imports/prefer-source-alias": [
"error", "error",
{ {
aliasForSubpaths: true, sourceRoot: `${base}/src`,
alias: {
"@": `${base}/src`,
},
}, },
], ],
}); });
+5 -2
View File
@@ -4,7 +4,7 @@ import globals from "globals";
import { defineConfig, globalIgnores } from "eslint/config"; import { defineConfig, globalIgnores } from "eslint/config";
import * as sveltePlugin from "eslint-plugin-svelte"; import * as sveltePlugin from "eslint-plugin-svelte";
import svelteParser from "svelte-eslint-parser"; import svelteParser from "svelte-eslint-parser";
import importAlias from "@dword-design/eslint-plugin-import-alias"; import importAlias from "./utils/import-alias.mjs";
import { baseRules, ImportAliasRules, obsidianRules } from "./eslint.config.common.mjs"; import { baseRules, ImportAliasRules, obsidianRules } from "./eslint.config.common.mjs";
const warnWhileDev = "off"; // Change to "warn" to enable warnings for rules that are currently disabled. const warnWhileDev = "off"; // Change to "warn" to enable warnings for rules that are currently disabled.
const lintProjects = [ const lintProjects = [
@@ -56,7 +56,10 @@ export default defineConfig([
]), ]),
...sveltePlugin.configs["flat/base"], ...sveltePlugin.configs["flat/base"],
...obsidianmd.configs.recommended, ...obsidianmd.configs.recommended,
importAlias.configs.recommended, {
plugins: { "livesync-imports": importAlias },
rules: { "livesync-imports/prefer-source-alias": "error" },
},
{ {
files: ["**/*.ts"], files: ["**/*.ts"],
languageOptions: { languageOptions: {
+108 -911
View File
File diff suppressed because it is too large Load Diff
+4 -5
View File
@@ -62,6 +62,8 @@
"test:e2e:obsidian:document-history-nav": "tsx test/e2e-obsidian/scripts/document-history-nav.ts", "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: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: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:configuration-encryption-sync": "tsx test/e2e-obsidian/scripts/configuration-encryption-sync.ts",
"test:e2e:obsidian:review-harness": "tsx test/e2e-obsidian/scripts/review-harness.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:p2p-pane": "tsx test/e2e-obsidian/scripts/p2p-pane.ts",
"test:e2e:obsidian:vault-reflection": "tsx test/e2e-obsidian/scripts/vault-reflection.ts", "test:e2e:obsidian:vault-reflection": "tsx test/e2e-obsidian/scripts/vault-reflection.ts",
@@ -122,7 +124,6 @@
"author": "vorotamoroz", "author": "vorotamoroz",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@dword-design/eslint-plugin-import-alias": "^8.1.8",
"@emnapi/core": "1.11.1", "@emnapi/core": "1.11.1",
"@emnapi/runtime": "1.11.1", "@emnapi/runtime": "1.11.1",
"@eslint/js": "^9.39.3", "@eslint/js": "^9.39.3",
@@ -131,7 +132,6 @@
"@types/deno": "^2.5.0", "@types/deno": "^2.5.0",
"@types/diff-match-patch": "^1.0.36", "@types/diff-match-patch": "^1.0.36",
"@types/markdown-it": "^14.1.2", "@types/markdown-it": "^14.1.2",
"@types/micromatch": "^4.0.10",
"@types/node": "^24.10.13", "@types/node": "^24.10.13",
"@types/pouchdb": "^6.4.2", "@types/pouchdb": "^6.4.2",
"@types/pouchdb-adapter-http": "^6.1.6", "@types/pouchdb-adapter-http": "^6.1.6",
@@ -167,7 +167,6 @@
"pouchdb-replication": "^9.0.0", "pouchdb-replication": "^9.0.0",
"pouchdb-utils": "^9.0.0", "pouchdb-utils": "^9.0.0",
"prettier": "3.8.1", "prettier": "3.8.1",
"rollup-plugin-copy": "^3.5.0",
"svelte": "5.56.3", "svelte": "5.56.3",
"svelte-check": "^4.6.0", "svelte-check": "^4.6.0",
"svelte-eslint-parser": "^1.8.0", "svelte-eslint-parser": "^1.8.0",
@@ -192,7 +191,7 @@
"@smithy/types": "^4.14.3", "@smithy/types": "^4.14.3",
"@smithy/util-retry": "^4.4.5", "@smithy/util-retry": "^4.4.5",
"@vrtmrz/browser-ui-kit": "0.1.0", "@vrtmrz/browser-ui-kit": "0.1.0",
"@vrtmrz/livesync-commonlib": "0.1.36", "@vrtmrz/livesync-commonlib": "0.1.39",
"@vrtmrz/obsidian-plugin-kit": "0.1.4", "@vrtmrz/obsidian-plugin-kit": "0.1.4",
"@vrtmrz/ui-interactions": "0.1.2", "@vrtmrz/ui-interactions": "0.1.2",
"diff-match-patch": "^1.0.5", "diff-match-patch": "^1.0.5",
@@ -200,7 +199,7 @@
"markdown-it": "^14.3.2", "markdown-it": "^14.3.2",
"minimatch": "^10.2.5", "minimatch": "^10.2.5",
"obsidian": "^1.13.1", "obsidian": "^1.13.1",
"octagonal-wheels": "^0.1.54", "octagonal-wheels": "^0.1.55",
"qrcode-generator": "^1.4.4", "qrcode-generator": "^1.4.4",
"xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2" "xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2"
}, },
@@ -133,7 +133,7 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
applySetting(keys: AllSettingItemKey[]) { applySetting(keys: AllSettingItemKey[]) {
for (const k of keys) { for (const k of keys) {
if (!this.isDirty(k)) continue; if (!this.isDirty(k)) continue;
if (k in OnDialogSettingsDefault) { if (this.isConfigurationEncryptionSetting(k) || k in OnDialogSettingsDefault) {
// //@ts-ignore // //@ts-ignore
// this.initialSettings[k] = this.editingSettings[k]; // this.initialSettings[k] = this.editingSettings[k];
continue; continue;
@@ -141,21 +141,21 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
this.copySettingValue(this.core.settings, this.editingSettings, k); this.copySettingValue(this.core.settings, this.editingSettings, k);
this.copySettingValue(this.initialSettings, this.core.settings, 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) => const changedKeys = (Object.keys(this.editingSettings ?? {}) as AllSettingItemKey[]).filter((e) =>
this.isDirty(e) this.isDirty(e)
); );
await this.saveConfigurationEncryptionIfDirty(changedKeys);
this.applySetting(changedKeys); this.applySetting(changedKeys);
this.reloadAllSettings(); this.reloadAllSettings();
} }
async saveLocalSetting(key: keyof typeof OnDialogSettingsDefault) { 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") { if (key == "deviceAndVaultName") {
this.services.setting.setDeviceAndVaultName(this.editingSettings?.[key] ?? ""); this.services.setting.setDeviceAndVaultName(this.editingSettings?.[key] ?? "");
this.services.setting.saveDeviceAndVaultName(); this.services.setting.saveDeviceAndVaultName();
@@ -168,10 +168,10 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
*/ */
async saveSettings(keys: AllSettingItemKey[]) { async saveSettings(keys: AllSettingItemKey[]) {
let hasChanged = false; let hasChanged = false;
const appliedKeys = [] as AllSettingItemKey[]; const appliedKeys = keys.filter((k) => this.isDirty(k));
for (const k of keys) { await this.saveConfigurationEncryptionIfDirty(appliedKeys);
if (!this.isDirty(k)) continue; for (const k of appliedKeys) {
appliedKeys.push(k); if (this.isConfigurationEncryptionSetting(k)) continue;
if (k in OnDialogSettingsDefault) { if (k in OnDialogSettingsDefault) {
await this.saveLocalSetting(k as keyof OnDialogSettings); await this.saveLocalSetting(k as keyof OnDialogSettings);
this.copySettingValue(this.initialSettings, this.editingSettings, k); 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]))); .map((e) => Promise.resolve(e.handler(this.editingSettings[e.key])));
await Promise.all(handlers); 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<void> {
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 * Reread all settings and request invalidate
*/ */
reloadAllSettings(skipUpdate: boolean = false) { 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(); const localSetting = this.reloadAllLocalSettings();
this._editingSettings = { ...this.core.settings, ...localSetting }; this._editingSettings = { ...this.core.settings, ...localSetting };
this._editingSettings = { ...this.editingSettings, ...this.computeAllLocalSettings() }; this._editingSettings = { ...this.editingSettings, ...this.computeAllLocalSettings() };
this.initialSettings = { ...this.editingSettings }; 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(); if (!skipUpdate) this.requestUpdate();
} }
@@ -1020,7 +1070,7 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
if (!this.editingSettings.encrypt) { if (!this.editingSettings.encrypt) {
this.editingSettings.passphrase = ""; this.editingSettings.passphrase = "";
} }
this.applyAllSettings(); await this.applyAllSettings();
await this.services.setting.suspendAllSync(); await this.services.setting.suspendAllSync();
await this.services.setting.suspendExtraSync(); await this.services.setting.suspendExtraSync();
this.reloadAllSettings(); this.reloadAllSettings();
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SETTINGS, LOG_LEVEL_NOTICE, REMOTE_COUCHDB } from "@vrtmrz/livesync-commonlib/compat/common/types"; 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 { REMOTE_RESOURCE_KINDS } from "@vrtmrz/livesync-commonlib/replication";
import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions";
const settingsInitialisationMocks = vi.hoisted(() => ({ const settingsInitialisationMocks = vi.hoisted(() => ({
applySettingsWithInitialisationChoice: vi.fn(), applySettingsWithInitialisationChoice: vi.fn(),
@@ -75,6 +76,8 @@ beforeEach(() => {
settingsInitialisationMocks.applySettingsWithInitialisationChoice.mockReset(); settingsInitialisationMocks.applySettingsWithInitialisationChoice.mockReset();
loggerMocks.Logger.mockClear(); loggerMocks.Logger.mockClear();
vi.mocked($msg).mockClear(); vi.mocked($msg).mockClear();
vi.mocked(compatGlobal.localStorage.getItem).mockReset().mockReturnValue(null);
vi.mocked(compatGlobal.localStorage.setItem).mockReset();
}); });
describe("ObsidianLiveSyncSettingTab passphrase verification", () => { describe("ObsidianLiveSyncSettingTab passphrase verification", () => {
@@ -260,6 +263,9 @@ describe("ObsidianLiveSyncSettingTab Fresh Start Wipe", () => {
describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => { describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => {
function createSettingsTab() { function createSettingsTab() {
const saveSettingData = vi.fn(async () => undefined); 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 confirmWithMessage = vi.fn();
const plugin = { const plugin = {
app: {}, app: {},
@@ -276,8 +282,13 @@ describe("ObsidianLiveSyncSettingTab pending-setting initialisation", () => {
setting: { setting: {
saveSettingData, saveSettingData,
getDeviceAndVaultName: vi.fn(() => ""), getDeviceAndVaultName: vi.fn(() => ""),
suspendAllSync,
suspendExtraSync,
}, },
}, },
rebuilder: {
$performRebuildDB: performRebuildDB,
},
}, },
}; };
const tab = new ObsidianLiveSyncSettingTab({} as never, plugin as never); 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, "isPassphraseValid").mockResolvedValue(true);
vi.spyOn(tab, "checkWorkingPassphrase").mockResolvedValue(true); vi.spyOn(tab, "checkWorkingPassphrase").mockResolvedValue(true);
const closeSetting = vi.spyOn(tab, "closeSetting").mockImplementation(() => undefined); 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 () => { 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(tab.core.settings.handleFilenameCaseSensitive).toBe(false);
expect(closeSetting).not.toHaveBeenCalled(); 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", () => { describe("ObsidianLiveSyncSettingTab declarative settings boundary", () => {
@@ -463,4 +525,82 @@ describe("ObsidianLiveSyncSettingTab declarative settings boundary", () => {
expect(first).not.toHaveBeenCalled(); expect(first).not.toHaveBeenCalled();
expect(replacement).toHaveBeenCalledOnce(); 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<void>((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");
});
}); });
@@ -17,9 +17,66 @@ vi.mock("@/common/translation", () => ({
setLang: vi.fn(), setLang: vi.fn(),
})); }));
vi.mock("@vrtmrz/livesync-commonlib/compat/worker/bgWorker", () => ({
initialiseWorkerModule: vi.fn(),
}));
import { ModuleLiveSyncMain } from "./ModuleLiveSyncMain.ts"; import { ModuleLiveSyncMain } from "./ModuleLiveSyncMain.ts";
describe("ModuleLiveSyncMain", () => { 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<void>((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 () => { it("reports a database preparation failure at the application boundary", async () => {
const initialiseDatabase = vi.fn(async () => false); const initialiseDatabase = vi.fn(async () => false);
const log = vi.fn(); const log = vi.fn();
+7 -1
View File
@@ -74,6 +74,8 @@ After changing plug-in source, use the focused wrapper rather than invoking a sc
```bash ```bash
npm run test:e2e:obsidian:focused -- settings-ui npm run test:e2e:obsidian:focused -- settings-ui
npm run test:e2e:obsidian:focused -- configuration-encryption
npm run test:e2e:obsidian:focused -- configuration-encryption-sync
npm run test:e2e:obsidian:focused -- two-vault-sync npm run test:e2e:obsidian:focused -- two-vault-sync
npm run test:e2e:obsidian:focused -- stale-file-restart npm run test:e2e:obsidian:focused -- stale-file-restart
npm run test:e2e:obsidian:focused -- folder-batch npm run test:e2e:obsidian:focused -- folder-batch
@@ -111,6 +113,8 @@ The underlying `test:e2e:obsidian:<scenario>` 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. `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. It also checks changes from custom and ASK modes to Default through the settings interface, and recovery from a wrong saved device key, including cancellation, the validated replacement key, and another restart.
`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: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. `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.
@@ -134,7 +138,9 @@ The Harness also measures ID generation with fixed in-memory data on desktop and
`test:e2e:obsidian:p2p-pane` starts one configured CouchDB-only session with no P2P profile and separate configured P2P sessions for desktop and mobile. It proves that the command remains registered while the retired command, automatic pane, and ribbon entry without a P2P configuration are absent. For the configured P2P profiles, it verifies that the desktop ribbon is available, the current status command reaches the pane without it opening at start-up, checks its connection control and horizontal layout, and captures unobstructed desktop and mobile screenshots. The mobile session uses a fresh Vault, profile, and Obsidian process, enters `app.emulateMobile(true)` through `lifecycle.beforePluginStart`, and requires the P2P view to belong to the right drawer rather than inheriting desktop workspace state. It deliberately uses no relay or peer: replacement of the active replicator is covered by focused unit tests, the Deno and Compose CLI P2P lifecycle suite covers the headless transport, and `p2p-setup-uri-workflow` owns the visible transfer path between two real Obsidian sessions. `test:e2e:obsidian:p2p-pane` starts one configured CouchDB-only session with no P2P profile and separate configured P2P sessions for desktop and mobile. It proves that the command remains registered while the retired command, automatic pane, and ribbon entry without a P2P configuration are absent. For the configured P2P profiles, it verifies that the desktop ribbon is available, the current status command reaches the pane without it opening at start-up, checks its connection control and horizontal layout, and captures unobstructed desktop and mobile screenshots. The mobile session uses a fresh Vault, profile, and Obsidian process, enters `app.emulateMobile(true)` through `lifecycle.beforePluginStart`, and requires the P2P view to belong to the right drawer rather than inheriting desktop workspace state. It deliberately uses no relay or peer: replacement of the active replicator is covered by focused unit tests, the Deno and Compose CLI P2P lifecycle suite covers the headless transport, and `p2p-setup-uri-workflow` owns the visible transfer path between two real Obsidian sessions.
`test:e2e:obsidian:local-suite` builds the plug-in and, unless `LIVESYNC_CLI_COMMAND` selects an external CLI, the local LiveSync CLI. It then runs discovery, smoke, the onboarding invitation, Svelte dialogue mounting, revision repair, settings UI, the Review Harness, the P2P status pane, Vault reflection, CouchDB upload and manual setup, CLI-to-Obsidian synchronisation, Object Storage upload and Setup URI and QR round trips, P2P Setup URI round-trip, startup scan, provisioned CouchDB Setup URI, two-vault synchronisation, Hidden File Sync, Customisation Sync, internal Metadata Doctor, and setting Markdown export in sequence. Start the local CouchDB, RustFS, and P2P relay fixtures before running it, or use `test:e2e:obsidian:local-suite:services` to let the wrapper stop leftover fixtures, start fresh fixtures, and stop them again after the run. `test:e2e:obsidian:configuration-encryption-sync` requires only the CouchDB fixture configured through `.test.env` or the process environment. It changes the configuration protection key through the real settings interface, restarts the source Vault, and sends a note with E2EE enabled. A fresh Vault receives the encrypted settings without a saved device key, cancels and retries recovery, and restarts with the validated key. Both Vaults then exchange exact note bytes through CouchDB. The scenario checks the restored connection credentials, E2EE passphrase, ID key, remote Metadata, and Chunks, and removes its temporary Vaults, profiles, and unique remote database.
`test:e2e:obsidian:local-suite` builds the plug-in and, unless `LIVESYNC_CLI_COMMAND` selects an external CLI, the local LiveSync CLI. It then runs discovery, smoke, the onboarding invitation, Svelte dialogue mounting, revision repair, settings UI, configuration encryption and its CouchDB synchronisation workflow, the Review Harness, the P2P status pane, Vault reflection, CouchDB upload and manual setup, CLI-to-Obsidian synchronisation, Object Storage upload and Setup URI and QR round trips, P2P Setup URI round-trip, startup scan, provisioned CouchDB Setup URI, two-vault synchronisation, Hidden File Sync, Customisation Sync, internal Metadata Doctor, and setting Markdown export in sequence. Start the local CouchDB, RustFS, and P2P relay fixtures before running it, or use `test:e2e:obsidian:local-suite:services` to let the wrapper stop leftover fixtures, start fresh fixtures, and stop them again after the run.
`test:e2e:obsidian:couchdb-upload` reuses the CouchDB variables from `.test.env` or the process environment. It expects a reachable CouchDB service, creates a unique database, starts from configured plug-in data without the device-local compatibility marker, and verifies that the marker is initialised without a compatibility dialogue, reminder, or runtime pause. It then creates a note in real Obsidian, commits it into the local database, runs one-shot synchronisation, and verifies that the remote database contains both the Metadata document and its Chunks. `test:e2e:obsidian:couchdb-upload` reuses the CouchDB variables from `.test.env` or the process environment. It expects a reachable CouchDB service, creates a unique database, starts from configured plug-in data without the device-local compatibility marker, and verifies that the marker is initialised without a compatibility dialogue, reminder, or runtime pause. It then creates a note in real Obsidian, commits it into the local database, runs one-shot synchronisation, and verifies that the remote database contains both the Metadata document and its Chunks.
@@ -0,0 +1,332 @@
import assert from "node:assert/strict";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { evalObsidianJson } from "../runner/cli.ts";
import {
assertCouchDbReachable,
createCouchDbDatabase,
deleteCouchDbDatabase,
loadCouchDbConfig,
makeUniqueDatabaseName,
waitForCouchDbDocs,
} from "../runner/couchdb.ts";
import { discoverObsidianCli, requireObsidianBinary } from "../runner/environment.ts";
import {
configureCouchDb,
createE2eCouchDbPluginData,
createE2eObsidianDeviceLocalState,
prepareRemote,
pushLocalChanges,
waitForLiveSyncCoreReady,
waitForLocalDatabaseEntry,
} 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-sync-configuration-key-a";
const secondKey = "synthetic-sync-configuration-key-b";
const dataPassphrase = "synthetic-note-encryption-passphrase";
const idKey = "cd".repeat(32);
const sourcePath = "E2E/configuration-source.md";
const replyPath = "E2E/configuration-reply.md";
const sourceContent = "# Configuration key rotation\n日本語とEnglishの内容を保持します。\n".repeat(200);
const replyContent = "# Configuration key recovery reply\n復旧した端末から送信します。\n".repeat(200);
const diagnosticsDirectory = process.env.E2E_OBSIDIAN_DIAGNOSTICS_DIR ?? "/tmp/obsidian-livesync-e2e";
process.env.E2E_OBSIDIAN_CLI_TIMEOUT_MS ??= "30000";
async function applyKey(session: ObsidianLiveSyncSession, key: string, changeMode: boolean): Promise<void> {
await withObsidianPage(session.remoteDebuggingPort, async (page) => {
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 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 navigator.close();
});
}
async function assertConnection(
cli: string,
session: ObsidianLiveSyncSession,
expected: Record<string, unknown>
): Promise<void> {
const settings = await evalObsidianJson(
cli,
`(()=>{
const s=${coreExpression}.services.setting.currentSettings();
return JSON.stringify({uri:s.couchDB_URI,user:s.couchDB_USER,password:s.couchDB_PASSWORD,
database:s.couchDB_DBNAME,encrypt:s.encrypt,passphrase:s.passphrase,idKey:s.idDerivationKey,
store:s.configPassphraseStore,key:localStorage.getItem('ls-setting-passphrase')});
})()`,
session.cliEnv
);
assert.deepEqual(settings, expected);
}
async function createNote(cli: string, session: ObsidianLiveSyncSession, path: string, content: string): Promise<void> {
await evalObsidianJson(
cli,
`(async()=>{
if(!(await app.vault.adapter.exists('E2E'))) await app.vault.createFolder('E2E');
await app.vault.create(${JSON.stringify(path)},${JSON.stringify(content)});
return JSON.stringify(true);
})()`,
session.cliEnv
);
await waitForLocalDatabaseEntry(cli, session.cliEnv, path);
}
async function assertNote(
cli: string,
session: ObsidianLiveSyncSession,
vaultPath: string,
path: string,
content: string
): Promise<void> {
// Return only a boolean through the CLI; compare the complete Vault file below.
const matches = await evalObsidianJson<boolean>(
cli,
`(async()=>{
const path=${JSON.stringify(path)};
const expected=${JSON.stringify(content)};
const deadline=Date.now()+20000;
while(Date.now()<deadline){
const actual=await app.vault.adapter.read(path).catch(()=>null);
if(actual===expected) return JSON.stringify(true);
await new Promise(resolve=>setTimeout(resolve,250));
}
throw new Error('Timed out waiting for the received note');
})()`,
session.cliEnv
);
assert.equal(matches, true);
assert.equal(await readFile(join(vaultPath, path), "utf8"), content);
}
async function main(): Promise<void> {
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 couchDb = await loadCouchDbConfig();
const dbName = makeUniqueDatabaseName(couchDb.dbPrefix, "configuration-encryption");
const sourceVault = await createTemporaryVault("obsidian-configuration-sync-source-");
let receiverVault: Awaited<ReturnType<typeof createTemporaryVault>> | undefined;
let session: ObsidianLiveSyncSession | undefined;
let remoteCreated = false;
let stage = "source-startup";
const connection = {
uri: couchDb.uri,
user: couchDb.username,
password: couchDb.password,
database: dbName,
encrypt: true,
passphrase: dataPassphrase,
idKey,
store: "LOCALSTORAGE",
key: secondKey,
};
try {
await assertCouchDbReachable(couchDb);
await createCouchDbDatabase(couchDb, dbName);
remoteCreated = true;
session = await startObsidianLiveSyncSession({
binary,
cliBinary,
vault: sourceVault,
pluginData: createE2eCouchDbPluginData(
{ ...couchDb, dbName },
{
doctorProcessedVersion: "1.0.35",
usePowerUserMode: true,
idDerivationVersion: 0,
}
),
localStorageEntries: createE2eObsidianDeviceLocalState(sourceVault.name),
});
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
stage = "source-configuration";
await configureCouchDb(
cliBinary,
session.cliEnv,
{ ...couchDb, dbName },
{
doctorProcessedVersion: "1.0.35",
usePowerUserMode: true,
encrypt: true,
passphrase: dataPassphrase,
idDerivationVersion: 1,
idDerivationKey: idKey,
}
);
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
await prepareRemote(cliBinary, session.cliEnv);
stage = "source-key-rotation";
await applyKey(session, firstKey, true);
await applyKey(session, secondKey, false);
const dataPath = join(sourceVault.path, ".obsidian/plugins/obsidian-livesync/data.json");
const encryptedData = await readFile(dataPath, "utf8");
assert.equal(encryptedData.includes(dataPassphrase), false);
assert.equal(encryptedData.includes(idKey), false);
assert.equal(encryptedData.includes(couchDb.password), false);
const saved = JSON.parse(encryptedData) as Record<string, unknown>;
await session.app.stop();
session = undefined;
session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: sourceVault });
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
await assertConnection(cliBinary, session, connection);
stage = "source-upload-after-restart";
await createNote(cliBinary, session, sourcePath, sourceContent);
await assertNote(cliBinary, session, sourceVault.path, sourcePath, sourceContent);
const sourceEntry = await waitForLocalDatabaseEntry(cliBinary, session.cliEnv, sourcePath);
await pushLocalChanges(cliBinary, session.cliEnv);
const docs = await waitForCouchDbDocs(couchDb, dbName, (docs) => {
const ids = new Set(docs.map((doc) => doc._id));
return ids.has(sourceEntry.id) && sourceEntry.children.every((id) => ids.has(id));
});
assert.ok(sourceEntry.children.length > 0);
assert.equal(
docs.some((doc) => typeof doc.data === "string" && doc.data.includes("Configuration key rotation")),
false
);
console.log(
"Configuration encryption sync: key rotation and restart retained credentials, E2EE, and the ID key; Metadata and encrypted Chunks reached CouchDB."
);
await session.app.stop();
session = undefined;
stage = "receiver-key-recovery";
receiverVault = await createTemporaryVault("obsidian-configuration-sync-receiver-");
const receiverDataPath = join(receiverVault.path, ".obsidian/plugins/obsidian-livesync/data.json");
session = await startObsidianLiveSyncSession({
binary,
cliBinary,
vault: receiverVault,
pluginData: saved,
localStorageEntries: createE2eObsidianDeviceLocalState(receiverVault.name),
lifecycle: {
afterPluginLoad: async ({ remoteDebuggingPort, cliEnv }) => {
await withObsidianPage(remoteDebuggingPort, async (page) => {
const dialogue = await waitForVisibleObsidianDialogue(page, "Configuration passphrase");
assert.equal(await dialogue.locator('input[type="password"]').getAttribute("type"), "password");
const before = await readFile(receiverDataPath, "utf8");
await dialogue.getByRole("button", { name: "Cancel", exact: true }).click();
await dialogue.waitFor({ state: "hidden" });
const pending = await evalObsidianJson(
cliBinary,
`(()=>{
const core=${coreExpression};
return JSON.stringify({databaseReady:core.services.database.isDatabaseReady(),
tabRegistered:core.modules.some(module=>!!module.settingTab)});
})()`,
cliEnv
);
assert.deepEqual(pending, { databaseReady: false, tabRegistered: false });
assert.equal(await readFile(receiverDataPath, "utf8"), before);
await evalObsidianJson(
cliBinary,
`(async()=>{
await app.plugins.disablePlugin('obsidian-livesync');
await app.plugins.enablePlugin('obsidian-livesync');
return JSON.stringify(true);
})()`,
cliEnv
);
const retry = await waitForVisibleObsidianDialogue(page, "Configuration passphrase");
await retry.locator('input[type="password"]').fill(secondKey);
await mkdir(diagnosticsDirectory, { recursive: true });
await retry.locator(".modal").screenshot({
path: join(diagnosticsDirectory, "configuration-sync-unlock.png"),
animations: "disabled",
caret: "hide",
});
await retry.getByRole("button", { name: "OK", exact: true }).click();
});
},
},
});
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
await assertConnection(cliBinary, session, connection);
await session.app.stop();
session = undefined;
session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: receiverVault });
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
await assertConnection(cliBinary, session, connection);
await pushLocalChanges(cliBinary, session.cliEnv);
stage = "receiver-transfer-after-restart";
await assertNote(cliBinary, session, receiverVault.path, sourcePath, sourceContent);
await createNote(cliBinary, session, replyPath, replyContent);
await assertNote(cliBinary, session, receiverVault.path, replyPath, replyContent);
await pushLocalChanges(cliBinary, session.cliEnv);
const replyEntry = await waitForLocalDatabaseEntry(cliBinary, session.cliEnv, replyPath);
await waitForCouchDbDocs(couchDb, dbName, (docs) => docs.some((doc) => doc._id === replyEntry.id));
await session.app.stop();
session = undefined;
session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: sourceVault });
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
await assertConnection(cliBinary, session, connection);
await pushLocalChanges(cliBinary, session.cliEnv);
stage = "source-receive-reply";
await assertNote(cliBinary, session, sourceVault.path, replyPath, replyContent);
console.log(
"Configuration encryption sync: copied settings survived cancellation, key recovery, and restart; both real Obsidian Vaults exchanged exact note bytes through CouchDB."
);
} catch (error) {
await mkdir(diagnosticsDirectory, { recursive: true });
if (session) {
await withObsidianPage(session.remoteDebuggingPort, async (page) => {
await page.screenshot({
path: join(diagnosticsDirectory, "configuration-sync.failure.png"),
fullPage: true,
});
}).catch(() => undefined);
const state = await evalObsidianJson(
cliBinary,
`(()=>{
const core=${coreExpression};
return JSON.stringify({databaseReady:core?.services.database.isDatabaseReady(),
appReady:core?.services.appLifecycle.isReady(),
mode:core?.settings?.configPassphraseStore});
})()`,
session.cliEnv
).catch(() => ({ stateReadFailed: true }));
await writeFile(
join(diagnosticsDirectory, "configuration-sync.failure.json"),
JSON.stringify({ stage, state }, null, 2) + "\n"
);
}
throw error;
} finally {
try {
if (session) await session.app.stop();
} finally {
try {
await sourceVault.dispose();
if (receiverVault) await receiverVault.dispose();
} finally {
if (remoteCreated) await deleteCouchDbDatabase(couchDb, dbName);
}
}
}
}
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.stack : error);
process.exitCode = 1;
});
@@ -0,0 +1,573 @@
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 wrongSavedKey = "synthetic-wrong-saved-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<typeof secrets> {
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<void> {
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<void> {
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<void> {
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,
screenshot = "01-default-after-restart.png"
): Promise<void> {
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, screenshot);
await navigator.close();
});
}
async function assertRejectedEmptyKey(cli: string, session: ObsidianLiveSyncSession, dataPath: string): Promise<void> {
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<void> {
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<void> {
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 applyDefaultMode(
session: ObsidianLiveSyncSession,
screenshot = "12-ask-to-default-before-restart.png"
): Promise<void> {
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("");
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('configPassphraseStore') && core.settings.configPassphraseStore==='';
})()`);
await capture(navigator.dialogue, screenshot);
await navigator.close();
});
}
async function assertSavedConfigurationKey(cli: string, env: NodeJS.ProcessEnv, expectedKey: string): Promise<void> {
const key = await evalObsidianJson(cli, `JSON.stringify(localStorage.getItem('ls-setting-passphrase'))`, env);
assert.equal(key, expectedKey);
}
async function assertLoadedLocalStorageConfiguration(
cli: string,
env: NodeJS.ProcessEnv,
expectedKey: string
): Promise<void> {
const state = await evalObsidianJson(
cli,
`(()=>{
const core=${coreExpression};
return JSON.stringify({databaseReady:core.services.database.isDatabaseReady(),
tabRegistered:core.modules.some(module=>!!module.settingTab),
store:core.settings.configPassphraseStore,
key:localStorage.getItem('ls-setting-passphrase')});
})()`,
env
);
assert.deepEqual(state, {
databaseReady: true,
tabRegistered: true,
store: "LOCALSTORAGE",
key: expectedKey,
});
}
async function main(): Promise<void> {
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<ReturnType<typeof createTemporaryVault>> | undefined;
let retryVault: Awaited<ReturnType<typeof createTemporaryVault>> | 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<string, unknown>;
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 applyDefaultMode(session, "18-custom-to-default-before-restart.png");
assert.deepEqual(await readSecrets(cliBinary, session), secrets);
await assertSavedConfigurationKey(cliBinary, session.cliEnv, secondKey);
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 assertSavedConfigurationKey(cliBinary, session.cliEnv, secondKey);
await assertDefaultSettings(session, "19-custom-to-default-after-restart.png");
console.log(
"Configuration encryption: changing the custom key mode to Default preserved protected values without a prompt and retained the device key after restart."
);
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."
);
await applyDefaultMode(session);
assert.deepEqual(await readSecrets(cliBinary, session), secrets);
await assertSavedConfigurationKey(cliBinary, session.cliEnv, secondKey);
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);
await assertSavedConfigurationKey(cliBinary, session.cliEnv, secondKey);
await assertDefaultSettings(session, "13-ask-to-default-after-restart.png");
console.log(
"Configuration encryption: changing ASK_AT_LAUNCH to Default through settings restored protected values without a prompt and retained the device key after restart."
);
await session.app.stop();
session = undefined;
retryVault = await createTemporaryVault("obsidian-livesync-configuration-wrong-saved-key-");
const retryDataPath = join(retryVault.path, ".obsidian/plugins/obsidian-livesync/data.json");
session = await startObsidianLiveSyncSession({
binary,
cliBinary,
vault: retryVault,
pluginData: saved,
localStorageEntries: {
...createE2eObsidianDeviceLocalState(retryVault.name),
"ls-setting-passphrase": wrongSavedKey,
},
lifecycle: {
afterPluginLoad: async ({ remoteDebuggingPort, cliEnv }) => {
await withObsidianPage(remoteDebuggingPort, async (page) => {
try {
const retry = await waitForVisibleObsidianDialogue(
page,
"Configuration could not be decrypted"
);
const input = retry.locator('input[type="password"]');
assert.equal(await input.getAttribute("type"), "password");
await assertPendingLoad(cliBinary, cliEnv, wrongSavedKey);
const beforeCancellation = await readFile(retryDataPath, "utf8");
await capture(retry.locator(".modal"), "14-saved-wrong-key-retry-prompt.png");
await retry.getByRole("button", { name: "Cancel", exact: true }).click();
await retry.waitFor({ state: "hidden" });
await assertPendingLoad(cliBinary, cliEnv, wrongSavedKey);
assert.equal(await readFile(retryDataPath, "utf8"), beforeCancellation);
await evalObsidianJson(
cliBinary,
`(async()=>{
await app.plugins.disablePlugin('obsidian-livesync');
await app.plugins.enablePlugin('obsidian-livesync');
return JSON.stringify(true);
})()`,
cliEnv
);
const retryAfterCancellation = await waitForVisibleObsidianDialogue(
page,
"Configuration could not be decrypted"
);
const retryInput = retryAfterCancellation.locator('input[type="password"]');
assert.equal(await retryInput.getAttribute("type"), "password");
await assertPendingLoad(cliBinary, cliEnv, wrongSavedKey);
await retryInput.fill(secondKey);
await capture(
retryAfterCancellation.locator(".modal"),
"15-saved-wrong-key-correct-retry.png"
);
await assertPendingLoad(cliBinary, cliEnv, wrongSavedKey);
await retryAfterCancellation.getByRole("button", { name: "OK", exact: true }).click();
} catch (error) {
await mkdir(diagnosticsDirectory, { recursive: true });
await page.screenshot({
path: join(diagnosticsDirectory, "configuration-saved-key-retry.failure.png"),
fullPage: true,
});
throw error;
}
});
},
},
});
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
assert.deepEqual(await readSecrets(cliBinary, session), secrets);
await assertLoadedLocalStorageConfiguration(cliBinary, session.cliEnv, secondKey);
await withObsidianPage(session.remoteDebuggingPort, async (page) => {
assert.equal(await page.locator('.modal-container input[type="password"]').count(), 0);
const navigator = await openLiveSyncSettings(page);
await navigator.openPage("Power users");
await capture(navigator.dialogue, "16-saved-wrong-key-unlocked-settings.png");
await navigator.close();
});
await session.app.stop();
session = undefined;
session = await startObsidianLiveSyncSession({ binary, cliBinary, vault: retryVault });
await waitForLiveSyncCoreReady(cliBinary, session.cliEnv);
assert.deepEqual(await readSecrets(cliBinary, session), secrets);
await assertLoadedLocalStorageConfiguration(cliBinary, session.cliEnv, secondKey);
await withObsidianPage(session.remoteDebuggingPort, async (page) => {
assert.equal(await page.locator('.modal-container input[type="password"]').count(), 0);
const navigator = await openLiveSyncSettings(page);
await navigator.openPage("Power users");
await capture(navigator.dialogue, "17-validated-key-after-restart.png");
await navigator.close();
});
console.log(
"Configuration encryption: a saved wrong key remained intact after cancellation; the correct retry restored protected values, persisted the validated key, and survived another restart."
);
console.log(`Configuration encryption screenshots: ${JSON.stringify(screenshots)}`);
} finally {
if (session) await session.app.stop();
await firstVault.dispose();
if (secondVault) await secondVault.dispose();
if (retryVault) await retryVault.dispose();
}
}
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.stack : error);
process.exitCode = 1;
});
+5
View File
@@ -18,6 +18,11 @@ const testSteps: Step[] = [
{ name: "conflict dialogue policy", args: ["run", "test:e2e:obsidian:conflict-dialog-policy"] }, { name: "conflict dialogue policy", args: ["run", "test:e2e:obsidian:conflict-dialog-policy"] },
{ name: "revision repair", args: ["run", "test:e2e:obsidian:revision-repair"] }, { name: "revision repair", args: ["run", "test:e2e:obsidian:revision-repair"] },
{ name: "settings UI", args: ["run", "test:e2e:obsidian:settings-ui"] }, { name: "settings UI", args: ["run", "test:e2e:obsidian:settings-ui"] },
{ name: "configuration encryption", args: ["run", "test:e2e:obsidian:configuration-encryption"] },
{
name: "configuration encryption synchronisation",
args: ["run", "test:e2e:obsidian:configuration-encryption-sync"],
},
{ name: "Review Harness", args: ["run", "test:e2e:obsidian:review-harness"] }, { name: "Review Harness", args: ["run", "test:e2e:obsidian:review-harness"] },
{ name: "P2P status pane", args: ["run", "test:e2e:obsidian:p2p-pane"] }, { name: "P2P status pane", args: ["run", "test:e2e:obsidian:p2p-pane"] },
{ name: "vault reflection", args: ["run", "test:e2e:obsidian:vault-reflection"] }, { name: "vault reflection", args: ["run", "test:e2e:obsidian:vault-reflection"] },
+2
View File
@@ -13,6 +13,8 @@ const focusedScenarios = new Set([
"document-history-nav", "document-history-nav",
"document-history-restore", "document-history-restore",
"settings-ui", "settings-ui",
"configuration-encryption",
"configuration-encryption-sync",
"review-harness", "review-harness",
"p2p-pane", "p2p-pane",
"vault-reflection", "vault-reflection",
+12
View File
@@ -12,6 +12,13 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi
## Unreleased ## 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)
### Localisation ### Localisation
#### Fixed #### Fixed
@@ -20,6 +27,11 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi
- Remote database lock warnings now use the existing translations consistently. - Remote database lock warnings now use the existing translations consistently.
- Fast Setup follows the selected display language while preserving saved choices across restarts and language changes. - Fast Setup follows the selected display language while preserving saved choices across restarts and language changes.
### Maintenance
- Build copying and import alias checks now use repository-owned helpers, removing the vulnerable `braces` dependency from development tooling.
- Updated compatible development dependencies with available security fixes.
### Acknowledgements ### Acknowledgements
Thank you for your contributions! Thank you for your contributions!
+42
View File
@@ -0,0 +1,42 @@
import { access, copyFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import type { Plugin } from "vite";
const BUILD_FILES = ["manifest.json", "main.js", "styles.css"] as const;
function hasErrorCode(error: unknown, code: string): boolean {
return typeof error === "object" && error !== null && "code" in error && error.code === code;
}
export function copyBuildFiles(destinations: readonly string[], sourceDirectory = process.cwd()): Plugin {
return {
name: "copy-build-files",
async writeBundle() {
let copied = false;
for (const destination of destinations) {
let destinationCreated = false;
for (const file of BUILD_FILES) {
const source = join(sourceDirectory, file);
try {
await access(source);
} catch (error) {
if (hasErrorCode(error, "ENOENT")) continue;
throw error;
}
if (!destinationCreated) {
await mkdir(destination, { recursive: true });
destinationCreated = true;
}
const target = join(destination, file);
await copyFile(source, target);
if (!copied) console.log("copied:");
copied = true;
console.log(` ${source} → ${target}`);
}
}
if (!copied) console.log("no items to copy");
},
};
}
+107
View File
@@ -0,0 +1,107 @@
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Plugin } from "vite";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { copyBuildFiles } from "./copy-build-files";
const BUILD_FILES = ["manifest.json", "main.js", "styles.css"] as const;
let temporaryDirectory: string;
function createCopyPlugin(sourceDirectory: string, destinations: string[]): Plugin {
return copyBuildFiles(destinations, sourceDirectory);
}
async function runWriteBundle(plugin: Plugin): Promise<void> {
const hook = plugin.writeBundle as
| ((this: Plugin) => unknown)
| { handler?: (this: Plugin) => unknown }
| undefined;
const handler = typeof hook === "function" ? hook : hook?.handler;
if (!handler) {
throw new Error("The copy plug-in does not define a writeBundle hook");
}
await handler.call(plugin);
}
describe("build file copying", () => {
beforeEach(async () => {
temporaryDirectory = await mkdtemp(join(tmpdir(), "livesync-copy-build-files-"));
});
afterEach(async () => {
await rm(temporaryDirectory, { recursive: true, force: true });
});
it("does nothing when no destinations are configured", async () => {
const plugin = createCopyPlugin(join(temporaryDirectory, "missing-source"), []);
await expect(runWriteBundle(plugin)).resolves.toBeUndefined();
});
it("copies the fixed build files to nested destinations and overwrites them on repeated builds", async () => {
const sourceDirectory = join(temporaryDirectory, "build");
const destinations = [
join(temporaryDirectory, "vault-one", ".obsidian", "plugins", "livesync"),
join(temporaryDirectory, "vault-two", "nested", ".obsidian", "plugins", "livesync"),
];
await mkdir(sourceDirectory, { recursive: true });
await Promise.all(BUILD_FILES.map((file) => writeFile(join(sourceDirectory, file), `first ${file}`)));
await mkdir(destinations[0], { recursive: true });
await writeFile(join(destinations[0], "manifest.json"), "stale manifest");
const plugin = createCopyPlugin(sourceDirectory, destinations);
expect(plugin.writeBundle).toBeDefined();
await runWriteBundle(plugin);
for (const destination of destinations) {
for (const file of BUILD_FILES) {
await expect(readFile(join(destination, file), "utf8")).resolves.toBe(`first ${file}`);
}
}
await writeFile(join(sourceDirectory, "main.js"), "second main.js");
await runWriteBundle(plugin);
for (const destination of destinations) {
await expect(readFile(join(destination, "main.js"), "utf8")).resolves.toBe("second main.js");
}
});
it("skips missing source files", async () => {
const sourceDirectory = join(temporaryDirectory, "partial-build");
const destination = join(temporaryDirectory, "vault", ".obsidian", "plugins", "livesync");
await mkdir(sourceDirectory, { recursive: true });
await writeFile(join(sourceDirectory, "manifest.json"), "manifest");
await runWriteBundle(createCopyPlugin(sourceDirectory, [destination]));
await expect(readFile(join(destination, "manifest.json"), "utf8")).resolves.toBe("manifest");
await expect(readFile(join(destination, "main.js"), "utf8")).rejects.toMatchObject({ code: "ENOENT" });
await expect(readFile(join(destination, "styles.css"), "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
it("propagates source path errors", async () => {
const invalidSourceDirectory = join(temporaryDirectory, "source-is-a-file");
await writeFile(invalidSourceDirectory, "not a directory");
await expect(
runWriteBundle(createCopyPlugin(invalidSourceDirectory, [join(temporaryDirectory, "vault")]))
).rejects.toMatchObject({ code: "ENOTDIR" });
});
it("propagates destination errors", async () => {
const sourceDirectory = join(temporaryDirectory, "build");
const destinationParent = join(temporaryDirectory, "destination-is-a-file");
await mkdir(sourceDirectory, { recursive: true });
await writeFile(join(sourceDirectory, "manifest.json"), "manifest");
await writeFile(destinationParent, "not a directory");
await expect(
runWriteBundle(createCopyPlugin(sourceDirectory, [join(destinationParent, "nested")]))
).rejects.toMatchObject({ code: "ENOTDIR" });
});
});
+62
View File
@@ -0,0 +1,62 @@
import path from "node:path";
/**
* @param {string} sourcePath
* @param {string} filename
* @param {string} cwd
* @param {string} sourceRoot
* @returns {string | null}
*/
export function resolveSourceAlias(sourcePath, filename, cwd, sourceRoot = "./src") {
if (!/^(?:\.\/)?\.\.(?:\/|$)/u.test(sourcePath)) return null;
const paths = /^[A-Za-z]:[\\/]|^\\\\/u.test(filename) ? path.win32 : path;
const root = paths.resolve(cwd, sourceRoot);
const importedPath = paths.resolve(paths.dirname(filename), sourcePath);
const relative = paths.relative(root, importedPath);
if (relative === ".." || relative.startsWith(`..${paths.sep}`) || paths.isAbsolute(relative)) return null;
return relative ? `@/${relative.split(paths.sep).join("/")}` : "@";
}
/** @type {import("eslint").Rule.RuleModule} */
const preferSourceAlias = {
meta: {
type: "suggestion",
fixable: "code",
docs: { description: "Prefer the source alias for relative parent imports within this repository" },
schema: [
{
type: "object",
properties: { sourceRoot: { type: "string" } },
additionalProperties: false,
},
],
messages: {
parentImport: "Unexpected parent import '{{sourcePath}}'. Use '{{rewrittenImport}}' instead",
},
},
create(context) {
if (context.filename === "<text>" || context.filename === "<input>") return {};
return {
ImportDeclaration(node) {
const sourcePath = node.source.value;
if (typeof sourcePath !== "string") return;
const rewrittenImport = resolveSourceAlias(
sourcePath,
context.filename,
context.cwd,
context.options[0]?.sourceRoot
);
if (rewrittenImport === null) return;
context.report({
node,
messageId: "parentImport",
data: { sourcePath, rewrittenImport },
fix: (fixer) =>
fixer.replaceTextRange([node.source.range[0] + 1, node.source.range[1] - 1], rewrittenImport),
});
},
};
},
};
export default { rules: { "prefer-source-alias": preferSourceAlias } };
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import { Linter } from "eslint";
import tsParser from "@typescript-eslint/parser";
import svelteParser from "svelte-eslint-parser";
import importAlias, { resolveSourceAlias } from "./import-alias.mjs";
import { resolve } from "node:path";
const cwd = process.cwd();
const rule = importAlias.rules["prefer-source-alias"];
function lint(code: string, filename = "src/modules/example.ts") {
const linter = new Linter({ cwd });
return linter.verifyAndFix(
code,
[
{
files: ["**/*.ts", "**/*.svelte"],
languageOptions: {
parser: filename.endsWith(".svelte") ? svelteParser : tsParser,
parserOptions: { parser: tsParser },
},
plugins: { local: { rules: { "prefer-source-alias": rule } } },
rules: {
"local/prefer-source-alias": ["error", { sourceRoot: "./src" }],
},
},
],
{ filename: resolve(cwd, filename) }
);
}
describe("source import aliases", () => {
it.each([
["src/modules/example.ts", "../common/types", "@/common/types"],
["src/modules/example.ts", "./../common/types", "@/common/types"],
["src/modules/example.ts", "..", "@"],
["src/modules/example.ts", "../common/types.js", "@/common/types.js"],
["src/apps/browser/main.ts", "../../common/types", "@/common/types"],
["src/apps/cli/main.ts", "../../common/types", "@/common/types"],
["src/apps/webapp/main.ts", "../../common/types", "@/common/types"],
["src/apps/webpeer/src/main.ts", "../../../common/types", "@/common/types"],
])("rewrites %s parent import %s to %s", (filename, sourcePath, expected) => {
const result = lint(`import type { Value } from '${sourcePath}';`, filename);
expect(result.messages).toEqual([]);
expect(result.fixed).toBe(true);
expect(result.output).toBe(`import type { Value } from '${expected}';`);
});
it.each([
"./helper",
"@/common/types",
"@vrtmrz/livesync-commonlib/common/types",
"node:path",
"../../test/helper",
])("preserves import %s", (sourcePath) => {
const code = `import value from "${sourcePath}";`;
const result = lint(code);
expect(result.messages).toEqual([]);
expect(result.fixed).toBe(false);
expect(result.output).toBe(code);
});
it("does not treat a sibling directory whose name begins with src as source-owned", () => {
const code = 'import value from "../../src-other/helper";';
const result = lint(code);
expect(result.messages).toEqual([]);
expect(result.fixed).toBe(false);
expect(result.output).toBe(code);
});
it("rewrites imports inside Svelte scripts", () => {
const result = lint(
'<script lang="ts">import type { Value } from "../../common/types";</script>',
"src/components/dialog/Example.svelte"
);
expect(result.messages).toEqual([]);
expect(result.fixed).toBe(true);
expect(result.output).toBe('<script lang="ts">import type { Value } from "@/common/types";</script>');
});
it.each([
["C:\\live\\src\\modules\\file.ts", "../common/types", "C:\\live", "@/common/types"],
["C:\\live\\src\\apps\\webpeer\\src\\main.ts", "../../../common/types", "C:\\live", "@/common/types"],
["C:\\live\\src\\modules\\file.ts", "../../src-other/helper", "C:\\live", null],
[
"\\\\server\\share\\live\\src\\modules\\file.ts",
"../common/types",
"\\\\server\\share\\live",
"@/common/types",
],
])("handles Windows source paths in %s", (filename, sourcePath, root, expected) => {
expect(resolveSourceAlias(sourcePath, filename, root)).toBe(expected);
});
it("uses the configured source root", () => {
const result = resolveSourceAlias(
"../common/types",
resolve(cwd, "nested/src/modules/file.ts"),
cwd,
"nested/src"
);
expect(result).toBe("@/common/types");
});
});
+2 -9
View File
@@ -2,11 +2,11 @@ import { defineConfig } from "vitest/config";
import { svelte } from "@sveltejs/vite-plugin-svelte"; import { svelte } from "@sveltejs/vite-plugin-svelte";
import { sveltePreprocess } from "svelte-preprocess"; import { sveltePreprocess } from "svelte-preprocess";
import inlineWorkerPlugin from "esbuild-plugin-inline-worker"; import inlineWorkerPlugin from "esbuild-plugin-inline-worker";
import copy from "rollup-plugin-copy";
import path from "path"; import path from "path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import fs from "node:fs"; import fs from "node:fs";
import { platform } from "node:process"; import { platform } from "node:process";
import { copyBuildFiles } from "./utils/copy-build-files";
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
function readJson(filePath: string) { function readJson(filePath: string) {
@@ -117,14 +117,7 @@ export default defineConfig(({ mode }) => {
compilerOptions: { css: "injected", preserveComments: false }, compilerOptions: { css: "injected", preserveComments: false },
}), }),
copy({ copyBuildFiles(PATH_TEST_INSTALL),
targets: ["manifest.json", "main.js", "styles.css"]
.map((file) => PATH_TEST_INSTALL.map((dest) => ({ src: file, dest: dest })))
.flat(),
// Copy after the build is complete
hook: "writeBundle",
verbose: true,
}),
], ],
resolve: { resolve: {