diff --git a/infrastructure/services/CloudSyncManager.ts b/infrastructure/services/CloudSyncManager.ts index ba6302061..b6c209641 100644 --- a/infrastructure/services/CloudSyncManager.ts +++ b/infrastructure/services/CloudSyncManager.ts @@ -272,8 +272,11 @@ export class CloudSyncManager { connection: ProviderConnection, authAttemptId?: number, assertCanPersist?: () => void, + preserveStoredSecrets = false, ): Promise { - return saveProviderConnectionImpl.call(this, provider, connection, authAttemptId, assertCanPersist); + return saveProviderConnectionImpl.call( + this, provider, connection, authAttemptId, assertCanPersist, preserveStoredSecrets, + ); } private loadFromStorage(key: string): T | null { diff --git a/infrastructure/services/cloudSync/stateAndSecurityMethods.ts b/infrastructure/services/cloudSync/stateAndSecurityMethods.ts index 0a03f665d..fe3249999 100644 --- a/infrastructure/services/cloudSync/stateAndSecurityMethods.ts +++ b/infrastructure/services/cloudSync/stateAndSecurityMethods.ts @@ -404,6 +404,7 @@ export async function saveProviderConnectionImpl(this: any, connection: ProviderConnection, authAttemptId?: number, assertCanPersist?: () => void, + preserveStoredSecrets = false, ): Promise { const key = providerConnectionStorageKey(provider); // Use write-specific counter so status-only updates cannot discard @@ -413,6 +414,19 @@ export async function saveProviderConnectionImpl(this: any, const pending = (async () => { const encrypted = await encryptProviderSecrets(connection); assertCanPersist?.(); + // A no-op only updates sync metadata. Preserve the latest stored secret + // fields so an unseen peer-window credential refresh is not overwritten. + if (preserveStoredSecrets) { + const latest = this.loadProviderConnection(provider) as ProviderConnection; + assertCanPersist?.(); + for (const field of ['tokens', 'config', 'credential'] as const) { + if (Object.prototype.hasOwnProperty.call(latest, field)) { + (encrypted as any)[field] = latest[field]; + } else { + delete (encrypted as any)[field]; + } + } + } // Only persist if no newer save has started during the async gap if ( seq === this.providerWriteSeq[provider] && diff --git a/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts b/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts index c43dfa126..6d3ca42e4 100644 --- a/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts +++ b/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts @@ -625,6 +625,28 @@ test("guarded provider saves cannot recreate state cleared during an await", asy queueMicrotask(() => { providerChanged = true; }); await assert.rejects(connectionSave, /provider changed/); assert.equal(stored.size, 0); + + providerChanged = false; + const latestConnection = { + provider: "github" as const, + status: "connected" as const, + tokens: { accessToken: "fresh" }, + resourceId: "resource-7", + }; + const metadataManager = { + providerWriteSeq: { github: 0 }, + loadProviderConnection: () => latestConnection, + saveToStorage: (_storageKey: string, value: typeof latestConnection) => { + stored.set("connection", value); + }, + }; + await saveProviderConnectionImpl.call(metadataManager, "github", { + ...latestConnection, + tokens: { accessToken: "old" }, + lastSyncVersion: 7, + }, undefined, assertProviderUnchanged, true); + const savedConnection = stored.get("connection") as typeof latestConnection; + assert.equal(savedConnection.tokens.accessToken, "fresh"); } finally { console.warn = originalWarn; } @@ -1236,9 +1258,13 @@ test("no-op sync does not persist stale credentials after a concurrent provider assertCanPersist?.(); anchorWrites += 1; }, - saveProviderConnection: async () => { + saveProviderConnection: async (_provider: CloudProvider, _connection: unknown, + _authAttemptId?: number, assertCanPersist?: () => void, + preserveStoredSecrets?: boolean) => { + assert.equal(preserveStoredSecrets, true); saveCalls += 1; manager.providerWriteSeq.github += 1; + assertCanPersist?.(); if (raceAt === "connection") { manager.providerWriteSeq.github += 1; manager.providerDecryptSeq.github += 1; @@ -1255,14 +1281,22 @@ test("no-op sync does not persist stale credentials after a concurrent provider }; const result = (await syncAllProvidersImpl.call(manager, localPayload)).get("github"); - assert.equal(result?.success, false, raceAt); - assert.match(result?.error ?? "", /Provider connection changed/, raceAt); - assert.equal(saveCalls, raceAt === "connection" ? 1 : 0, raceAt); - assert.equal(anchorWrites, raceAt === "connection" ? 1 : 0, raceAt); + const sameResourceTokenRefresh = raceAt === "storage"; + assert.equal(result?.success, sameResourceTokenRefresh, `${raceAt}: ${result?.error ?? "no error"}`); + if (sameResourceTokenRefresh) { + assert.equal(result?.action, "none"); + assert.equal(storedToken, "fresh"); + } else { + assert.match(result?.error ?? "", /Provider connection changed/, raceAt); + } + assert.equal(saveCalls, raceAt === "connection" || sameResourceTokenRefresh ? 1 : 0, raceAt); + assert.equal(anchorWrites, raceAt === "connection" || sameResourceTokenRefresh ? 1 : 0, raceAt); assert.equal(uploads, 0, raceAt); - assert.equal(manager.state.providers.github.status, "error", raceAt); + assert.equal(manager.state.providers.github.status, + sameResourceTokenRefresh ? "connected" : "error", raceAt); assert.equal(manager.providerDecryptSeq.github, - raceAt === "connection" ? 2 : raceAt === "anchor" ? 1 : 0, raceAt); + raceAt === "connection" ? 2 : raceAt === "anchor" || sameResourceTokenRefresh ? 1 : 0, + raceAt); if (raceAt === "connection") { assert.equal(manager.state.providers.github.tokens.accessToken, "fresh"); } @@ -1346,6 +1380,72 @@ test("no-op sync accepts its own token refresh during the remote check", async ( } }); +test("peer no-op metadata updates do not fail an identical provider sync", async () => { + const originalDecryptPayload = EncryptionService.decryptPayload; + const localPayload = payload("local"); + let storedConnection = { + provider: "github" as const, + status: "connected" as const, + tokens: { accessToken: "same" }, + resourceId: "resource-7", + lastSyncVersion: 7, + }; + let saves = 0; + let uploads = 0; + EncryptionService.decryptPayload = async () => localPayload; + + try { + const manager = { + masterPassword: "pw", + adapters: new Map(), + providerDecryptSeq: { github: 0 }, + providerWriteSeq: { github: 0 }, + state: { + securityState: "UNLOCKED", + providers: { github: { enabled: true, connected: true, ...storedConnection } }, + lastError: null, + syncState: "IDLE", + syncStrategy: "smartMerge", + localVersion: 7, + deviceId: "local-device", + deviceName: "Local", + }, + getConnectedAdapter: async () => ({ provider: "github", resourceId: "resource-7" }), + updateProviderStatus: () => {}, + emit: () => {}, + checkProviderConflict: async () => ({ + conflict: false, + remoteFile: remoteFile("github", 7, 700), + }), + loadProviderConnection: () => storedConnection, + loadSyncBase: async () => localPayload, + saveSyncBase: async () => {}, + saveSyncAnchor: async () => { + storedConnection = { ...storedConnection, lastSyncVersion: 8 }; + }, + saveProviderConnection: async () => { + saves += 1; + manager.providerWriteSeq.github += 1; + }, + saveSyncConfig: () => {}, + uploadToProvider: async () => { + uploads += 1; + return { success: true, provider: "github" as const, action: "upload" as const }; + }, + exitBlockedState: () => {}, + notifyStateChange: () => {}, + }; + + const result = (await syncAllProvidersImpl.call(manager, localPayload)).get("github"); + assert.equal(result?.success, true); + assert.equal(result?.action, "none"); + assert.equal(saves, 1); + assert.equal(uploads, 0); + } finally { + EncryptionService.decryptPayload = originalDecryptPayload; + } +}); + test("no-op sync does not upload when saving a newer remote base fails", async () => { const originalDecryptPayload = EncryptionService.decryptPayload; const originalEncryptPayload = EncryptionService.encryptPayload; diff --git a/infrastructure/services/cloudSync/syncAllStorageMethods.ts b/infrastructure/services/cloudSync/syncAllStorageMethods.ts index 84b6aad94..89563b943 100644 --- a/infrastructure/services/cloudSync/syncAllStorageMethods.ts +++ b/infrastructure/services/cloudSync/syncAllStorageMethods.ts @@ -101,6 +101,38 @@ function providerConnectionIdentity(connection: ProviderConnection | undefined): }); } +function persistedProviderIdentity(provider: CloudProvider, connection: ProviderConnection): string { + const config = connection.config; + let configIdentity: unknown = config; + if (provider === 'webdav' && config && typeof config === 'object' && 'authType' in config) { + configIdentity = { + endpoint: config.endpoint, + authType: config.authType, + username: config.username, + allowInsecure: config.allowInsecure, + }; + } else if (provider === 's3' && config && typeof config === 'object' && 'bucket' in config) { + configIdentity = { + endpoint: config.endpoint, + region: config.region, + bucket: config.bucket, + accessKeyId: config.accessKeyId, + prefix: config.prefix, + forcePathStyle: config.forcePathStyle, + allowInsecure: config.allowInsecure, + }; + } + return JSON.stringify({ + accountId: connection.account?.id, + resourceId: connection.resourceId, + config: configIdentity, + credential: connection.credential, + hasConnectionData: connection.tokens != null + || Object.prototype.hasOwnProperty.call(connection, 'config') + || connection.credential != null, + }); +} + async function loadRawSyncBase(this: any, provider?: CloudProvider): Promise { const key = this.state.unlockedKey?.derivedKey; if (!key || typeof this.loadFromStorage !== 'function') return null; @@ -637,7 +669,8 @@ export async function syncAllProvidersImpl(this: any, // its event has advanced providerWriteSeq here. if ( storedProviderFingerprint !== null - && JSON.stringify(this.loadProviderConnection(provider)) !== storedProviderFingerprint + && persistedProviderIdentity(provider, this.loadProviderConnection(provider)) + !== storedProviderFingerprint ) { throw new ProviderConnectionChangedDuringSyncError( 'Provider connection changed during sync; retry with its latest credentials', @@ -689,7 +722,7 @@ export async function syncAllProvidersImpl(this: any, // while in-memory credentials still lag the stored connection. if (typeof this.loadProviderConnection === 'function') { const rawStoredConnection = this.loadProviderConnection(provider); - storedProviderFingerprint = JSON.stringify(rawStoredConnection); + storedProviderFingerprint = persistedProviderIdentity(provider, rawStoredConnection); const storedConnection = await decryptProviderSecrets(rawStoredConnection); assertSyncSecurityGeneration(this, syncSecurityGeneration); assertProviderConnectionUnchanged(); @@ -753,7 +786,9 @@ export async function syncAllProvidersImpl(this: any, originalProviderWriteSeq == null ? undefined : originalProviderWriteSeq + 1, ); }; - await this.saveProviderConnection(provider, connection, undefined, assertCanPersistConnection); + await this.saveProviderConnection( + provider, connection, undefined, assertCanPersistConnection, true, + ); assertSyncSecurityGeneration(this, syncSecurityGeneration); if ( originalProviderWriteSeq != null