Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 19 additions & 50 deletions apple/TablePro/Core/Compare/CompareSyncProfileStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,6 @@
// CompareSyncProfileStorage.swift
// TablePro
//
// Named comparison setups, keyed by source scope, target scope, and mode.
//
// The key used to be the pair of connection ids alone, which cannot tell two
// databases on one server apart. A profile saved under the old key is read back
// and adopted onto whatever database each connection currently points at, which
// is the same place it was saved from, so nothing is silently retargeted and
// nothing is thrown away.
//

import Foundation
import os
Expand All @@ -26,8 +18,7 @@ internal struct CompareSyncProfile: Codable, Hashable, Identifiable {
internal var selectedObjects: [String]
internal var tableScopes: [String: DataTableScope]

/// The compared-column exclusions a profile saved before they became per table. Read so a
/// saved comparison keeps leaving out the columns it left out, never written back.
// Column exclusions saved before they became per table, so an old comparison keeps leaving them out.
internal var legacyExcludedColumns: Set<String>

internal init(
Expand Down Expand Up @@ -87,9 +78,7 @@ internal struct CompareSyncProfile: Codable, Hashable, Identifiable {
dataOptions = try container.decodeIfPresent(DataCompareOptions.self, forKey: .dataOptions) ?? .default
selectedObjects = try container.decodeIfPresent([String].self, forKey: .selectedObjects) ?? []
tableScopes = try container.decodeIfPresent([String: DataTableScope].self, forKey: .tableScopes) ?? [:]
/// Kept on the profile once it has been read, because saving or deleting any comparison
/// rewrites the whole stored array, and a profile still waiting to be loaded would lose the
/// columns it was told to leave out.
// Carried once read: every save rewrites the whole array, and a profile not yet loaded would lose them.
if let carried = try container.decodeIfPresent(Set<String>.self, forKey: .legacyExcludedColumns) {
legacyExcludedColumns = carried
return
Expand Down Expand Up @@ -132,8 +121,10 @@ internal final class CompareSyncProfileStorage {
internal static let shared = CompareSyncProfileStorage()

private static let logger = Logger(subsystem: "com.TablePro", category: "CompareSyncProfileStorage")
private static let defaultsKey = "compareSyncProfiles"
private static let lastSetupKey = "compareSyncLastSetup"
private static let profilesKey = JSONDefaultsKey<[CompareSyncProfile]>("compareSyncProfiles")
// The same entry as written when a profile was keyed by the connection pair alone.
private static let legacyProfilesKey = JSONDefaultsKey<[LegacyProfile]>("compareSyncProfiles")
private static let lastSetupKey = JSONDefaultsKey<CompareSyncProfile>("compareSyncLastSetup")

private let defaults: UserDefaults

Expand All @@ -143,37 +134,22 @@ internal final class CompareSyncProfileStorage {

// MARK: - Last setup

/// The pair, the mode and the options the window last held, so reopening it lands on the same
/// comparison rather than on two empty pickers. It carries no included objects: what to change
/// is a decision about one comparison's results, and re-arming it against a report that has not
/// run yet would put a stale choice behind an Apply button.
// Holds no included objects: re-arming them before the report runs would put a stale choice behind Apply.
internal func lastSetup() -> CompareSyncProfile? {
guard let data = defaults.data(forKey: Self.lastSetupKey) else { return nil }
do {
return try JSONDecoder().decode(CompareSyncProfile.self, from: data)
} catch {
Self.logger.error("Failed to decode last setup: \(error.publicLogShape, privacy: .public)")
return nil
}
defaults.read(Self.lastSetupKey).value
}

internal func rememberSetup(_ profile: CompareSyncProfile) {
do {
defaults.set(try JSONEncoder().encode(profile), forKey: Self.lastSetupKey)
} catch {
Self.logger.error("Failed to persist last setup: \(error.publicLogShape, privacy: .public)")
}
try? defaults.write(profile, to: Self.lastSetupKey)
}

// MARK: - Saved comparisons

internal func allProfiles() -> [CompareSyncProfile] {
guard let data = defaults.data(forKey: Self.defaultsKey) else { return [] }
do {
return try JSONDecoder().decode([CompareSyncProfile].self, from: data)
} catch {
Self.logger.error("Failed to decode profiles: \(error.publicLogShape, privacy: .public)")
return migrateLegacyProfiles(from: data)
switch defaults.read(Self.profilesKey) {
case .missing: return []
case .value(let profiles): return profiles
case .unreadable: return migrateLegacyProfiles()
}
}

Expand All @@ -192,21 +168,15 @@ internal final class CompareSyncProfileStorage {
}

private func persist(_ profiles: [CompareSyncProfile]) {
do {
defaults.set(try JSONEncoder().encode(profiles), forKey: Self.defaultsKey)
} catch {
Self.logger.error("Failed to persist profiles: \(error.publicLogShape, privacy: .public)")
}
try? defaults.write(profiles, to: Self.profilesKey)
}

/// A profile written before an endpoint carried a database is adopted onto whichever database
/// its connections currently point at, which is where it was saved from. Discarding them
/// instead would lose setups the user had already named.
private func migrateLegacyProfiles(from data: Data) -> [CompareSyncProfile] {
guard let legacy = try? JSONDecoder().decode([LegacyProfile].self, from: data) else { return [] }
// Adopted onto the database each connection points at now, which is where it was saved from.
private func migrateLegacyProfiles() -> [CompareSyncProfile] {
guard let legacy = defaults.read(Self.legacyProfilesKey).value else { return [] }
let connections = ConnectionStorage.shared.loadConnections()
let databaseByConnection = Dictionary(
connections.map { ($0.id, $0.database ?? "") }, uniquingKeysWith: { first, _ in first }
connections.map { ($0.id, $0.database) }, uniquingKeysWith: { first, _ in first }
)
let migrated = legacy.map { entry in
CompareSyncProfile(
Expand Down Expand Up @@ -244,8 +214,7 @@ internal final class CompareSyncProfileStorage {
let structureOptions: StructureCompareOptions
let dataOptions: DataCompareOptions
let selectedTables: [String]
/// The compared-column exclusions this shape stored inside its options, read here because
/// `DataCompareOptions` no longer carries them and the migration is the last chance to.
// Stored inside the options, which no longer carry it, so the migration is the last chance to read it.
let excludedColumns: Set<String>

private enum CodingKeys: String, CodingKey {
Expand Down
24 changes: 2 additions & 22 deletions apple/TablePro/Core/ConnectionLibrary/RecentConnectionsStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,12 @@

import Combine
import Foundation
import os
import TableProConnectionLibrary

@MainActor
internal final class RecentConnectionsStore: ObservableObject {
internal static let shared = RecentConnectionsStore()

nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "RecentConnectionsStore")

private let defaults: UserDefaults
private let appEvents: AppEvents
@Published internal private(set) var ledger: RecentConnectionsLedger
Expand All @@ -24,7 +21,7 @@ internal final class RecentConnectionsStore: ObservableObject {
) {
self.defaults = defaults
self.appEvents = appEvents
self.ledger = Self.load(from: defaults)
self.ledger = defaults.read(PreferenceKeys.recentConnections).value ?? RecentConnectionsLedger()
}

internal var lastConnected: [UUID: Date] {
Expand Down Expand Up @@ -58,24 +55,7 @@ internal final class RecentConnectionsStore: ObservableObject {
private func commit(_ updated: RecentConnectionsLedger) {
guard updated != ledger else { return }
ledger = updated
do {
let data = try JSONEncoder().encode(updated)
defaults.set(data, forKey: PreferenceKeys.recentConnections.name)
} catch {
Self.logger.error("Failed to save recent connections: \(error.publicLogShape, privacy: .public)")
}
try? defaults.write(updated, to: PreferenceKeys.recentConnections)
appEvents.connectionListStateChanged.send(())
}

private static func load(from defaults: UserDefaults) -> RecentConnectionsLedger {
guard let data = defaults.data(forKey: PreferenceKeys.recentConnections.name) else {
return RecentConnectionsLedger()
}
do {
return try JSONDecoder().decode(RecentConnectionsLedger.self, from: data)
} catch {
logger.error("Discarding unreadable recent connections: \(error.publicLogShape, privacy: .public)")
return RecentConnectionsLedger()
}
}
}
56 changes: 8 additions & 48 deletions apple/TablePro/Core/MCP/Outside/MCPServerStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,29 @@

import Combine
import Foundation
import os
import TableProMCP

/// The outside MCP servers this Mac knows about, and their bearer tokens.
///
/// The configuration is device-local JSON in UserDefaults; the token is in the Keychain, keyed by
/// the server's id, so removing a server removes its credential and nothing else has to remember to.
/// Nothing here syncs: a server reachable from this Mac is not necessarily reachable from another,
/// and a token that travelled would be a credential the user did not choose to copy.
// Device-local and never synced: a server this Mac reaches may not be reachable from another.
@MainActor
internal final class MCPServerStore: ObservableObject {
internal static let shared = MCPServerStore()

nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "MCPServerStore")

private static let defaultsKey = "com.TablePro.mcp.outsideServers"
private static let serversKey = JSONDefaultsKey<[MCPServerConfiguration]>("com.TablePro.mcp.outsideServers")

@Published internal private(set) var servers: [MCPServerConfiguration] = []

private let defaults: UserDefaults
private let keychain: any KeychainStoring

/// Both come from `AppStorageEnvironment` rather than from `.standard` and the real Keychain.
/// A store that names those directly reads the developer's own data under test isolation, which
/// is the one thing the sandbox exists to prevent.
/// The defaults come from `AppStorageEnvironment` rather than from `.standard`, so a store that
/// names them directly cannot read the developer's own data under test isolation.
///
/// The Keychain is `MCPServerTokenKeychain` in production and the sandbox's own file store under
/// test. `AppStorageEnvironment.keychain` is `KeychainHelper`, which marks every item
/// synchronizable once the user turns on connection password sync, and a token for a server
/// this Mac can reach is not a credential they chose to copy to another one.
// Not `AppStorageEnvironment.keychain` in production: it syncs items once password sync is on.
internal init(
defaults: UserDefaults = AppStorageEnvironment.shared.defaults,
keychain: (any KeychainStoring)? = nil
) {
self.defaults = defaults
let environment = AppStorageEnvironment.shared
self.keychain = keychain ?? (environment.isIsolated ? environment.keychain : MCPServerTokenKeychain())
servers = Self.decode(defaults.data(forKey: Self.defaultsKey))
servers = defaults.read(Self.serversKey).value ?? []
}

// MARK: - Reads
Expand All @@ -53,15 +36,12 @@ internal final class MCPServerStore: ObservableObject {
servers.first { $0.id == id }
}

/// The servers a session on this connection may reach. A nil connection reaches none: a session
/// with no connection cannot pass the allowlist, and defaulting to "all" there would make a
/// half-built session the most privileged one in the app.
// A nil connection reaches none, so a half-built session is never the most privileged one.
internal func servers(allowedFor connectionId: UUID?) -> [MCPServerConfiguration] {
guard let connectionId else { return [] }
return servers.filter { $0.allowedConnectionIds.contains(connectionId) }
}

/// Whether one tool name, already namespaced, belongs to a server this connection may reach.
internal func allowsTool(named toolName: String, connectionId: UUID?) -> Bool {
guard let server = server(owningTool: toolName) else { return false }
return server.allows(connectionId: connectionId)
Expand Down Expand Up @@ -96,8 +76,6 @@ internal final class MCPServerStore: ObservableObject {
return nil
}

/// Removes the server and its credential together. A token left behind would be a live secret
/// for a server the user believes they deleted.
internal func remove(id: UUID) {
servers.removeAll { $0.id == id }
keychain.delete(forKey: Self.tokenKey(id))
Expand All @@ -116,9 +94,7 @@ internal final class MCPServerStore: ObservableObject {
persist()
}

/// Called when a connection is deleted, so its id does not sit in an allowlist forever. A new
/// connection cannot inherit it (ids are fresh UUIDs), but a stale entry makes the settings pane
/// lie about how far a server reaches.
// A stale id would make the settings pane overstate how far a server reaches.
internal func forgetConnection(_ connectionId: UUID) {
var next = servers
var changed = false
Expand All @@ -131,9 +107,7 @@ internal final class MCPServerStore: ObservableObject {
persist()
}

/// Nil for a locked or cancelled Keychain as well as a missing token. The call that needs it
/// fails with the server unreachable, which is the honest report: a token TablePro cannot read is
/// a token it does not have.
// Nil for a locked or cancelled Keychain too: the call then fails with the server unreachable.
internal func token(for serverId: UUID) -> String? {
guard case .found(let token) = keychain.readStringResult(forKey: Self.tokenKey(serverId)) else {
return nil
Expand All @@ -148,20 +122,6 @@ internal final class MCPServerStore: ObservableObject {
}

private func persist() {
do {
defaults.set(try JSONEncoder().encode(servers), forKey: Self.defaultsKey)
} catch {
Self.logger.error("Failed to persist outside MCP servers: \(error.localizedDescription)")
}
}

private static func decode(_ data: Data?) -> [MCPServerConfiguration] {
guard let data else { return [] }
do {
return try JSONDecoder().decode([MCPServerConfiguration].self, from: data)
} catch {
Self.logger.error("Failed to load outside MCP servers: \(error.localizedDescription)")
return []
}
try? defaults.write(servers, to: Self.serversKey)
}
}
38 changes: 20 additions & 18 deletions apple/TablePro/Core/Services/TeamLibrary/TeamLibraryState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -151,28 +151,26 @@ internal struct TeamLibraryStateStore {
func loadAll() -> [TeamLibraryTeamState] {
let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []
return files.filter { $0.pathExtension == "json" }.compactMap { file in
guard let data = try? Data(contentsOf: file) else { return nil }
do {
return try JSONDecoder().decode(TeamLibraryTeamState.self, from: data)
} catch {
Self.logger.error("Dropping an unreadable team library file: \(error.publicLogShape, privacy: .public)")
try? FileManager.default.removeItem(at: file)
let store = JSONFileStore<TeamLibraryTeamState>(url: file)
switch store.read() {
case .value(let state):
return state
case .unreadable(let error) where error is DecodingError:
try? store.remove()
return nil
// A file that could not be read at all is kept for the next launch.
case .missing, .unreadable:
return nil
}
}
}

func save(_ state: TeamLibraryTeamState) {
do {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
try JSONEncoder().encode(state).write(to: file(for: state.teamID), options: .atomic)
} catch {
Self.logger.error("Could not store the team library: \(error.publicLogShape, privacy: .public)")
}
try? teamFile(state.teamID).write(state)
}

func remove(teamID: String) {
try? FileManager.default.removeItem(at: file(for: teamID))
try? teamFile(teamID).remove()
}

func removeAll() {
Expand All @@ -182,23 +180,27 @@ internal struct TeamLibraryStateStore {

// What the last /v1 pull cached, keyed by client ID like a /v2 snapshot, so the first one matches it item by item.
func loadLegacy(now: Date) -> TeamLibraryLegacyLibrary? {
guard let data = try? Data(contentsOf: legacyFile) else { return nil }
guard let cache = legacyCache.read().value else { return nil }
do {
return try JSONDecoder().decode(TeamLibraryLegacyCache.self, from: data).library(at: now)
return try cache.library(at: now)
} catch {
Self.logger.error("The /v1 team library cache is unreadable: \(error.publicLogShape, privacy: .public)")
return nil
}
}

func removeLegacy() {
try? FileManager.default.removeItem(at: legacyFile)
try? legacyCache.remove()
defaults.removeObject(forKey: Self.legacyPullKey)
}

private func file(for teamID: String) -> URL {
private var legacyCache: JSONFileStore<TeamLibraryLegacyCache> {
JSONFileStore(url: legacyFile)
}

private func teamFile(_ teamID: String) -> JSONFileStore<TeamLibraryTeamState> {
let name = String(teamID.unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) || $0 == "_" })
return directory.appendingPathComponent("\(name).json")
return JSONFileStore(url: directory.appendingPathComponent("\(name).json"))
}
}

Expand Down
Loading
Loading