From b8058474cafd6fd6791143f186228e68fe633372 Mon Sep 17 00:00:00 2001 From: Giovanny Aranda Date: Mon, 9 Nov 2026 17:28:23 +0100 Subject: [PATCH 1/3] feat: sync server profiles and credentials with iCloud --- DockhandMobile.xcodeproj/project.pbxproj | 18 ++ DockhandMobile/App/AppModel.swift | 69 ++++- DockhandMobile/App/DockhandRootView.swift | 8 + DockhandMobile/DockhandMobile.entitlements | 6 + .../Settings/ServerSyncSettingsView.swift | 40 +++ .../Features/Settings/SettingsView.swift | 24 +- DockhandMobile/Localizable.xcstrings | 140 +++++++++ DockhandMobile/Services/KeychainStore.swift | 124 ++++---- .../Services/PreferencesStore.swift | 3 +- .../Services/ServerSyncRecord.swift | 28 ++ DockhandMobile/Services/ServerSyncStore.swift | 265 ++++++++++++++++++ .../Services/SyncedServerCredentials.swift | 53 ++++ DockhandMobileTests/DockhandMobileTests.swift | 100 +++++++ PRIVACY.md | 12 +- docs/icloud-server-sync.md | 52 ++++ project.yml | 3 +- 16 files changed, 869 insertions(+), 76 deletions(-) create mode 100644 DockhandMobile/DockhandMobile.entitlements create mode 100644 DockhandMobile/Features/Settings/ServerSyncSettingsView.swift create mode 100644 DockhandMobile/Services/ServerSyncRecord.swift create mode 100644 DockhandMobile/Services/ServerSyncStore.swift create mode 100644 DockhandMobile/Services/SyncedServerCredentials.swift create mode 100644 docs/icloud-server-sync.md diff --git a/DockhandMobile.xcodeproj/project.pbxproj b/DockhandMobile.xcodeproj/project.pbxproj index 407710d..1cc19de 100644 --- a/DockhandMobile.xcodeproj/project.pbxproj +++ b/DockhandMobile.xcodeproj/project.pbxproj @@ -41,6 +41,10 @@ F854ED0C103528EC1A4988AC /* EnvironmentHeaderBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87D71C8FB475456C871903FB /* EnvironmentHeaderBar.swift */; }; A1D4A7E25C0B4F6E9A3C2B11 /* AdaptiveActionGrid.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1D4A7E25C0B4F6E9A3C2B12 /* AdaptiveActionGrid.swift */; }; FE2A71ABBC45203166737B6E /* DockhandService+Decoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6945D3BE7FFCE50A45EE56BC /* DockhandService+Decoding.swift */; }; + EA2200000000000000000000 /* ServerSyncRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000000; }; + EA2200000000000000000001 /* SyncedServerCredentials.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000001; }; + EA2200000000000000000002 /* ServerSyncStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000002; }; + EA2200000000000000000003 /* ServerSyncSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1100000000000000000003; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -90,6 +94,10 @@ EF70FDD79036BE973B27B8D1 /* ContainerShellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerShellView.swift; sourceTree = ""; }; F0976C1D3ECF9207F9267361 /* .gitkeep */ = {isa = PBXFileReference; lastKnownFileType = text; name = .gitkeep; path = es.lproj/.gitkeep; sourceTree = ""; }; FAE66F21FC999D77378C2C04 /* ContainerShellStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerShellStore.swift; sourceTree = ""; }; + EA1100000000000000000000 /* ServerSyncRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSyncRecord.swift; sourceTree = ""; }; + EA1100000000000000000001 /* SyncedServerCredentials.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncedServerCredentials.swift; sourceTree = ""; }; + EA1100000000000000000002 /* ServerSyncStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSyncStore.swift; sourceTree = ""; }; + EA1100000000000000000003 /* ServerSyncSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSyncSettingsView.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -244,6 +252,9 @@ E5A1342B619AADBFCAF7582E /* DockhandService.swift */, 6945D3BE7FFCE50A45EE56BC /* DockhandService+Decoding.swift */, 08E6CB656D0F64ACB6AFBAC0 /* KeychainStore.swift */, + EA1100000000000000000002 /* ServerSyncStore.swift */, + EA1100000000000000000001 /* SyncedServerCredentials.swift */, + EA1100000000000000000000 /* ServerSyncRecord.swift */, 3A1F5D851E40D36A5154376B /* PreferencesStore.swift */, ); path = Services; @@ -264,6 +275,7 @@ children = ( C0A1B2C3D4E5F60718293A4C /* CustomHeadersEditor.swift */, 13E28C30131DD132BCF62665 /* SettingsView.swift */, + EA1100000000000000000003 /* ServerSyncSettingsView.swift */, ); path = Settings; sourceTree = ""; @@ -382,6 +394,10 @@ A814D3A2D9614875BAFF6C4A /* ImagesStore.swift in Sources */, 4866D6323DEB9849B27209D2 /* ImagesView.swift in Sources */, D259E02834327E2FBF25E5D2 /* KeychainStore.swift in Sources */, + EA2200000000000000000003 /* ServerSyncSettingsView.swift in Sources */, + EA2200000000000000000002 /* ServerSyncStore.swift in Sources */, + EA2200000000000000000001 /* SyncedServerCredentials.swift in Sources */, + EA2200000000000000000000 /* ServerSyncRecord.swift in Sources */, AB608708755DE5D3031BCBCE /* PreferencesStore.swift in Sources */, C0A1B2C3D4E5F60718293A4B /* CustomHeadersEditor.swift in Sources */, B6C034E5D85C2DDB6C9100CC /* SettingsView.swift in Sources */, @@ -516,6 +532,7 @@ "CODE_SIGN_IDENTITY" = "iPhone Developer"; "CURRENT_PROJECT_VERSION" = 18; "DEVELOPMENT_TEAM" = 8DA225EN79; + CODE_SIGN_ENTITLEMENTS = DockhandMobile/DockhandMobile.entitlements; "GENERATE_INFOPLIST_FILE" = NO; "INFOPLIST_FILE" = "DockhandMobile/Info.plist"; "LD_RUNPATH_SEARCH_PATHS" = ( @@ -540,6 +557,7 @@ "CODE_SIGN_IDENTITY" = "iPhone Developer"; "CURRENT_PROJECT_VERSION" = 18; "DEVELOPMENT_TEAM" = 8DA225EN79; + CODE_SIGN_ENTITLEMENTS = DockhandMobile/DockhandMobile.entitlements; "GENERATE_INFOPLIST_FILE" = NO; "INFOPLIST_FILE" = "DockhandMobile/Info.plist"; "LD_RUNPATH_SEARCH_PATHS" = ( diff --git a/DockhandMobile/App/AppModel.swift b/DockhandMobile/App/AppModel.swift index fe968fc..7a71472 100644 --- a/DockhandMobile/App/AppModel.swift +++ b/DockhandMobile/App/AppModel.swift @@ -5,6 +5,7 @@ import Observation struct DockhandConnectionScope: Hashable, Sendable { var profileID: String? var environmentID: Int? + var revision: Int = 0 } enum DockhandServerAddress { @@ -35,6 +36,9 @@ enum DockhandServerAddress { @MainActor @Observable final class AppModel { + let serverSync = ServerSyncStore() + private var syncConnectionRevision = 0 + private var activeSyncPending = false var serverProfiles: [DockhandServerProfile] var selectedProfileID: String? var token: String @@ -91,7 +95,8 @@ final class AppModel { } var normalizedBaseURL: URL? { - selectedProfile.flatMap { DockhandServerAddress.normalizedURL(from: $0.baseURL) } + guard !serverSync.pendingCredentials.contains(selectedProfileID ?? "") else { return nil } + return selectedProfile.flatMap { DockhandServerAddress.normalizedURL(from: $0.baseURL) } } var selectedEnvironment: Components.Schemas.Environment? { @@ -103,7 +108,7 @@ final class AppModel { } var connectionScopeID: String { - "\(selectedProfileID ?? "none"):\(selectedEnvironmentID ?? -1)" + "\(selectedProfileID ?? "none"):\(selectedEnvironmentID ?? -1):\(syncConnectionRevision)" } /// A remembered environment ID alone is not enough: list tasks must restart @@ -113,7 +118,7 @@ final class AppModel { } var connectionScope: DockhandConnectionScope { - DockhandConnectionScope(profileID: selectedProfileID, environmentID: selectedEnvironmentID) + DockhandConnectionScope(profileID: selectedProfileID, environmentID: selectedEnvironmentID, revision: syncConnectionRevision) } /// Builds a service carrying the active profile's token and custom headers. @@ -131,11 +136,14 @@ final class AppModel { } func bootstrap() async { + serverSync.onChange = { [weak self] in self?.applySyncedServers() } + serverSync.refresh() await refreshEnvironments(forceEnvironmentReset: false) } /// Persists the profile immediately. Reconnecting runs in the background so /// an unreachable server never blocks the editor. + @discardableResult func saveServerProfile( profileID: String?, name: String, @@ -143,7 +151,7 @@ final class AppModel { token: String, customHeaders: [DockhandCustomHeader] = [], makeActive: Bool = true - ) { + ) -> Bool { let cleanedName = name.trimmingCharacters(in: .whitespacesAndNewlines) let cleanedURL = baseURLText.trimmingCharacters(in: .whitespacesAndNewlines) let resolvedName = cleanedName.isEmpty ? cleanedURL : cleanedName @@ -151,29 +159,37 @@ final class AppModel { let targetID = profileID ?? UUID().uuidString let profile = DockhandServerProfile(id: targetID, name: resolvedName, baseURL: cleanedURL) + do { + try KeychainStore.installSyncedCredentials( + SyncedServerCredentials(token: DockhandToken.normalized(token), headers: DockhandCustomHeaderValidator.sanitized(customHeaders)), + profileID: targetID) + } catch { + serverSync.error = String(localized: "Could not save credentials. Unlock your device and try again.") + return false + } + if let index = serverProfiles.firstIndex(where: { $0.id == targetID }) { serverProfiles[index] = profile } else { serverProfiles.append(profile) } - serverProfiles.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } PreferencesStore.serverProfiles = serverProfiles - KeychainStore.writeToken(token, profileID: targetID) - KeychainStore.writeCustomHeaders(DockhandCustomHeaderValidator.sanitized(customHeaders), profileID: targetID) + serverSync.save(profile, position: serverProfiles.firstIndex(where: { $0.id == targetID }) ?? 0) if makeActive || selectedProfileID == nil { Task { await selectServerProfile(targetID, forceEnvironmentReset: true) } } + return true } func deleteServerProfile(_ profileID: String) async { + if let profile = serverProfiles.first(where: { $0.id == profileID }) { serverSync.delete(profile) } serverProfiles.removeAll { $0.id == profileID } PreferencesStore.serverProfiles = serverProfiles PreferencesStore.removeSelectedEnvironmentID(for: profileID) PreferencesStore.removeCachedDashboardSnapshots(for: profileID) - KeychainStore.deleteToken(profileID: profileID) - KeychainStore.deleteCustomHeaders(profileID: profileID) + KeychainStore.deleteCredentials(profileID: profileID) if selectedProfileID == profileID { selectedProfileID = serverProfiles.first?.id @@ -188,6 +204,41 @@ final class AppModel { } } + func moveServers(from source: IndexSet, to destination: Int) { + guard (0...serverProfiles.count).contains(destination), + source.allSatisfy({ serverProfiles.indices.contains($0) }) else { return } + var reordered = serverProfiles + let moving = source.sorted().map { reordered[$0] } + for index in source.sorted(by: >) { reordered.remove(at: index) } + reordered.insert(contentsOf: moving, at: destination - source.filter { $0 < destination }.count) + serverProfiles = reordered + PreferencesStore.serverProfiles = reordered + serverSync.reorder(reordered) + } + + private func applySyncedServers() { + let profiles = PreferencesStore.serverProfiles + let active = profiles.first(where: { $0.id == selectedProfileID }) ?? profiles.first + let pending = serverSync.pendingCredentials.contains(active?.id ?? "") + let newToken = pending ? "" : active.flatMap { KeychainStore.readToken(profileID: $0.id) } ?? "" + let newHeaders = pending ? [] : active.map { KeychainStore.readCustomHeaders(profileID: $0.id) } ?? [] + let changed = pending != activeSyncPending || selectedProfile != active || token != newToken || customHeaders != newHeaders || (pending && !environments.isEmpty) + activeSyncPending = pending + serverProfiles = profiles + guard changed else { return } + syncConnectionRevision += 1 + environmentsLoadToken = UUID() + selectedProfileID = active?.id + PreferencesStore.selectedProfileID = active?.id + token = newToken + customHeaders = newHeaders + environments = [] + selectedEnvironmentID = active.flatMap { PreferencesStore.selectedEnvironmentID(for: $0.id) } + lastHealthStatus = nil + environmentError = nil + Task { await refreshEnvironments(forceEnvironmentReset: false) } + } + func selectServerProfile(_ profileID: String, forceEnvironmentReset: Bool = false) async { guard selectedProfileID != profileID || forceEnvironmentReset else { return } diff --git a/DockhandMobile/App/DockhandRootView.swift b/DockhandMobile/App/DockhandRootView.swift index ca914e2..fec3858 100644 --- a/DockhandMobile/App/DockhandRootView.swift +++ b/DockhandMobile/App/DockhandRootView.swift @@ -78,6 +78,14 @@ struct DockhandRootView: View { } await appModel.bootstrap() } + .task(id: scenePhase) { + guard scenePhase == .active else { return } + appModel.serverSync.foregroundRefresh() + while !Task.isCancelled { + appModel.serverSync.refresh() + do { try await Task.sleep(for: .seconds(5)) } catch { break } + } + } .onChange(of: scenePhase) { _, phase in guard phase == .active else { return } Task { await appModel.recoverConnectionIfNeeded() } diff --git a/DockhandMobile/DockhandMobile.entitlements b/DockhandMobile/DockhandMobile.entitlements new file mode 100644 index 0000000..3a44987 --- /dev/null +++ b/DockhandMobile/DockhandMobile.entitlements @@ -0,0 +1,6 @@ + + + +com.apple.developer.ubiquity-kvstore-identifier +$(TeamIdentifierPrefix)$(CFBundleIdentifier) + diff --git a/DockhandMobile/Features/Settings/ServerSyncSettingsView.swift b/DockhandMobile/Features/Settings/ServerSyncSettingsView.swift new file mode 100644 index 0000000..5f0044f --- /dev/null +++ b/DockhandMobile/Features/Settings/ServerSyncSettingsView.swift @@ -0,0 +1,40 @@ +import SwiftUI + +struct ServerSyncSettingsView: View { + let appModel: AppModel + @State private var confirmDisable = false + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Toggle(isOn: Binding(get: { appModel.serverSync.enabled }, set: { enabled in + if enabled { + do { try appModel.serverSync.enable() } + catch { appModel.serverSync.error = String(localized: "Could not enable iCloud sync. Check your iCloud account and iCloud Keychain settings, then try again.") } + } else { confirmDisable = true } + })) { + Label(String(localized: "Sync servers with iCloud"), systemImage: "icloud") + } + Text(String(localized: "Sync server addresses, order, tokens and custom headers across your devices. Credentials use iCloud Keychain. Your selected server and environment stay on this device.")) + .font(.footnote) + .foregroundStyle(.secondary) + if !appModel.serverSync.pendingCredentials.isEmpty { + Label(String(localized: "Some server credentials are unavailable. Wait for iCloud Keychain or edit the server."), systemImage: "key.icloud") + .font(.footnote) + } + if let error = appModel.serverSync.error { + Text(error).font(.footnote).foregroundStyle(.red) + } + } + .confirmationDialog(String(localized: "Turn off iCloud sync?"), isPresented: $confirmDisable, titleVisibility: .visible) { + Button(String(localized: "Keep servers on this device")) { + appModel.serverSync.disable(removeLocal: false) + } + Button(String(localized: "Remove servers from this device"), role: .destructive) { + appModel.serverSync.disable(removeLocal: true) + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text(String(localized: "Choose whether to keep a local copy. Servers in iCloud and on your other devices will be kept.")) + } + } +} diff --git a/DockhandMobile/Features/Settings/SettingsView.swift b/DockhandMobile/Features/Settings/SettingsView.swift index b3fe270..29c0752 100644 --- a/DockhandMobile/Features/Settings/SettingsView.swift +++ b/DockhandMobile/Features/Settings/SettingsView.swift @@ -91,6 +91,11 @@ struct SettingsList: View { ) } } + .onMove { appModel.moveServers(from: $0, to: $1) } + } + + Section { + ServerSyncSettingsView(appModel: appModel) } Section(String(localized: "About")) { @@ -107,6 +112,7 @@ struct SettingsList: View { } .navigationTitle(String(localized: "Settings")) .toolbar { + ToolbarItem(placement: .topBarLeading) { EditButton() } ToolbarItem(placement: .topBarTrailing) { Button { isAddingServer = true @@ -210,6 +216,9 @@ struct SettingsView: View { statusCard(statusMessage) } + ServerSyncSettingsView(appModel: appModel) + .padding(16) + .glassEffect(.regular, in: .rect(cornerRadius: 22)) aboutCard } .padding() @@ -512,6 +521,16 @@ struct SettingsView: View { } .buttonStyle(.plain) .frame(maxWidth: .infinity) + .contextMenu { + if let index = appModel.serverProfiles.firstIndex(where: { $0.id == profile.id }) { + Button(String(localized: "Move up"), systemImage: "arrow.up") { + appModel.moveServers(from: IndexSet(integer: index), to: index - 1) + }.disabled(index == 0) + Button(String(localized: "Move down"), systemImage: "arrow.down") { + appModel.moveServers(from: IndexSet(integer: index), to: index + 2) + }.disabled(index == appModel.serverProfiles.count - 1) + } + } } } } @@ -973,7 +992,7 @@ private struct ServerProfileDetailView: View { } private func saveProfile() { - appModel.saveServerProfile( + let saved = appModel.saveServerProfile( profileID: profileID, name: draftName, baseURLText: draftBaseURL, @@ -981,7 +1000,8 @@ private struct ServerProfileDetailView: View { customHeaders: draftHeaders.headers, makeActive: true ) - dismiss() + if saved { dismiss() } + else { statusMessage = appModel.serverSync.error } } @MainActor diff --git a/DockhandMobile/Localizable.xcstrings b/DockhandMobile/Localizable.xcstrings index ed33d3c..08e7fc7 100644 --- a/DockhandMobile/Localizable.xcstrings +++ b/DockhandMobile/Localizable.xcstrings @@ -4932,6 +4932,146 @@ } } } + }, + "Sync servers with iCloud" : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Sincroniza servidores con iCloud" + } + } + } + }, + "Sync server addresses, order, tokens and custom headers across your devices. Credentials use iCloud Keychain. Your selected server and environment stay on this device." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Sincroniza las direcciones, el orden, los tokens y los headers personalizados de tus servidores entre dispositivos. Las credenciales usan el llavero de iCloud. El servidor y el entorno seleccionados se mantienen en este dispositivo." + } + } + } + }, + "Some server credentials are unavailable. Wait for iCloud Keychain or edit the server." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Faltan credenciales de algunos servidores. Espera al llavero de iCloud o edita el servidor." + } + } + } + }, + "Turn off iCloud sync?" : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "¿Desactivar la sincronización con iCloud?" + } + } + } + }, + "Keep servers on this device" : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Conservar los servidores en este dispositivo" + } + } + } + }, + "Remove servers from this device" : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Eliminar los servidores de este dispositivo" + } + } + } + }, + "Choose whether to keep a local copy. Servers in iCloud and on your other devices will be kept." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Elige si quieres conservar una copia local. Se conservarán los servidores en iCloud y en tus otros dispositivos." + } + } + } + }, + "Could not enable iCloud sync. Check your iCloud account and iCloud Keychain settings, then try again." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo activar la sincronización. Revisa tu cuenta y el llavero de iCloud y vuelve a intentarlo." + } + } + } + }, + "iCloud storage limit reached. Your servers remain saved locally." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Se alcanzó el límite de almacenamiento de iCloud. Tus servidores siguen guardados localmente." + } + } + } + }, + "Could not sync credentials. Your changes remain saved locally." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron sincronizar las credenciales. Tus cambios siguen guardados localmente." + } + } + } + }, + "Your iCloud account changed. Sync has been turned off; your local servers were kept." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Tu cuenta de iCloud ha cambiado. Se ha desactivado la sincronización y se han conservado tus servidores locales." + } + } + } + }, + "Could not save credentials. Unlock your device and try again." : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron guardar las credenciales. Desbloquea tu dispositivo y vuelve a intentarlo." + } + } + } + }, + "Move up" : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Subir" + } + } + } + }, + "Move down" : { + "localizations": { + "es": { + "stringUnit": { + "state": "translated", + "value": "Bajar" + } + } + } } }, "version" : "1.2" diff --git a/DockhandMobile/Services/KeychainStore.swift b/DockhandMobile/Services/KeychainStore.swift index 27bc07e..78a8368 100644 --- a/DockhandMobile/Services/KeychainStore.swift +++ b/DockhandMobile/Services/KeychainStore.swift @@ -13,50 +13,94 @@ enum KeychainStore { private static let legacyAccount = "dockhand-token" static func readToken(profileID: String) -> String? { - readToken(account: account(for: profileID)).map(DockhandToken.normalized) + if let local = try? credentialsForSync(profileID: profileID) { return DockhandToken.normalized(local.token) } + return nil } static func writeToken(_ token: String, profileID: String) { - writeToken(DockhandToken.normalized(token), account: account(for: profileID)) + guard var local = try? credentialsForSync(profileID: profileID) else { return } + local.token = DockhandToken.normalized(token) + try? installSyncedCredentials(local, profileID: profileID) } static func deleteToken(profileID: String) { + writeToken("", profileID: profileID) + } + + static func deleteCredentials(profileID: String) { + deleteItem(account: "dockhand-credentials." + profileID) deleteItem(account: account(for: profileID)) + deleteItem(account: headersAccount(for: profileID)) } static func migrateLegacyTokenIfNeeded(to profileID: String) { - let targetAccount = account(for: profileID) - guard readToken(account: targetAccount) == nil, - let legacyToken = readLegacyToken(), - !legacyToken.isEmpty else { - return + guard var local = try? credentialsForSync(profileID: profileID), + readData(account: "dockhand-credentials." + profileID) == nil, + readToken(account: account(for: profileID)) == nil, + let legacyToken = readLegacyToken(), !legacyToken.isEmpty else { return } + local.token = DockhandToken.normalized(legacyToken) + do { + try installSyncedCredentials(local, profileID: profileID) + deleteItem(account: legacyAccount) + } catch { + // Preserve the legacy item until the complete local snapshot is committed. } - - writeToken(DockhandToken.normalized(legacyToken), account: targetAccount) - deleteItem(account: legacyAccount) } /// Custom header names and values are stored together as one JSON item per - /// profile. The item never leaves this device (no backups, no iCloud sync) - /// and stays readable after first unlock so background refresh keeps working. + /// profile. This local mirror stays readable after first unlock. When users + /// enable sync, a separate versioned item is stored in iCloud Keychain. static func readCustomHeaders(profileID: String) -> [DockhandCustomHeader] { - guard let data = readData(account: headersAccount(for: profileID)), - let headers = try? JSONDecoder().decode([DockhandCustomHeader].self, from: data) else { - return [] - } - return headers + (try? credentialsForSync(profileID: profileID).headers) ?? [] } static func writeCustomHeaders(_ headers: [DockhandCustomHeader], profileID: String) { - let account = headersAccount(for: profileID) - guard !headers.isEmpty, let data = try? JSONEncoder().encode(headers) else { - deleteItem(account: account) - return - } - writeData(data, account: account, accessibility: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) + guard var local = try? credentialsForSync(profileID: profileID) else { return } + local.headers = headers + try? installSyncedCredentials(local, profileID: profileID) } static func deleteCustomHeaders(profileID: String) { + guard let local = try? credentialsForSync(profileID: profileID) else { return } + if local.token.isEmpty { deleteCredentials(profileID: profileID) } + else { writeCustomHeaders([], profileID: profileID) } + } + + static func credentialsForSync(profileID: String) throws -> SyncedServerCredentials { + func checkedData(_ account: String) throws -> Data? { + let query: [CFString: Any] = [kSecClass: kSecClassGenericPassword, + kSecAttrService: service, kSecAttrAccount: account, kSecAttrSynchronizable: false, + kSecReturnData: true, kSecMatchLimit: kSecMatchLimitOne] + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } + return result as? Data + } + if let bundle = try checkedData("dockhand-credentials." + profileID) { + return try JSONDecoder().decode(SyncedServerCredentials.self, from: bundle) + } + let tokenData = try checkedData(account(for: profileID)) + let headersData = try checkedData(headersAccount(for: profileID)) + return SyncedServerCredentials( + token: tokenData.flatMap { String(data: $0, encoding: .utf8) } ?? "", + headers: try headersData.map { try JSONDecoder().decode([DockhandCustomHeader].self, from: $0) } ?? []) + } + + /// Commit the complete credential snapshot as one atomic Keychain update. + static func installSyncedCredentials(_ credentials: SyncedServerCredentials, profileID: String) throws { + let query: [CFString: Any] = [kSecClass: kSecClassGenericPassword, + kSecAttrService: service, kSecAttrAccount: "dockhand-credentials." + profileID, + kSecAttrSynchronizable: false] + let attributes: [CFString: Any] = [kSecValueData: try JSONEncoder().encode(credentials), + kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] + var status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) + if status == errSecItemNotFound { + status = SecItemAdd(query.merging(attributes) { _, new in new } as CFDictionary, nil) + } + guard status == errSecSuccess else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } + // Remove legacy fragments only after the complete local snapshot exists. + deleteItem(account: account(for: profileID)) deleteItem(account: headersAccount(for: profileID)) } @@ -93,40 +137,6 @@ enum KeychainStore { return data } - private static func writeToken(_ token: String, account: String) { - let query: [CFString: Any] = [ - kSecClass: kSecClassGenericPassword, - kSecAttrService: service, - kSecAttrAccount: account - ] - - if token.isEmpty { - SecItemDelete(query as CFDictionary) - return - } - - writeData(Data(token.utf8), account: account, accessibility: nil) - } - - private static func writeData(_ data: Data, account: String, accessibility: CFString?) { - let query: [CFString: Any] = [ - kSecClass: kSecClassGenericPassword, - kSecAttrService: service, - kSecAttrAccount: account - ] - - var attributes: [CFString: Any] = [kSecValueData: data] - if let accessibility { - attributes[kSecAttrAccessible] = accessibility - } - let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) - - if updateStatus == errSecItemNotFound { - let item = query.merging(attributes) { _, new in new } - SecItemAdd(item as CFDictionary, nil) - } - } - private static func deleteItem(account: String) { let query: [CFString: Any] = [ kSecClass: kSecClassGenericPassword, diff --git a/DockhandMobile/Services/PreferencesStore.swift b/DockhandMobile/Services/PreferencesStore.swift index 673dab9..90f1831 100644 --- a/DockhandMobile/Services/PreferencesStore.swift +++ b/DockhandMobile/Services/PreferencesStore.swift @@ -32,8 +32,7 @@ enum PreferencesStore { static var serverProfiles: [DockhandServerProfile] { get { if let data = defaults.data(forKey: profilesKey) { - if let decoded = try? JSONDecoder().decode([DockhandServerProfile].self, from: data), - !decoded.isEmpty { + if let decoded = try? JSONDecoder().decode([DockhandServerProfile].self, from: data) { return decoded } defaults.removeObject(forKey: profilesKey) diff --git a/DockhandMobile/Services/ServerSyncRecord.swift b/DockhandMobile/Services/ServerSyncRecord.swift new file mode 100644 index 0000000..cdd093a --- /dev/null +++ b/DockhandMobile/Services/ServerSyncRecord.swift @@ -0,0 +1,28 @@ +import Foundation + +/// One independently merged record per server. Tombstones prevent offline resurrection. +struct ServerSyncRecord: Codable, Equatable, Sendable { + var profile: DockhandServerProfile + var modified: Date + var mutation: String + var credentialID: String + var position: Int + var deleted: Bool + var orderModified: Date = .distantPast + var orderMutation: String = "" + + static func merged(_ local: Self, _ remote: Self) -> Self { + var result = local.supersedes(remote) ? local : remote + let localOrderWins = local.orderModified == remote.orderModified + ? local.orderMutation > remote.orderMutation : local.orderModified > remote.orderModified + let order = localOrderWins ? local : remote + result.position = order.position + result.orderModified = order.orderModified + result.orderMutation = order.orderMutation + return result + } + + func supersedes(_ other: Self) -> Bool { + modified == other.modified ? mutation > other.mutation : modified > other.modified + } +} diff --git a/DockhandMobile/Services/ServerSyncStore.swift b/DockhandMobile/Services/ServerSyncStore.swift new file mode 100644 index 0000000..82aca26 --- /dev/null +++ b/DockhandMobile/Services/ServerSyncStore.swift @@ -0,0 +1,265 @@ +import Foundation +import Observation + +@MainActor +@Observable +final class ServerSyncStore { + private(set) var enabled = UserDefaults.standard.bool(forKey: "dockhand.sync.enabled") + private(set) var pendingCredentials = Set(UserDefaults.standard.stringArray(forKey: "dockhand.sync.pending") ?? []) + var error: String? + @ObservationIgnored var onChange: (() -> Void)? + @ObservationIgnored private let cloud = NSUbiquitousKeyValueStore.default + @ObservationIgnored nonisolated(unsafe) private var observer: NSObjectProtocol? + @ObservationIgnored private var records: [String: ServerSyncRecord] = [:] + @ObservationIgnored private var dirty = Set(UserDefaults.standard.stringArray(forKey: "dockhand.sync.dirty") ?? []) + @ObservationIgnored private var dirtyDates: [String: Date] = { + guard let data = UserDefaults.standard.data(forKey: "dockhand.sync.dirtyDates") else { return [:] } + return (try? JSONDecoder().decode([String: Date].self, from: data)) ?? [:] + }() + @ObservationIgnored private var owner: Data? + private static let prefix = "server.v1." + + init() { + owner = UserDefaults.standard.data(forKey: "dockhand.sync.owner") + if let data = UserDefaults.standard.data(forKey: "dockhand.sync.records") { + records = (try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data)) ?? [:] + } + observer = NotificationCenter.default.addObserver( + forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, + object: cloud, queue: .main + ) { [weak self] notification in + let reason = notification.userInfo?[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int + Task { @MainActor [weak self] in + guard let self, self.enabled else { return } + if reason == NSUbiquitousKeyValueStoreQuotaViolationChange { + self.error = String(localized: "iCloud storage limit reached. Your servers remain saved locally.") + } else { + self.refresh() + } + } + } + } + + deinit { + if let observer { NotificationCenter.default.removeObserver(observer) } + } + + func enable() throws { + guard let identity = FileManager.default.ubiquityIdentityToken else { + throw CocoaError(.ubiquitousFileUnavailable) + } + let newOwner = try NSKeyedArchiver.archivedData(withRootObject: identity, requiringSecureCoding: false) + // A different account starts a new journal; never upload the previous account's journal. + if !sameAccount(identity) { records = [:] } + owner = newOwner + UserDefaults.standard.set(newOwner, forKey: "dockhand.sync.owner") + cloud.synchronize() + mergeRemote() + for (position, profile) in PreferencesStore.serverProfiles.enumerated() where records[profile.id] == nil || dirty.contains(profile.id) { + try publish(profile, position: position) + } + enabled = true + UserDefaults.standard.set(true, forKey: "dockhand.sync.enabled") + error = nil + refresh() + } + + func disable(removeLocal: Bool) { + enabled = false + UserDefaults.standard.set(false, forKey: "dockhand.sync.enabled") + if removeLocal { + for profile in PreferencesStore.serverProfiles { + KeychainStore.deleteCredentials(profileID: profile.id) + PreferencesStore.removeSelectedEnvironmentID(for: profile.id) + PreferencesStore.removeCachedDashboardSnapshots(for: profile.id) + } + records = [:] + dirty = [] + dirtyDates = [:] + PreferencesStore.serverProfiles = [] + PreferencesStore.selectedProfileID = nil + } + if removeLocal { pendingCredentials = [] } + persist() + error = nil + onChange?() + } + + func save(_ profile: DockhandServerProfile, position: Int) { + reloadParticipationIfNeeded() + pendingCredentials.remove(profile.id) + dirty.insert(profile.id) + dirtyDates[profile.id] = max(Date(), (records[profile.id]?.modified ?? .distantPast).addingTimeInterval(0.001)) + persist() + guard enabled else { return } + guard let identity = FileManager.default.ubiquityIdentityToken, sameAccount(identity) else { refresh(); return } + do { try publish(profile, position: position) } + catch { self.error = String(localized: "Could not sync credentials. Your changes remain saved locally.") } + } + + func reorder(_ profiles: [DockhandServerProfile]) { + reloadParticipationIfNeeded() + if enabled { + guard let identity = FileManager.default.ubiquityIdentityToken, sameAccount(identity) else { refresh(); return } + } + for (position, profile) in profiles.enumerated() { + guard var record = records[profile.id], !record.deleted else { continue } + record.position = position + record.orderModified = max(Date(), record.orderModified.addingTimeInterval(0.001)) + record.orderMutation = UUID().uuidString + records[profile.id] = record + if enabled { write(record) } + } + persist() + } + + func delete(_ profile: DockhandServerProfile) { + reloadParticipationIfNeeded() + dirty.remove(profile.id) + persist() + guard enabled else { return } + guard let identity = FileManager.default.ubiquityIdentityToken, sameAccount(identity) else { refresh(); return } + var record = records[profile.id] ?? ServerSyncRecord(profile: profile, modified: .distantPast, mutation: "", credentialID: "", position: 0, deleted: false) + record.deleted = true + stamp(&record) + write(record) + } + + func foregroundRefresh() { + if enabled { cloud.synchronize() } + refresh() + } + + func refresh() { + let participationChanged = reloadParticipationIfNeeded() + guard enabled else { + if participationChanged { onChange?() } + return + } + guard let identity = FileManager.default.ubiquityIdentityToken, sameAccount(identity) else { + disable(removeLocal: false) + error = String(localized: "Your iCloud account changed. Sync has been turned off; your local servers were kept.") + return + } + mergeRemote() + for (position, profile) in PreferencesStore.serverProfiles.enumerated() where dirty.contains(profile.id) { + do { try publish(profile, position: position) } + catch { self.error = String(localized: "Could not sync credentials. Your changes remain saved locally.") } + } + var profiles: [DockhandServerProfile] = [] + var pending: Set = [] + for record in records.values.sorted(by: { + $0.position == $1.position ? $0.profile.id < $1.profile.id : $0.position < $1.position + }) { + let id = record.profile.id + if dirty.contains(id) { continue } + if record.deleted { + SyncedServerCredentials.deleteAll(profileID: id) + KeychainStore.deleteCredentials(profileID: id) + PreferencesStore.removeSelectedEnvironmentID(for: id) + PreferencesStore.removeCachedDashboardSnapshots(for: id) + continue + } + profiles.append(record.profile) + do { + if let credentials = try SyncedServerCredentials.read(record.credentialID) { + let local = try KeychainStore.credentialsForSync(profileID: id) + if local.token != credentials.token || local.headers != credentials.headers { + try KeychainStore.installSyncedCredentials(credentials, profileID: id) + } + } else { pending.insert(id) } + } catch { pending.insert(id) } + } + // Never discard a local edit whose secret could not be published. + let known = Set(profiles.map(\.id)) + profiles += PreferencesStore.serverProfiles.filter { (records[$0.id] == nil || dirty.contains($0.id)) && !known.contains($0.id) } + pendingCredentials = pending + persist() + PreferencesStore.serverProfiles = profiles + onChange?() + } + + /// Multiple windows can own an AppModel; a device-level opt-out applies to all of them. + @discardableResult + private func reloadParticipationIfNeeded() -> Bool { + let defaults = UserDefaults.standard + let storedEnabled = defaults.bool(forKey: "dockhand.sync.enabled") + guard storedEnabled != enabled else { return false } + enabled = storedEnabled + owner = defaults.data(forKey: "dockhand.sync.owner") + if let data = defaults.data(forKey: "dockhand.sync.records"), + let stored = try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data) { records = stored } + dirty = Set(defaults.stringArray(forKey: "dockhand.sync.dirty") ?? []) + if let data = defaults.data(forKey: "dockhand.sync.dirtyDates"), + let dates = try? JSONDecoder().decode([String: Date].self, from: data) { dirtyDates = dates } + pendingCredentials = Set(defaults.stringArray(forKey: "dockhand.sync.pending") ?? []) + return true + } + + private func publish(_ profile: DockhandServerProfile, position: Int) throws { + let credentials = try KeychainStore.credentialsForSync(profileID: profile.id) + if let edited = dirtyDates[profile.id], let remote = records[profile.id], remote.modified > edited { + dirty.remove(profile.id) + dirtyDates.removeValue(forKey: profile.id) + persist() + return + } + let credentialID = "\(profile.id).\(UUID().uuidString)" + try credentials.write(credentialID) + var record = ServerSyncRecord(profile: profile, modified: .distantPast, mutation: "", credentialID: credentialID, position: position, deleted: false) + if let previous = records[profile.id] { + record.position = previous.position + record.orderModified = previous.orderModified + record.orderMutation = previous.orderMutation + } else { + record.orderModified = Date() + record.orderMutation = UUID().uuidString + } + stamp(&record) + if let edited = dirtyDates[profile.id] { record.modified = edited } + dirtyDates.removeValue(forKey: profile.id) + dirty.remove(profile.id) + write(record) + } + + private func sameAccount(_ identity: any NSCoding & NSCopying & NSObjectProtocol) -> Bool { + guard let owner, let decoder = try? NSKeyedUnarchiver(forReadingFrom: owner) else { return false } + decoder.requiresSecureCoding = false + decoder.decodingFailurePolicy = .setErrorAndReturn + defer { decoder.finishDecoding() } + guard let previous = decoder.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as? NSObject else { return false } + return previous.isEqual(identity) + } + + private func stamp(_ record: inout ServerSyncRecord) { + record.modified = max(Date(), (records[record.profile.id]?.modified ?? .distantPast).addingTimeInterval(0.001)) + record.mutation = UUID().uuidString + } + + private func write(_ record: ServerSyncRecord) { + records[record.profile.id] = record + if let data = try? JSONEncoder().encode(record) { cloud.set(data, forKey: Self.prefix + record.profile.id) } + persist() + } + + private func mergeRemote() { + for (key, value) in cloud.dictionaryRepresentation where key.hasPrefix(Self.prefix) { + guard let data = value as? Data, + let remote = try? JSONDecoder().decode(ServerSyncRecord.self, from: data), + key == Self.prefix + remote.profile.id else { continue } + let merged = records[remote.profile.id].map { ServerSyncRecord.merged($0, remote) } ?? remote + records[remote.profile.id] = merged + if merged != remote, let data = try? JSONEncoder().encode(merged) { + cloud.set(data, forKey: key) + } + } + persist() + } + + private func persist() { + UserDefaults.standard.set(Array(pendingCredentials), forKey: "dockhand.sync.pending") + if let data = try? JSONEncoder().encode(dirtyDates) { UserDefaults.standard.set(data, forKey: "dockhand.sync.dirtyDates") } + UserDefaults.standard.set(Array(dirty), forKey: "dockhand.sync.dirty") + if let data = try? JSONEncoder().encode(records) { UserDefaults.standard.set(data, forKey: "dockhand.sync.records") } + } +} diff --git a/DockhandMobile/Services/SyncedServerCredentials.swift b/DockhandMobile/Services/SyncedServerCredentials.swift new file mode 100644 index 0000000..266aa74 --- /dev/null +++ b/DockhandMobile/Services/SyncedServerCredentials.swift @@ -0,0 +1,53 @@ +import DockhandAPI +import Foundation +import Security + +struct SyncedServerCredentials: Codable, Sendable { + var token: String + var headers: [DockhandCustomHeader] + + private static let service = "pro.dockhand.mobile.server-sync.v1" + + static func read(_ id: String) throws -> Self? { + var query = identity(id) + query[kSecReturnData] = true + query[kSecMatchLimit] = kSecMatchLimitOne + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess, let data = result as? Data else { + throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) + } + return try JSONDecoder().decode(Self.self, from: data) + } + + func write(_ id: String) throws { + var item = Self.identity(id) + item[kSecValueData] = try JSONEncoder().encode(self) + item[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlock + let status = SecItemAdd(item as CFDictionary, nil) + guard status == errSecSuccess || status == errSecDuplicateItem else { + throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) + } + } + + static func deleteAll(profileID: String) { + var query: [CFString: Any] = [kSecClass: kSecClassGenericPassword, + kSecAttrService: service, kSecAttrSynchronizable: true, + kSecReturnAttributes: true, kSecMatchLimit: kSecMatchLimitAll] + var result: AnyObject? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, + let items = result as? [[String: Any]] else { return } + for item in items { + guard let account = item[kSecAttrAccount as String] as? String, + account.hasPrefix(profileID + ".") else { continue } + query = identity(account) + SecItemDelete(query as CFDictionary) + } + } + + private static func identity(_ id: String) -> [CFString: Any] { + [kSecClass: kSecClassGenericPassword, kSecAttrService: service, + kSecAttrAccount: id, kSecAttrSynchronizable: true] + } +} diff --git a/DockhandMobileTests/DockhandMobileTests.swift b/DockhandMobileTests/DockhandMobileTests.swift index e3e05ac..dd67fef 100644 --- a/DockhandMobileTests/DockhandMobileTests.swift +++ b/DockhandMobileTests/DockhandMobileTests.swift @@ -1,9 +1,109 @@ import XCTest +import Security import SwiftUI @testable import DockhandMobile import DockhandAPI final class DockhandMobileTests: XCTestCase { + func testSyncTombstoneWinsAgainstOlderOfflineEdit() throws { + let profile = DockhandServerProfile(id: "sync-test", name: "Test", baseURL: "https://example.invalid") + let edit = ServerSyncRecord(profile: profile, modified: Date(timeIntervalSince1970: 10), mutation: "a", credentialID: "secret", position: 0, deleted: false) + var deletion = edit + deletion.modified = Date(timeIntervalSince1970: 20) + deletion.deleted = true + XCTAssertTrue(deletion.supersedes(edit)) + XCTAssertFalse(edit.supersedes(deletion)) + let decoded = try JSONDecoder().decode(ServerSyncRecord.self, from: JSONEncoder().encode(deletion)) + XCTAssertEqual(decoded, deletion) + XCTAssertTrue(decoded.deleted) + } + + func testReorderingDoesNotOverwriteNewerServerCredentials() { + let old = ServerSyncRecord(profile: .init(id: "server", name: "Old", baseURL: "https://old.invalid"), modified: Date(timeIntervalSince1970: 10), mutation: "a", credentialID: "old-secret", position: 0, deleted: false) + var reordered = old + reordered.position = 2 + reordered.orderModified = Date(timeIntervalSince1970: 30) + reordered.orderMutation = "move" + var edited = old + edited.profile.baseURL = "https://new.invalid" + edited.credentialID = "new-secret" + edited.modified = Date(timeIntervalSince1970: 20) + let merged = ServerSyncRecord.merged(reordered, edited) + XCTAssertEqual(merged.profile.baseURL, "https://new.invalid") + XCTAssertEqual(merged.credentialID, "new-secret") + XCTAssertEqual(merged.position, 2) + XCTAssertEqual(merged, ServerSyncRecord.merged(edited, reordered)) + edited.deleted = true + XCTAssertTrue(ServerSyncRecord.merged(reordered, edited).deleted) + } + + func testSyncConcurrentChangesHaveDeterministicWinner() { + let profile = DockhandServerProfile(id: "sync-test", name: "Test", baseURL: "https://example.invalid") + let first = ServerSyncRecord(profile: profile, modified: Date(timeIntervalSince1970: 10), mutation: "a", credentialID: "secret", position: 0, deleted: false) + var second = first + second.mutation = "b" + XCTAssertTrue(second.supersedes(first)) + XCTAssertFalse(first.supersedes(second)) + XCTAssertFalse(first.supersedes(first)) + } + + @MainActor + func testEmptyProfileListDoesNotResurrectLegacyServer() throws { + withRestoredDefaults(keys: ["dockhand.serverProfiles", "dockhand.baseURL"]) { defaults in + defaults.set("https://legacy.invalid", forKey: "dockhand.baseURL") + PreferencesStore.serverProfiles = [] + XCTAssertTrue(PreferencesStore.serverProfiles.isEmpty) + } + } + + @MainActor + func testDisablingSyncCanKeepOrRemoveLocalRecords() throws { + let keys = ["dockhand.serverProfiles", "dockhand.selectedProfileID", "dockhand.sync.enabled", "dockhand.sync.pending", "dockhand.sync.records", "dockhand.sync.orderDirty", "dockhand.sync.dirty", "dockhand.sync.dirtyDates"] + withRestoredDefaults(keys: keys) { defaults in + defaults.set(true, forKey: "dockhand.sync.enabled") + let profile = DockhandServerProfile(id: UUID().uuidString, name: "Test", baseURL: "https://example.invalid") + PreferencesStore.serverProfiles = [profile] + PreferencesStore.selectedProfileID = profile.id + let store = ServerSyncStore() + let otherWindow = ServerSyncStore() + store.disable(removeLocal: false) + otherWindow.refresh() + XCTAssertFalse(otherWindow.enabled, "Opting out applies to every window on this device") + XCTAssertEqual(PreferencesStore.serverProfiles, [profile]) + XCTAssertEqual(PreferencesStore.selectedProfileID, profile.id) + XCTAssertFalse(store.enabled) + store.disable(removeLocal: true) + XCTAssertTrue(PreferencesStore.serverProfiles.isEmpty) + XCTAssertNil(PreferencesStore.selectedProfileID) + } + } + + func testCredentialMigrationPreservesTokenAndCustomHeaders() throws { + let id = "sync-test-" + UUID().uuidString + defer { + KeychainStore.deleteToken(profileID: id) + KeychainStore.deleteCustomHeaders(profileID: id) + } + let expected = SyncedServerCredentials(token: "sample-token", headers: [.init(name: "X-Access", value: "sample-value")]) + // Seed the pre-sync layout: separate token and header items. + for (account, data) in [ + ("dockhand-token." + id, Data(expected.token.utf8)), + ("dockhand-headers." + id, try JSONEncoder().encode(expected.headers)) + ] { + let item: [CFString: Any] = [kSecClass: kSecClassGenericPassword, + kSecAttrService: "pro.dockhand.mobile", kSecAttrAccount: account, + kSecValueData: data, kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] + XCTAssertEqual(SecItemAdd(item as CFDictionary, nil), errSecSuccess) + } + let legacy = try KeychainStore.credentialsForSync(profileID: id) + XCTAssertEqual(legacy.token, expected.token) + XCTAssertEqual(legacy.headers, expected.headers) + try KeychainStore.installSyncedCredentials(legacy, profileID: id) + let actual = try KeychainStore.credentialsForSync(profileID: id) + XCTAssertEqual(actual.token, expected.token) + XCTAssertEqual(actual.headers, expected.headers) + } + @MainActor func testEnvironmentSwitchClearsPreviousUpdateCheckPresentation() async { let model = AppModel() diff --git a/PRIVACY.md b/PRIVACY.md index 0d6c732..d4f50d5 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # Privacy Policy -_Last updated: October 19, 2026_ +_Last updated: November 9, 2026_ Dockhand Mobile ("the app") is an independent, open-source client for self-hosted [Dockhand](https://github.com/Finsys/dockhand) servers. This policy explains how the app handles your information. @@ -10,17 +10,19 @@ Dockhand Mobile ("the app") is an independent, open-source client for self-hoste ## Data stored on your device -To work, the app stores the following information locally on your device only: +To work, the app stores the following information locally on your device: - Server URLs and names you add. - API tokens and optional custom HTTP headers, stored in the iOS Keychain. - App preferences, such as the selected server and environment. -This data never leaves your device except when it is sent to the servers you configured. +If you enable iCloud sync, server names, addresses and order also sync through your iCloud account. API tokens and custom HTTP headers sync separately through iCloud Keychain. Sync is optional and off by default. The developer cannot access this data. + +The selected server, selected environment and cached server responses stay local. Turning sync off lets you keep the local server records or remove them from that device, without removing the shared iCloud records. Removing a server while sync is enabled propagates the deletion to your other participating devices. ## Network connections -The app connects only to the Dockhand servers that you configure. All requests (container, stack, image, log, backup and terminal data) go directly from your device to your server. The developer has no access to your servers or to any of this traffic. +The app connects to the Dockhand servers that you configure and, when you enable sync, uses Apple iCloud services. All requests (container, stack, image, log, backup and terminal data) go directly from your device to your server. The developer has no access to your servers or to any of this traffic. Any data handled by your Dockhand server is governed by that server's configuration and by whoever operates it. @@ -30,7 +32,7 @@ The app is not directed to children and does not knowingly collect information f ## Deleting your data -Removing a server in the app deletes its stored settings and credentials. Deleting the app removes all locally stored data. +Removing a server in the app deletes its stored settings and credentials. Uninstalling the app does not delete shared iCloud records, and Keychain items may survive uninstall. To remove shared server records, delete those servers while sync is enabled. ## Changes diff --git a/docs/icloud-server-sync.md b/docs/icloud-server-sync.md new file mode 100644 index 0000000..11274e4 --- /dev/null +++ b/docs/icloud-server-sync.md @@ -0,0 +1,52 @@ +# iCloud server sync + +The feature is opt-in, requires iOS 26+, and uses the same signed app identifier on iPhone, iPad and Mac (Designed for iPad). + +## Data and protection + +- Server UUID, name, address and position are stored in separate `NSUbiquitousKeyValueStore` records. Each device retains its local copy. +- Tokens and all custom headers are encoded together in immutable, versioned synchronizable Keychain items. Cloud records reference a credential version; they never contain credential values. +- Local credentials use a separate `AfterFirstUnlockThisDeviceOnly` mirror. Synchronized items use `AfterFirstUnlock`, because `ThisDeviceOnly` is incompatible with synchronization. +- Selection, environments, caches, logs and operations stay local. +- Existing credentials are read with explicit error handling before copying. A failed copy preserves local data and queues the local edit. Enabling sync does not delete the original local credentials. + +## Reconciliation + +Content conflicts resolve by modification date, then a deterministic mutation identifier. Order has its own modification date and mutation identifier, so moving a server does not revert an independently edited address or token. Equal positions resolve by server UUID. Clock skew can influence conflicts, as with any wall-clock last-writer policy. + +Deletion writes a tombstone. Tombstones are retained, and older offline edits cannot recreate a deleted server. Deletion also removes that server's synchronized credential revisions when a participating device processes the tombstone. Historical credential versions of live servers remain in Keychain to support delayed record delivery; they are removed when that server is deleted. + +Profiles and credentials travel independently. Until the matching credential version is available and installed, the server is marked pending and connection loading is blocked. Foreground polling checks delayed Keychain delivery; it does not assert that a successful local write means another device has received it. `synchronize()` is used on enable/foreground, not as a forced upload. + +A changed or missing iCloud identity disables participation and retains local records. Re-enabling is explicit. Turning sync off offers to keep or remove local records; neither choice deletes the shared iCloud records. Removing local records clears the app's profile journal and local credential mirrors; Apple-managed iCloud caches and synchronizable Keychain copies are not remotely deleted by this action. + +## Signing and deployment + +`DockhandMobile.entitlements` declares `com.apple.developer.ubiquity-kvstore-identifier` using the signed team prefix and bundle identifier. The existing App ID and provisioning profile must support iCloud key-value storage. CloudKit containers, database schemas and a third-party sync framework are not required. The existing Keychain service identifiers are preserved. + +## Required real-device acceptance + +Use two devices signed with the same application identity, Apple Account and iCloud Keychain enabled: + +1. Begin with different local servers. Enable sync and confirm both libraries combine without losing authentication or custom proxy headers. +2. Change names, addresses and secrets. Verify the receiving device waits for the matching credential revision before connecting. +3. Reorder servers; verify order converges. Concurrently reorder on one device and edit credentials on the other; verify the credentials are preserved. +4. Edit offline, delete the same server elsewhere, then reconnect. An older edit must not resurrect it. +5. Turn sync off and cancel; participation must continue. Repeat and keep local records; verify they remain usable. Repeat and remove records; verify other devices retain them. +6. Restart, lock/unlock, disable iCloud Keychain and change the iCloud account. Verify pending/error presentation and preservation of local data. +7. Check quota errors and interrupted credential writes. Never include credential values in diagnostics. + +Simulator tests cover local regression behavior but cannot establish real iCloud delivery or cross-device Keychain behavior. + +## Apple references + +- https://developer.apple.com/documentation/security/ksecattrsynchronizable +- https://developer.apple.com/documentation/foundation/nsubiquitouskeyvaluestore +- https://developer.apple.com/documentation/foundation/nsubiquitouskeyvaluestore/synchronize() + +## Implementation validation + +- iOS 26.5 simulator: 100 tests executed, 3 optional integration tests skipped, 0 failures. +- Signed device build: passed with the existing development certificate and a new `Dockhand iCloud Development` profile. The signed app contains `8DA225EN79.garanda.dockhand.mobile` as its key-value store identifier; strict signature verification passed. +- iCloud capability was enabled on the existing App ID. No App Store submission or distribution-profile rotation was performed. +- Real cross-device iCloud/Keychain delivery remains an acceptance check on physical devices. diff --git a/project.yml b/project.yml index d104165..07754ed 100644 --- a/project.yml +++ b/project.yml @@ -28,7 +28,8 @@ targets: - package: SwiftTerm settings: base: - PRODUCT_BUNDLE_IDENTIFIER: pro.dockhand.mobile + PRODUCT_BUNDLE_IDENTIFIER: garanda.dockhand.mobile + CODE_SIGN_ENTITLEMENTS: DockhandMobile/DockhandMobile.entitlements SWIFT_VERSION: 6.0 TARGETED_DEVICE_FAMILY: "1,2" CURRENT_PROJECT_VERSION: 18 From c719ce494ae183cfa7dd80203bcc1e5dc3b8b23b Mon Sep 17 00:00:00 2001 From: Giovanny Aranda Date: Thu, 12 Nov 2026 15:52:14 +0100 Subject: [PATCH 2/3] fix: preserve iCloud sync deletions and credentials --- DockhandMobile/Services/KeychainStore.swift | 32 +++++--- DockhandMobile/Services/ServerSyncStore.swift | 77 ++++++++++++++++++- .../Services/SyncedServerCredentials.swift | 4 + DockhandMobileTests/CustomHeadersTests.swift | 10 +-- DockhandMobileTests/DockhandMobileTests.swift | 6 +- docs/icloud-server-sync.md | 6 +- 6 files changed, 110 insertions(+), 25 deletions(-) diff --git a/DockhandMobile/Services/KeychainStore.swift b/DockhandMobile/Services/KeychainStore.swift index 78a8368..0a541d9 100644 --- a/DockhandMobile/Services/KeychainStore.swift +++ b/DockhandMobile/Services/KeychainStore.swift @@ -17,14 +17,14 @@ enum KeychainStore { return nil } - static func writeToken(_ token: String, profileID: String) { - guard var local = try? credentialsForSync(profileID: profileID) else { return } + static func writeToken(_ token: String, profileID: String) throws { + var local = try credentialsForUpdate(profileID: profileID) local.token = DockhandToken.normalized(token) - try? installSyncedCredentials(local, profileID: profileID) + try installSyncedCredentials(local, profileID: profileID) } - static func deleteToken(profileID: String) { - writeToken("", profileID: profileID) + static func deleteToken(profileID: String) throws { + try writeToken("", profileID: profileID) } static func deleteCredentials(profileID: String) { @@ -54,16 +54,16 @@ enum KeychainStore { (try? credentialsForSync(profileID: profileID).headers) ?? [] } - static func writeCustomHeaders(_ headers: [DockhandCustomHeader], profileID: String) { - guard var local = try? credentialsForSync(profileID: profileID) else { return } + static func writeCustomHeaders(_ headers: [DockhandCustomHeader], profileID: String) throws { + var local = try credentialsForUpdate(profileID: profileID) local.headers = headers - try? installSyncedCredentials(local, profileID: profileID) + try installSyncedCredentials(local, profileID: profileID) } - static func deleteCustomHeaders(profileID: String) { - guard let local = try? credentialsForSync(profileID: profileID) else { return } + static func deleteCustomHeaders(profileID: String) throws { + let local = try credentialsForUpdate(profileID: profileID) if local.token.isEmpty { deleteCredentials(profileID: profileID) } - else { writeCustomHeaders([], profileID: profileID) } + else { try writeCustomHeaders([], profileID: profileID) } } static func credentialsForSync(profileID: String) throws -> SyncedServerCredentials { @@ -87,6 +87,16 @@ enum KeychainStore { headers: try headersData.map { try JSONDecoder().decode([DockhandCustomHeader].self, from: $0) } ?? []) } + /// Writes can safely replace a malformed saved snapshot with the new value. + /// Keychain access errors still propagate so callers can report locked-device failures. + private static func credentialsForUpdate(profileID: String) throws -> SyncedServerCredentials { + do { + return try credentialsForSync(profileID: profileID) + } catch is DecodingError { + return SyncedServerCredentials(token: "", headers: []) + } + } + /// Commit the complete credential snapshot as one atomic Keychain update. static func installSyncedCredentials(_ credentials: SyncedServerCredentials, profileID: String) throws { let query: [CFString: Any] = [kSecClass: kSecClassGenericPassword, diff --git a/DockhandMobile/Services/ServerSyncStore.swift b/DockhandMobile/Services/ServerSyncStore.swift index 82aca26..c0aace1 100644 --- a/DockhandMobile/Services/ServerSyncStore.swift +++ b/DockhandMobile/Services/ServerSyncStore.swift @@ -16,6 +16,12 @@ final class ServerSyncStore { guard let data = UserDefaults.standard.data(forKey: "dockhand.sync.dirtyDates") else { return [:] } return (try? JSONDecoder().decode([String: Date].self, from: data)) ?? [:] }() + @ObservationIgnored private var pendingDeletions: [String: ServerSyncRecord] = { + guard let data = UserDefaults.standard.data(forKey: "dockhand.sync.pendingDeletions") else { return [:] } + return (try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data)) ?? [:] + }() + @ObservationIgnored private var credentialRetryTask: Task? + @ObservationIgnored private var credentialRetryAttempt = 0 @ObservationIgnored private var owner: Data? private static let prefix = "server.v1." @@ -55,6 +61,7 @@ final class ServerSyncStore { UserDefaults.standard.set(newOwner, forKey: "dockhand.sync.owner") cloud.synchronize() mergeRemote() + flushPendingDeletions() for (position, profile) in PreferencesStore.serverProfiles.enumerated() where records[profile.id] == nil || dirty.contains(profile.id) { try publish(profile, position: position) } @@ -65,6 +72,9 @@ final class ServerSyncStore { } func disable(removeLocal: Bool) { + credentialRetryTask?.cancel() + credentialRetryTask = nil + credentialRetryAttempt = 0 enabled = false UserDefaults.standard.set(false, forKey: "dockhand.sync.enabled") if removeLocal { @@ -76,6 +86,7 @@ final class ServerSyncStore { records = [:] dirty = [] dirtyDates = [:] + pendingDeletions = [:] PreferencesStore.serverProfiles = [] PreferencesStore.selectedProfileID = nil } @@ -116,13 +127,18 @@ final class ServerSyncStore { func delete(_ profile: DockhandServerProfile) { reloadParticipationIfNeeded() dirty.remove(profile.id) - persist() - guard enabled else { return } - guard let identity = FileManager.default.ubiquityIdentityToken, sameAccount(identity) else { refresh(); return } + dirtyDates.removeValue(forKey: profile.id) var record = records[profile.id] ?? ServerSyncRecord(profile: profile, modified: .distantPast, mutation: "", credentialID: "", position: 0, deleted: false) record.deleted = true stamp(&record) - write(record) + records[profile.id] = record + pendingDeletions[profile.id] = record + persist() + guard enabled else { return } + guard let identity = FileManager.default.ubiquityIdentityToken, sameAccount(identity) else { refresh(); return } + cloud.synchronize() + mergeRemote() + flushPendingDeletions() } func foregroundRefresh() { @@ -142,6 +158,7 @@ final class ServerSyncStore { return } mergeRemote() + flushPendingDeletions() for (position, profile) in PreferencesStore.serverProfiles.enumerated() where dirty.contains(profile.id) { do { try publish(profile, position: position) } catch { self.error = String(localized: "Could not sync credentials. Your changes remain saved locally.") } @@ -177,6 +194,7 @@ final class ServerSyncStore { persist() PreferencesStore.serverProfiles = profiles onChange?() + scheduleCredentialRetryIfNeeded() } /// Multiple windows can own an AppModel; a device-level opt-out applies to all of them. @@ -186,6 +204,11 @@ final class ServerSyncStore { let storedEnabled = defaults.bool(forKey: "dockhand.sync.enabled") guard storedEnabled != enabled else { return false } enabled = storedEnabled + if !storedEnabled { + credentialRetryTask?.cancel() + credentialRetryTask = nil + credentialRetryAttempt = 0 + } owner = defaults.data(forKey: "dockhand.sync.owner") if let data = defaults.data(forKey: "dockhand.sync.records"), let stored = try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data) { records = stored } @@ -193,6 +216,10 @@ final class ServerSyncStore { if let data = defaults.data(forKey: "dockhand.sync.dirtyDates"), let dates = try? JSONDecoder().decode([String: Date].self, from: data) { dirtyDates = dates } pendingCredentials = Set(defaults.stringArray(forKey: "dockhand.sync.pending") ?? []) + if let data = defaults.data(forKey: "dockhand.sync.pendingDeletions"), + let deletions = try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data) { + pendingDeletions = deletions + } return true } @@ -204,6 +231,7 @@ final class ServerSyncStore { persist() return } + let previousCredentialID = records[profile.id]?.credentialID let credentialID = "\(profile.id).\(UUID().uuidString)" try credentials.write(credentialID) var record = ServerSyncRecord(profile: profile, modified: .distantPast, mutation: "", credentialID: credentialID, position: position, deleted: false) @@ -220,6 +248,44 @@ final class ServerSyncStore { dirtyDates.removeValue(forKey: profile.id) dirty.remove(profile.id) write(record) + if let previousCredentialID, previousCredentialID != credentialID { + SyncedServerCredentials.delete(previousCredentialID) + } + } + + private func flushPendingDeletions() { + for (id, pending) in Array(pendingDeletions) { + var record = records[id].map { ServerSyncRecord.merged(pending, $0) } ?? pending + record.deleted = true + record.modified = max(Date(), max(record.modified, pending.modified).addingTimeInterval(0.001)) + record.mutation = UUID().uuidString + records[id] = record + write(record) + pendingDeletions.removeValue(forKey: id) + } + persist() + } + + private func scheduleCredentialRetryIfNeeded() { + guard enabled, !pendingCredentials.isEmpty else { + credentialRetryTask?.cancel() + credentialRetryTask = nil + credentialRetryAttempt = 0 + return + } + guard credentialRetryTask == nil else { return } + let delay = min(30, 1 << min(credentialRetryAttempt, 5)) + credentialRetryAttempt += 1 + credentialRetryTask = Task { @MainActor [weak self] in + do { + try await Task.sleep(nanoseconds: UInt64(delay) * 1_000_000_000) + } catch { + return + } + guard let self, !Task.isCancelled else { return } + self.credentialRetryTask = nil + self.refresh() + } } private func sameAccount(_ identity: any NSCoding & NSCopying & NSObjectProtocol) -> Bool { @@ -260,6 +326,9 @@ final class ServerSyncStore { UserDefaults.standard.set(Array(pendingCredentials), forKey: "dockhand.sync.pending") if let data = try? JSONEncoder().encode(dirtyDates) { UserDefaults.standard.set(data, forKey: "dockhand.sync.dirtyDates") } UserDefaults.standard.set(Array(dirty), forKey: "dockhand.sync.dirty") + if let data = try? JSONEncoder().encode(pendingDeletions) { + UserDefaults.standard.set(data, forKey: "dockhand.sync.pendingDeletions") + } if let data = try? JSONEncoder().encode(records) { UserDefaults.standard.set(data, forKey: "dockhand.sync.records") } } } diff --git a/DockhandMobile/Services/SyncedServerCredentials.swift b/DockhandMobile/Services/SyncedServerCredentials.swift index 266aa74..5660dd8 100644 --- a/DockhandMobile/Services/SyncedServerCredentials.swift +++ b/DockhandMobile/Services/SyncedServerCredentials.swift @@ -31,6 +31,10 @@ struct SyncedServerCredentials: Codable, Sendable { } } + static func delete(_ id: String) { + SecItemDelete(identity(id) as CFDictionary) + } + static func deleteAll(profileID: String) { var query: [CFString: Any] = [kSecClass: kSecClassGenericPassword, kSecAttrService: service, kSecAttrSynchronizable: true, diff --git a/DockhandMobileTests/CustomHeadersTests.swift b/DockhandMobileTests/CustomHeadersTests.swift index 45325e2..1b17dd8 100644 --- a/DockhandMobileTests/CustomHeadersTests.swift +++ b/DockhandMobileTests/CustomHeadersTests.swift @@ -53,20 +53,20 @@ final class CustomHeadersTests: XCTestCase { XCTAssertEqual(request.value(forHTTPHeaderField: "P-Access-Token"), "token-secret") } - func testKeychainRoundTripsAndDeletesCustomHeaders() { + func testKeychainRoundTripsAndDeletesCustomHeaders() throws { let profileID = "custom-headers-test-\(UUID().uuidString)" - defer { KeychainStore.deleteCustomHeaders(profileID: profileID) } + defer { try? KeychainStore.deleteCustomHeaders(profileID: profileID) } XCTAssertEqual(KeychainStore.readCustomHeaders(profileID: profileID), []) - KeychainStore.writeCustomHeaders(pangolinHeaders, profileID: profileID) + try KeychainStore.writeCustomHeaders(pangolinHeaders, profileID: profileID) XCTAssertEqual(KeychainStore.readCustomHeaders(profileID: profileID), pangolinHeaders) let replaced = [DockhandCustomHeader(name: "CF-Access-Client-Id", value: "client")] - KeychainStore.writeCustomHeaders(replaced, profileID: profileID) + try KeychainStore.writeCustomHeaders(replaced, profileID: profileID) XCTAssertEqual(KeychainStore.readCustomHeaders(profileID: profileID), replaced) - KeychainStore.writeCustomHeaders([], profileID: profileID) + try KeychainStore.writeCustomHeaders([], profileID: profileID) XCTAssertEqual(KeychainStore.readCustomHeaders(profileID: profileID), []) } diff --git a/DockhandMobileTests/DockhandMobileTests.swift b/DockhandMobileTests/DockhandMobileTests.swift index dd67fef..c1db131 100644 --- a/DockhandMobileTests/DockhandMobileTests.swift +++ b/DockhandMobileTests/DockhandMobileTests.swift @@ -58,7 +58,7 @@ final class DockhandMobileTests: XCTestCase { @MainActor func testDisablingSyncCanKeepOrRemoveLocalRecords() throws { - let keys = ["dockhand.serverProfiles", "dockhand.selectedProfileID", "dockhand.sync.enabled", "dockhand.sync.pending", "dockhand.sync.records", "dockhand.sync.orderDirty", "dockhand.sync.dirty", "dockhand.sync.dirtyDates"] + let keys = ["dockhand.serverProfiles", "dockhand.selectedProfileID", "dockhand.sync.enabled", "dockhand.sync.pending", "dockhand.sync.records", "dockhand.sync.orderDirty", "dockhand.sync.dirty", "dockhand.sync.dirtyDates", "dockhand.sync.pendingDeletions"] withRestoredDefaults(keys: keys) { defaults in defaults.set(true, forKey: "dockhand.sync.enabled") let profile = DockhandServerProfile(id: UUID().uuidString, name: "Test", baseURL: "https://example.invalid") @@ -81,8 +81,8 @@ final class DockhandMobileTests: XCTestCase { func testCredentialMigrationPreservesTokenAndCustomHeaders() throws { let id = "sync-test-" + UUID().uuidString defer { - KeychainStore.deleteToken(profileID: id) - KeychainStore.deleteCustomHeaders(profileID: id) + try? KeychainStore.deleteToken(profileID: id) + try? KeychainStore.deleteCustomHeaders(profileID: id) } let expected = SyncedServerCredentials(token: "sample-token", headers: [.init(name: "X-Access", value: "sample-value")]) // Seed the pre-sync layout: separate token and header items. diff --git a/docs/icloud-server-sync.md b/docs/icloud-server-sync.md index 11274e4..436cb55 100644 --- a/docs/icloud-server-sync.md +++ b/docs/icloud-server-sync.md @@ -14,9 +14,11 @@ The feature is opt-in, requires iOS 26+, and uses the same signed app identifier Content conflicts resolve by modification date, then a deterministic mutation identifier. Order has its own modification date and mutation identifier, so moving a server does not revert an independently edited address or token. Equal positions resolve by server UUID. Clock skew can influence conflicts, as with any wall-clock last-writer policy. -Deletion writes a tombstone. Tombstones are retained, and older offline edits cannot recreate a deleted server. Deletion also removes that server's synchronized credential revisions when a participating device processes the tombstone. Historical credential versions of live servers remain in Keychain to support delayed record delivery; they are removed when that server is deleted. +Deletion writes a tombstone. A local deletion journal retains it while sync is off or the iCloud account is unavailable, then publishes it after sync is enabled and remote records are merged. Older offline edits cannot recreate a deleted server. Deletion also removes that server's synchronized credential revisions when a participating device processes the tombstone. When a live profile is edited, the previous credential snapshot is deleted after its replacement record is published. -Profiles and credentials travel independently. Until the matching credential version is available and installed, the server is marked pending and connection loading is blocked. Foreground polling checks delayed Keychain delivery; it does not assert that a successful local write means another device has received it. `synchronize()` is used on enable/foreground, not as a forced upload. +Profiles and credentials travel independently. Until the matching credential version is available and installed, the server is marked pending and connection loading is blocked. The app retries delayed Keychain delivery with backoff while active and checks again on foregrounding; it does not assert that a successful local write means another device has received it. `synchronize()` is used on enable/foreground, not as a forced upload. + +Tombstones are retained because an offline device may later return with an older profile record; there is no acknowledgement from every device that would make pruning safe. Each deleted profile therefore continues to use one KVS record key. A user with a large number of deleted profiles can eventually reach iCloud's KVS key or storage quota. A changed or missing iCloud identity disables participation and retains local records. Re-enabling is explicit. Turning sync off offers to keep or remove local records; neither choice deletes the shared iCloud records. Removing local records clears the app's profile journal and local credential mirrors; Apple-managed iCloud caches and synchronizable Keychain copies are not remotely deleted by this action. From 5b08ce1567f240c2775fd0f1381104084424e810 Mon Sep 17 00:00:00 2001 From: Giovanny Aranda Date: Sun, 15 Nov 2026 16:52:24 +0100 Subject: [PATCH 3/3] fix: harden iCloud sync conflict and credential cleanup - Keep offline tombstone timestamps so newer remote edits still win - Defer deleting superseded and tombstoned synced credentials for 24h - Drop pending deletions when the iCloud account changes - Cap credential retry polling and reset it on foreground or remote change - Fall back to local credentials when the synced item is missing --- DockhandMobile/Services/ServerSyncStore.swift | 60 +++++++++++++++---- DockhandMobileTests/DockhandMobileTests.swift | 2 +- 2 files changed, 51 insertions(+), 11 deletions(-) diff --git a/DockhandMobile/Services/ServerSyncStore.swift b/DockhandMobile/Services/ServerSyncStore.swift index c0aace1..d7fbb06 100644 --- a/DockhandMobile/Services/ServerSyncStore.swift +++ b/DockhandMobile/Services/ServerSyncStore.swift @@ -20,10 +20,18 @@ final class ServerSyncStore { guard let data = UserDefaults.standard.data(forKey: "dockhand.sync.pendingDeletions") else { return [:] } return (try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data)) ?? [:] }() + @ObservationIgnored private var supersededCredentials: [String: Date] = { + guard let data = UserDefaults.standard.data(forKey: "dockhand.sync.supersededCredentials") else { return [:] } + return (try? JSONDecoder().decode([String: Date].self, from: data)) ?? [:] + }() @ObservationIgnored private var credentialRetryTask: Task? @ObservationIgnored private var credentialRetryAttempt = 0 @ObservationIgnored private var owner: Data? private static let prefix = "server.v1." + /// Keychain and key-value changes reach other devices independently, so a replaced + /// credential item stays readable long enough for every device to merge the newer record. + private static let supersededCredentialGracePeriod: TimeInterval = 24 * 60 * 60 + private static let maxCredentialRetryAttempts = 8 init() { owner = UserDefaults.standard.data(forKey: "dockhand.sync.owner") @@ -40,6 +48,7 @@ final class ServerSyncStore { if reason == NSUbiquitousKeyValueStoreQuotaViolationChange { self.error = String(localized: "iCloud storage limit reached. Your servers remain saved locally.") } else { + self.credentialRetryAttempt = 0 self.refresh() } } @@ -56,7 +65,11 @@ final class ServerSyncStore { } let newOwner = try NSKeyedArchiver.archivedData(withRootObject: identity, requiringSecureCoding: false) // A different account starts a new journal; never upload the previous account's journal. - if !sameAccount(identity) { records = [:] } + if !sameAccount(identity) { + records = [:] + pendingDeletions = [:] + supersededCredentials = [:] + } owner = newOwner UserDefaults.standard.set(newOwner, forKey: "dockhand.sync.owner") cloud.synchronize() @@ -87,6 +100,7 @@ final class ServerSyncStore { dirty = [] dirtyDates = [:] pendingDeletions = [:] + supersededCredentials = [:] PreferencesStore.serverProfiles = [] PreferencesStore.selectedProfileID = nil } @@ -142,6 +156,7 @@ final class ServerSyncStore { } func foregroundRefresh() { + credentialRetryAttempt = 0 if enabled { cloud.synchronize() } refresh() } @@ -159,6 +174,7 @@ final class ServerSyncStore { } mergeRemote() flushPendingDeletions() + purgeSupersededCredentials() for (position, profile) in PreferencesStore.serverProfiles.enumerated() where dirty.contains(profile.id) { do { try publish(profile, position: position) } catch { self.error = String(localized: "Could not sync credentials. Your changes remain saved locally.") } @@ -171,7 +187,11 @@ final class ServerSyncStore { let id = record.profile.id if dirty.contains(id) { continue } if record.deleted { - SyncedServerCredentials.deleteAll(profileID: id) + // A newer edit from another device may still revive this profile, so its synced + // credential items are only removed once the tombstone has stood for the grace period. + if record.modified < Date().addingTimeInterval(-Self.supersededCredentialGracePeriod) { + SyncedServerCredentials.deleteAll(profileID: id) + } KeychainStore.deleteCredentials(profileID: id) PreferencesStore.removeSelectedEnvironmentID(for: id) PreferencesStore.removeCachedDashboardSnapshots(for: id) @@ -184,6 +204,10 @@ final class ServerSyncStore { if local.token != credentials.token || local.headers != credentials.headers { try KeychainStore.installSyncedCredentials(credentials, profileID: id) } + } else if (try? KeychainStore.credentialsForSync(profileID: id))?.token.isEmpty == false { + // The referenced item is missing, but this device still holds usable credentials. + // Keep using them instead of blocking the server; never republish them, since the + // newer item may simply not have arrived yet. } else { pending.insert(id) } } catch { pending.insert(id) } } @@ -220,6 +244,10 @@ final class ServerSyncStore { let deletions = try? JSONDecoder().decode([String: ServerSyncRecord].self, from: data) { pendingDeletions = deletions } + if let data = defaults.data(forKey: "dockhand.sync.supersededCredentials"), + let superseded = try? JSONDecoder().decode([String: Date].self, from: data) { + supersededCredentials = superseded + } return true } @@ -248,19 +276,28 @@ final class ServerSyncStore { dirtyDates.removeValue(forKey: profile.id) dirty.remove(profile.id) write(record) - if let previousCredentialID, previousCredentialID != credentialID { - SyncedServerCredentials.delete(previousCredentialID) + if let previousCredentialID, !previousCredentialID.isEmpty, previousCredentialID != credentialID { + supersededCredentials[previousCredentialID] = Date() + persist() } } + private func purgeSupersededCredentials() { + let referenced = Set(records.values.filter { !$0.deleted }.map(\.credentialID)) + let cutoff = Date().addingTimeInterval(-Self.supersededCredentialGracePeriod) + for (id, replaced) in supersededCredentials where replaced < cutoff { + if !referenced.contains(id) { SyncedServerCredentials.delete(id) } + supersededCredentials.removeValue(forKey: id) + } + persist() + } + private func flushPendingDeletions() { for (id, pending) in Array(pendingDeletions) { - var record = records[id].map { ServerSyncRecord.merged(pending, $0) } ?? pending - record.deleted = true - record.modified = max(Date(), max(record.modified, pending.modified).addingTimeInterval(0.001)) - record.mutation = UUID().uuidString + // Keep the tombstone's original stamp so a newer edit from another device still wins. + let record = records[id].map { ServerSyncRecord.merged(pending, $0) } ?? pending records[id] = record - write(record) + if record.deleted { write(record) } pendingDeletions.removeValue(forKey: id) } persist() @@ -273,7 +310,7 @@ final class ServerSyncStore { credentialRetryAttempt = 0 return } - guard credentialRetryTask == nil else { return } + guard credentialRetryTask == nil, credentialRetryAttempt < Self.maxCredentialRetryAttempts else { return } let delay = min(30, 1 << min(credentialRetryAttempt, 5)) credentialRetryAttempt += 1 credentialRetryTask = Task { @MainActor [weak self] in @@ -329,6 +366,9 @@ final class ServerSyncStore { if let data = try? JSONEncoder().encode(pendingDeletions) { UserDefaults.standard.set(data, forKey: "dockhand.sync.pendingDeletions") } + if let data = try? JSONEncoder().encode(supersededCredentials) { + UserDefaults.standard.set(data, forKey: "dockhand.sync.supersededCredentials") + } if let data = try? JSONEncoder().encode(records) { UserDefaults.standard.set(data, forKey: "dockhand.sync.records") } } } diff --git a/DockhandMobileTests/DockhandMobileTests.swift b/DockhandMobileTests/DockhandMobileTests.swift index c1db131..b1e899d 100644 --- a/DockhandMobileTests/DockhandMobileTests.swift +++ b/DockhandMobileTests/DockhandMobileTests.swift @@ -58,7 +58,7 @@ final class DockhandMobileTests: XCTestCase { @MainActor func testDisablingSyncCanKeepOrRemoveLocalRecords() throws { - let keys = ["dockhand.serverProfiles", "dockhand.selectedProfileID", "dockhand.sync.enabled", "dockhand.sync.pending", "dockhand.sync.records", "dockhand.sync.orderDirty", "dockhand.sync.dirty", "dockhand.sync.dirtyDates", "dockhand.sync.pendingDeletions"] + let keys = ["dockhand.serverProfiles", "dockhand.selectedProfileID", "dockhand.sync.enabled", "dockhand.sync.pending", "dockhand.sync.records", "dockhand.sync.orderDirty", "dockhand.sync.dirty", "dockhand.sync.dirtyDates", "dockhand.sync.pendingDeletions", "dockhand.sync.supersededCredentials"] withRestoredDefaults(keys: keys) { defaults in defaults.set(true, forKey: "dockhand.sync.enabled") let profile = DockhandServerProfile(id: UUID().uuidString, name: "Test", baseURL: "https://example.invalid")