From c2818b1c8c6fa8332e55cdb7e8ab8372dc5345d8 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 07:37:16 +0700 Subject: [PATCH 1/3] fix(macos): keep sessions on the SSH route they dialed, narrow link trust, conceal secret copies and confirm Settings deletes --- .../ConnectionDestination.swift | 4 +- .../ConnectionDestinationTests.swift | 3 +- apple/TablePro/AppDelegate.swift | 7 +- .../Core/Database/ConnectionTunnelError.swift | 3 + .../DatabaseManager+EnsureConnected.swift | 11 +-- .../Database/DatabaseManager+Health.swift | 4 +- .../Core/Database/DatabaseManager+SSH.swift | 16 +++- .../Database/DatabaseManager+Sessions.swift | 67 ++++++++++++-- .../Core/Database/DatabaseManager.swift | 4 + .../Database/EnvVarReferenceConsent.swift | 2 +- .../Database/LocalCredentialConsent.swift | 2 +- .../Plugins/PluginManager+Lifecycle.swift | 25 +++++ .../Infrastructure/ClipboardService.swift | 5 +- .../ExternalConnectionGate.swift | 13 ++- .../ExternalConnectionPrompting.swift | 33 ++++++- .../MainSplitViewController+Connection.swift | 22 ++--- .../Services/Infrastructure/TabRouter.swift | 6 +- .../Infrastructure/WindowManager.swift | 2 +- .../Core/Storage/AppSettingsManager.swift | 22 ++++- .../Core/Storage/AppSettingsStorage.swift | 2 +- .../Storage/ConnectionApprovalStore.swift | 9 +- .../Storage/IntegrityStampedFileStore.swift | 12 ++- .../ExternalConnectionTrustKey.swift | 11 ++- apple/TablePro/Models/AI/AIModels.swift | 10 ++ .../DatabaseConnection+Destination.swift | 30 +++--- .../Models/Settings/SyncSettings.swift | 5 + .../TablePro/Resources/Localizable.xcstrings | 27 ++++++ .../WelcomeViewModel+TeamLibrary.swift | 7 +- .../Views/Components/DiagramExporter.swift | 4 + .../Views/ERDiagram/ERDiagramScene.swift | 32 +++++-- .../Views/ERDiagram/ERDiagramView.swift | 6 +- .../Views/Settings/AISettingsView.swift | 3 +- .../Settings/CustomSlashCommandsSection.swift | 19 +++- .../Views/Settings/GeneralSettingsView.swift | 2 +- .../Views/Settings/KeyboardSettingsView.swift | 11 ++- .../Plugins/InstalledPluginsView.swift | 24 +++-- .../Views/Settings/Sections/SyncSection.swift | 25 ----- .../TrustedExternalConnectionsSection.swift | 12 ++- .../Views/Settings/SyncSettingsView.swift | 2 +- .../Database/DatabaseManagerTunnelTests.swift | 39 ++++++++ .../Database/PromptedPasswordKeyTests.swift | 19 ++++ .../Database/SessionRecoveryLoopTests.swift | 92 ++++++++++++++++++- .../Plugins/RejectedPluginRemovalTests.swift | 87 ++++++++++++++++++ .../Core/Services/ClipboardServiceTests.swift | 16 ++++ .../ExternalConnectionGateTests.swift | 68 ++++++++++++++ .../AppSettingsStorageResetTests.swift | 23 +++++ .../AppSettingsSyncSideEffectsTests.swift | 79 ++++++++++++++++ .../ConnectionApprovalStoreTests.swift | 20 ++++ .../ConnectionStoragePersistenceTests.swift | 22 +++++ .../Helpers/RecordingClipboard.swift | 6 ++ .../WelcomeViewModelTeamLibraryTests.swift | 24 +++++ .../ERDiagramBitmapExportTests.swift | 75 +++++++++++++++ 52 files changed, 939 insertions(+), 135 deletions(-) create mode 100644 apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift create mode 100644 apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift create mode 100644 apple/TableProTests/Views/ERDiagram/ERDiagramBitmapExportTests.swift diff --git a/apple/Packages/TableProCore/Sources/TableProConnectionLibrary/ConnectionDestination.swift b/apple/Packages/TableProCore/Sources/TableProConnectionLibrary/ConnectionDestination.swift index fe424e678d..a9ef52212e 100644 --- a/apple/Packages/TableProCore/Sources/TableProConnectionLibrary/ConnectionDestination.swift +++ b/apple/Packages/TableProCore/Sources/TableProConnectionLibrary/ConnectionDestination.swift @@ -20,9 +20,9 @@ public struct ConnectionDestination: Equatable, Sendable { case verifyIdentity } + // A linked SSH profile is named by the servers it dials, so moving the profile moves the destination. public enum Tunnel: Equatable, Sendable { case none - case profile(UUID) case ssh(server: Endpoint, jumps: [Endpoint]) } @@ -100,8 +100,6 @@ public struct ConnectionDestination: Equatable, Sendable { switch tunnel { case .none: return "none" - case .profile(let id): - return "profile:" + id.uuidString.lowercased() case .ssh(let server, let jumps): return ([server] + jumps) .map { Self.normalizedHost($0.host) + ":" + String($0.port) } diff --git a/apple/Packages/TableProCore/Tests/TableProConnectionLibraryTests/ConnectionDestinationTests.swift b/apple/Packages/TableProCore/Tests/TableProConnectionLibraryTests/ConnectionDestinationTests.swift index 024f2d9d23..57e3d833a6 100644 --- a/apple/Packages/TableProCore/Tests/TableProConnectionLibraryTests/ConnectionDestinationTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProConnectionLibraryTests/ConnectionDestinationTests.swift @@ -23,7 +23,7 @@ struct ConnectionDestinationTests { #expect(saved.digest != crafted.digest) } - @Test("Engine, TLS, SSH server, jump host, SSH profile and any plugin field each change the digest") + @Test("Engine, TLS, SSH server, jump host and any plugin field each change the digest") func everyRoutingInputChangesTheDigest() { let jumpless = ConnectionDestination.Tunnel.ssh( server: .init(host: "bastion.prod", port: 22), jumps: [] @@ -46,7 +46,6 @@ struct ConnectionDestinationTests { jumps: [.init(host: "hop.attacker.example", port: 22)] ) ), - Self.production(transport: .verifyIdentity, tunnel: .profile(UUID())), Self.production(transport: .verifyIdentity, tunnel: jumpless, fields: ["esSkipTLSVerify": "true"]), Self.production(transport: .verifyIdentity, tunnel: jumpless, fields: ["someFutureField": "x"]), ] diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 87a96c7c4c..f2b804510a 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -85,9 +85,10 @@ class AppDelegate: NSObject, NSApplicationDelegate { KeyRepeatFilter.shared.install() TableClickFocus.shared.install() RecentTabSwitcherController.installEditorKeyClaim() - let syncSettings = AppSettingsStorage.shared.loadSync() - let passwordSyncExpected = syncSettings.enabled && syncSettings.syncConnections && syncSettings.syncPasswords - AppStorageEnvironment.shared.defaults.set(passwordSyncExpected, forKey: KeychainHelper.passwordSyncEnabledKey) + AppStorageEnvironment.shared.defaults.set( + AppSettingsStorage.shared.loadSync().syncsPasswords, + forKey: KeychainHelper.passwordSyncEnabledKey + ) DatabaseManager.shared.startObservingSystemEvents() DatabaseManager.shared.tabStatePersister = SessionTabStatePersister() diff --git a/apple/TablePro/Core/Database/ConnectionTunnelError.swift b/apple/TablePro/Core/Database/ConnectionTunnelError.swift index 234178b0e0..6f8912c462 100644 --- a/apple/TablePro/Core/Database/ConnectionTunnelError.swift +++ b/apple/TablePro/Core/Database/ConnectionTunnelError.swift @@ -5,6 +5,7 @@ enum ConnectionTunnelError: Error, LocalizedError, Equatable { case remoteFileUnsupported(String) case remoteFilePathMissing case srvLookupBehindTunnel + case sshProfileMoved static func refusal(for connection: DatabaseConnection) -> ConnectionTunnelError? { guard connection.enabledTunnelKinds.contains(where: { $0 != .remoteFile && $0 != .remoteDatabaseSession }) @@ -36,6 +37,8 @@ enum ConnectionTunnelError: Error, LocalizedError, Equatable { An SRV record names servers the tunnel cannot reach, so the connection would go around it. Turn the tunnel \ off, or list the servers under Hosts and turn off Use SRV Record. """) + case .sshProfileMoved: + return String(localized: "The SSH profile this connection uses now points to another server. Click Reconnect in its window to use it.") } } } diff --git a/apple/TablePro/Core/Database/DatabaseManager+EnsureConnected.swift b/apple/TablePro/Core/Database/DatabaseManager+EnsureConnected.swift index 2b4af026a3..71d309b4f9 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+EnsureConnected.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+EnsureConnected.swift @@ -11,12 +11,10 @@ extension DatabaseManager { _ connection: DatabaseConnection, passwordOverride: String? = nil, sshPasswordOverride: String? = nil, - trigger: ConnectTrigger = .request + trigger: ConnectTrigger = .request, + adoptsSSHProfileEdits: Bool = false ) async throws { - /// An installed driver is only a reason to skip while it still answers. A reconnect that - /// gave up leaves one behind, and returning here made Reconnect a button that did nothing - /// on the one connection that needed it. A driver nobody has heard from in a while is the - /// same problem one step earlier, which is what the check answers. + // A driver is a reason to skip only while it answers: one a reconnect gave up on made Reconnect do nothing. await verifyBeforeUse(connection.id) if let session = activeSessions[connection.id], session.driver != nil, session.liveness == .live { return @@ -26,7 +24,8 @@ extension DatabaseManager { connection, passwordOverride: passwordOverride, sshPasswordOverride: sshPasswordOverride, - trigger: trigger + trigger: trigger, + adoptsSSHProfileEdits: adoptsSSHProfileEdits ) } } diff --git a/apple/TablePro/Core/Database/DatabaseManager+Health.swift b/apple/TablePro/Core/Database/DatabaseManager+Health.swift index a82634ef22..bcc87c5f33 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Health.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Health.swift @@ -213,7 +213,7 @@ extension DatabaseManager { } // A refusal that needs a person gets the same answer on every retry. if error is EnvVarReferenceConsentError || error is PreConnectScriptConsentError - || error is LocalCredentialConsentError { + || error is LocalCredentialConsentError || error is ConnectionTunnelError { return .stop(ConnectionFailureClassifier.info(for: error)) } guard isAuthenticationFailure(error) else { return .retry(nil) } @@ -284,6 +284,7 @@ extension DatabaseManager { } let connectionForDriver = try await buildEffectiveConnection( for: connection, + pinnedSSHRoute: session.connection.destinationTunnel, deadline: deadline, ownsAttempt: { self.isCurrentAttempt(generation, for: connectionId) } ) @@ -467,6 +468,7 @@ extension DatabaseManager { let deadline = ConnectionDeadline(configuredSeconds: connection.connectTimeoutSeconds) let effectiveConnection = try await buildEffectiveConnection( for: connection, + pinnedSSHRoute: session.connection.destinationTunnel, deadline: deadline, ownsAttempt: { self.isCurrentAttempt(generation, for: sessionId) } ) diff --git a/apple/TablePro/Core/Database/DatabaseManager+SSH.swift b/apple/TablePro/Core/Database/DatabaseManager+SSH.swift index 629955c883..bbf27fc1b4 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+SSH.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+SSH.swift @@ -7,6 +7,7 @@ import Foundation +import TableProConnectionLibrary import TableProSSHConfig import TableProSSHTransport @@ -16,13 +17,15 @@ extension DatabaseManager { // `sshPasswordOverride` is the password Test Connection typed, used instead of the stored one. // `ownsAttempt` is asked with nothing suspending before the tunnel is created: tunnels are keyed by // connection, and creating one closes whatever a newer attempt opened under the same id. + // `pinnedSSHRoute` is the route an open session dialed: a linked profile moved since then is refused, not followed. internal func buildEffectiveConnection( for original: DatabaseConnection, sshPasswordOverride: String? = nil, + pinnedSSHRoute: ConnectionDestination.Tunnel? = nil, deadline: ConnectionDeadline, ownsAttempt: () -> Bool = { true } ) async throws -> DatabaseConnection { - var connection = SSHProfileStorage.shared.refreshingLinkedProfile(original) + var connection = try routedThroughLinkedProfile(original, pinnedSSHRoute: pinnedSSHRoute) // Only the tunnel this connect opens says it secures the transport or names the server behind it; a saved or // imported field never does. connection.additionalFields[DatabaseConnection.tunnelSecuresTransportKey] = nil @@ -127,6 +130,17 @@ extension DatabaseManager { ) } + internal func routedThroughLinkedProfile( + _ connection: DatabaseConnection, + pinnedSSHRoute: ConnectionDestination.Tunnel? + ) throws -> DatabaseConnection { + let routed = SSHProfileStorage.shared.refreshingLinkedProfile(connection) + if let pinnedSSHRoute, case .profile = routed.sshTunnelMode, routed.destinationTunnel != pinnedSSHRoute { + throw ConnectionTunnelError.sshProfileMoved + } + return routed + } + // MARK: - SSH Tunnel Recovery func handleSSHTunnelDied(connectionId: UUID) async { diff --git a/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift b/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift index 36c19de2ac..793d3e525d 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift @@ -20,7 +20,8 @@ extension DatabaseManager { _ requestedConnection: DatabaseConnection, passwordOverride incomingPasswordOverride: String? = nil, sshPasswordOverride: String? = nil, - trigger: ConnectTrigger = .request + trigger: ConnectTrigger = .request, + adoptsSSHProfileEdits: Bool = false ) async throws { let connection = resolvedConnectionDefinition(for: requestedConnection) @@ -49,6 +50,12 @@ extension DatabaseManager { let effectiveQueryTimeoutSeconds = prepareConnectingSession(for: connection) lastActiveSessionId = connection.id + let (routedConnection, pinnedSSHRoute) = try pinSSHRoute( + for: connection, + adoptsSSHProfileEdits: adoptsSSHProfileEdits, + attempt: attempt + ) + let (resolvedConnection, dialledConnection) = try await authorizeConnect( connection, trigger: trigger, @@ -76,6 +83,7 @@ extension DatabaseManager { effectiveConnection = try await buildEffectiveConnectionReportingStages( for: dialledConnection, sshPasswordOverride: sshPasswordOverride, + pinnedSSHRoute: pinnedSSHRoute, deadline: deadline, attempt: (attempt, connection.id) ) @@ -148,9 +156,10 @@ extension DatabaseManager { // Batch all session mutations into a single write to fire objectWillChange once. if var session = activeSessions[connection.id] { session.connection = successfulConnectionRecord( - from: connection, + from: routedConnection, preservingSessionFieldsFrom: session.connection ) + dialedConnections[connection.id] = routedConnection session.driver = driver session.status = driver.status session.effectiveConnection = effectiveConnection @@ -162,10 +171,7 @@ extension DatabaseManager { markSessionVerified(connection.id) if let passwordOverride, !connection.usesIAMToken { session.cachedPassword = passwordOverride - /// Only a password that actually authenticated is shared with the other - /// connections on this profile. Caching the prompt's answer before the connect - /// meant one mistyped password locked every one of them out until a relaunch, - /// because the prompt never came back. + // Only once it authenticated: a mistyped answer shared with the profile locked every connection out. if promptsForPassword { promptedPasswords[promptCacheKey] = passwordOverride } @@ -173,7 +179,7 @@ extension DatabaseManager { setSession(session, for: connection.id) } - /// Before `finish`, so the clear is still the current attempt's to make. + // Before `finish`, so the clear is still the current attempt's to make. clearConnectionStage(for: connection.id) connectionAttempts.finish(attempt, for: connection.id) @@ -216,7 +222,7 @@ extension DatabaseManager { } // A session's answer is reused only while the connection still dials where it was typed for. let session = activeSessions[connection.id] - let sessionPassword = session?.connection.destination.digest == connection.destination.digest + let sessionPassword = session?.connection.destination.digest == connection.dialedDestination.digest ? session?.cachedPassword : nil if let cached = promptedPasswords[promptCacheKey] ?? sessionPassword { @@ -246,7 +252,7 @@ extension DatabaseManager { let sharedByProfile = connection.credentialMode.profileId != nil return PromptedPasswordKey( owner: ConnectionCredentialResolver.promptCacheKey(for: connection), - destination: sharedByProfile ? "" : connection.destination.digest + destination: sharedByProfile ? "" : connection.dialedDestination.digest ) } @@ -648,6 +654,8 @@ extension DatabaseManager { guard let previous = session(for: connectionId) else { throw DatabaseError.notConnected } + // Refused before anything is torn down, so the session stays on the server it dialed. + _ = try routedThroughLinkedProfile(previous.connection, pinnedSSHRoute: previous.connection.destinationTunnel) // The reconnect would end a live transaction; one on a connection that already stopped answering is gone anyway. if previous.liveness == .live, await browsedDriverHoldsTransaction(previous.driver, for: connectionId) { throw DatabaseError.connectionFailed( @@ -775,6 +783,8 @@ extension DatabaseManager { /// first: `MainContentCoordinator.teardown()` clears them from memory and only the window-close /// path saves on its way out, which is how a disconnect used to take a window's tabs with it. func disconnectSession(_ sessionId: UUID, origin: SessionDisconnectOrigin = .appManaged) async { + // Before the lookup: closing the window of a connect that failed has no session to end, only the route. + dialedConnections[sessionId] = nil let lifecycleLogger = Logger(subsystem: "com.TablePro", category: "NativeTabLifecycle") guard let session = activeSessions[sessionId] else { lifecycleLogger.info( @@ -1105,10 +1115,48 @@ extension DatabaseManager { } } + // Read once, before any approval is asked for, so the approvals and the dial name one route. A session that + // already dialed keeps its route under its window; only that window's Connect takes up a profile edit. + private func pinSSHRoute( + for connection: DatabaseConnection, + adoptsSSHProfileEdits: Bool, + attempt: Int + ) throws -> (routed: DatabaseConnection, pinned: ConnectionDestination.Tunnel) { + let routed = SSHProfileStorage.shared.refreshingLinkedProfile(connection) + let kept = adoptsSSHProfileEdits + ? nil + : activeSessions[connection.id].flatMap { $0.effectiveConnection == nil ? nil : $0.connection } + ?? dialedConnections[connection.id] + let pinned = kept?.destinationTunnel ?? routed.destinationTunnel + // A deleted profile leaves its last server inline, so a session dialed through one is checked as well. + guard Self.followsSSHProfile(routed) || kept.map(Self.followsSSHProfile) == true, + routed.destinationTunnel != pinned + else { return (routed, pinned) } + let error = ConnectionTunnelError.sshProfileMoved + if connectionAttempts.isCurrent(attempt, for: connection.id) { + clearConnectionStage(for: connection.id) + } + // A session that dialed stays, unreachable, under its window; an entry this attempt made goes. + if let driver = activeSessions[connection.id]?.driver { + let info = ConnectionFailureClassifier.info(for: error) + updateSession(connection.id) { $0.status = .error(info.message) } + markSessionUnreachable(connection.id, startedWith: driver, info: info) + } else { + finalizeConnectionFailure(for: connection.id, cancelled: false, error: error, attempt: attempt) + } + throw error + } + + private static func followsSSHProfile(_ connection: DatabaseConnection) -> Bool { + if case .profile = connection.sshTunnelMode { return true } + return false + } + // The proxy reports its download as a stage of this attempt. private func buildEffectiveConnectionReportingStages( for resolvedConnection: DatabaseConnection, sshPasswordOverride: String?, + pinnedSSHRoute: ConnectionDestination.Tunnel, deadline: ConnectionDeadline, attempt: (number: Int, connectionId: UUID) ) async throws -> DatabaseConnection { @@ -1118,6 +1166,7 @@ extension DatabaseManager { try await buildEffectiveConnection( for: resolvedConnection, sshPasswordOverride: sshPasswordOverride, + pinnedSSHRoute: pinnedSSHRoute, deadline: deadline, ownsAttempt: { !self.isAttemptCancelled(attempt.number, for: attempt.connectionId) } ) diff --git a/apple/TablePro/Core/Database/DatabaseManager.swift b/apple/TablePro/Core/Database/DatabaseManager.swift index 275998de5a..4b8501ee18 100644 --- a/apple/TablePro/Core/Database/DatabaseManager.swift +++ b/apple/TablePro/Core/Database/DatabaseManager.swift @@ -120,6 +120,10 @@ final class DatabaseManager: ObservableObject { /// before touching shared session state and discards its driver when it lost. internal var connectionAttempts = ConnectionAttemptRegistry() + // What each connection last dialed, kept through a failed connect so an unattended one cannot follow an SSH profile + // edit under the window; a disconnect ends it, and the window's own Connect replaces it. + internal var dialedConnections: [UUID: DatabaseConnection] = [:] + /// The step each in-flight connect last reported, so a window that joins one already running /// can seed itself. `AppEvents.connectionStageChanged` is a `PassthroughSubject`, so it holds /// nothing: an observer built after a step was sent could only report the generic fallback, diff --git a/apple/TablePro/Core/Database/EnvVarReferenceConsent.swift b/apple/TablePro/Core/Database/EnvVarReferenceConsent.swift index 49fe876501..96c2aca3b1 100644 --- a/apple/TablePro/Core/Database/EnvVarReferenceConsent.swift +++ b/apple/TablePro/Core/Database/EnvVarReferenceConsent.swift @@ -96,7 +96,7 @@ internal final class EnvVarReferenceConsent { EnvVarReferenceQuestion( connectionName: connection.name, names: EnvVarResolver.referencedNames(in: connection).sorted(), - destination: connection.destinationSummary, + destination: SSHProfileStorage.shared.refreshingLinkedProfile(connection).destinationSummary, origin: connection.origin ) } diff --git a/apple/TablePro/Core/Database/LocalCredentialConsent.swift b/apple/TablePro/Core/Database/LocalCredentialConsent.swift index a63b8a5d28..bddb50eca7 100644 --- a/apple/TablePro/Core/Database/LocalCredentialConsent.swift +++ b/apple/TablePro/Core/Database/LocalCredentialConsent.swift @@ -94,7 +94,7 @@ internal final class LocalCredentialConsent { uses: ConnectionFieldCatalog.localCredentialUses(in: connection.additionalFields).map { use in describe(use, fields: fields) }, - destination: connection.destinationSummary, + destination: SSHProfileStorage.shared.refreshingLinkedProfile(connection).destinationSummary, origin: connection.origin ) } diff --git a/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift b/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift index 12bfefacba..b5067794fa 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift @@ -35,4 +35,29 @@ extension PluginManager { Self.logger.info("Uninstalled plugin '\(id)'") needsRestart = true } + + // Only a bundle in the user's plugins folder: one inside the app breaks its seal, and no registry install brings + // a bundled engine back. + func canRemoveRejectedPlugin(_ plugin: RejectedPlugin) -> Bool { + let bundle = plugin.url.standardizedFileURL + guard !bundle.lastPathComponent.isEmpty, bundle.lastPathComponent != "/" else { return false } + // The folder, not the bundle, is resolved: a bundle linked in from a build folder is still the user's to remove. + let folder = bundle.deletingLastPathComponent().resolvingSymlinksInPath().path + return folder == userPluginsDir.standardizedFileURL.resolvingSymlinksInPath().path + } + + // To the Trash rather than deleted, so a mistaken removal can be put back. + func removeRejectedPlugin( + _ plugin: RejectedPlugin, + moveToTrash: (URL) throws -> Void = { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) } + ) throws { + guard canRemoveRejectedPlugin(plugin) else { throw PluginError.cannotUninstallBuiltIn } + if FileManager.default.fileExists(atPath: plugin.url.path) { + do { + try moveToTrash(plugin.url) + } catch CocoaError.fileNoSuchFile {} + } + removeFromRejected(url: plugin.url) + Self.logger.info("Moved rejected plugin '\(plugin.name, privacy: .public)' to the Trash") + } } diff --git a/apple/TablePro/Core/Services/Infrastructure/ClipboardService.swift b/apple/TablePro/Core/Services/Infrastructure/ClipboardService.swift index 111178a6bf..a4840ee40f 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ClipboardService.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ClipboardService.swift @@ -64,6 +64,8 @@ protocol ClipboardProvider { func readGridRows() -> GridRowsClipboardPayload? func readGridCells() -> GridCellsClipboardPayload? func writeText(_ text: String) + // A requirement, so a call on `ClipboardService.shared` reaches a provider's own concealed write. + func writeSecretText(_ text: String) func writeCsv(_ csv: String) func writeImage(_ image: NSImage) func writeRows(tsv: String, html: String?, gridRows: GridRowsClipboardPayload) @@ -75,8 +77,7 @@ protocol ClipboardProvider { } extension ClipboardProvider { - /// Text a clipboard-history app should not retain. Providers that cannot express that - /// fall back to a plain write rather than refusing to copy. + // A provider that cannot mark text concealed still copies it rather than refusing. func writeSecretText(_ text: String) { writeText(text) } diff --git a/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionGate.swift b/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionGate.swift index 9d28a608a4..4fbd27d1f1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionGate.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionGate.swift @@ -19,16 +19,19 @@ internal struct ExternalConnectionGate { self.prompt = prompt ?? ExternalConnectionAlertPrompt() } - /// The trust key names neither a filter nor an SSH server, so trusting a link that carries one - /// would cover whatever SQL or server a later link picks. A tunnelled loopback host is not on - /// this Mac either. + // The key names neither a filter nor a transport, so trusting a link that carries one would cover whatever SQL or + // server a later link picks. A loopback host behind any tunnel or proxy is not on this Mac either. internal func authorize( _ connection: DatabaseConnection, + isSaved: Bool = false, scopeName: String?, filter: ConnectionURLFilter? = nil ) async -> Bool { - let key = ExternalConnectionTrustKey(connection: connection, scopeName: scopeName) - let trustable = key.isLoopbackHost && !connection.sshConfig.enabled && filter == nil + let key = ExternalConnectionTrustKey(connection: connection, scopeName: scopeName, isSaved: isSaved) + let staysOnThisMac = connection.enabledTunnelKinds.isEmpty + && !connection.sshConfig.enabled + && !connection.resolvedSSHConfig.enabled + let trustable = key.isLoopbackHost && staysOnThisMac && filter == nil if trustable, trustStore.isTrusted(key) { return true } switch await prompt.prompt(for: connection, filter: filter, offerAlwaysAllow: trustable) { diff --git a/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionPrompting.swift b/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionPrompting.swift index de4a286fd2..c2d5e01583 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionPrompting.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ExternalConnectionPrompting.swift @@ -104,15 +104,15 @@ internal struct ExternalConnectionAlertPrompt: ExternalConnectionPrompting { details.append(String(format: String(localized: "Database: %@"), connection.database)) } details.append(contentsOf: sshDetails(for: connection)) + details.append(contentsOf: transportDetails(for: connection)) return details } - /// The database host of a tunnelled connection is the far end of the tunnel, usually - /// `localhost`, so listing it alone describes none of the machines the session actually - /// crosses. The alert asks the user to decide whether they trust the link; it has to name the - /// SSH server and every hop for that to mean anything. + // Behind a tunnel the database host is its far end, usually localhost, so the alert names every server the + // session crosses. A linked profile is read as it stands now, which is where the connect goes. private static func sshDetails(for connection: DatabaseConnection) -> [String] { - let ssh = connection.sshConfig + let linked = SSHProfileStorage.shared.refreshingLinkedProfile(connection).resolvedSSHConfig + let ssh = linked.enabled ? linked : connection.sshConfig guard ssh.enabled, !ssh.host.isEmpty else { return [] } let port = ssh.port ?? 22 @@ -130,6 +130,29 @@ internal struct ExternalConnectionAlertPrompt: ExternalConnectionPrompting { return details } + private static func transportDetails(for connection: DatabaseConnection) -> [String] { + connection.enabledTunnelKinds.compactMap { kind -> String? in + let target: String + switch kind { + case .ssh, .remoteFile, .remoteDatabaseSession: + return nil + case .socksProxy: + guard let proxy = connection.resolvedSOCKSProxyConfig else { return nil } + target = "\(proxy.host):\(proxy.port)" + case .tunnelCommand: + guard let command = connection.resolvedTunnelCommandConfig else { return nil } + target = command.method.displayName + case .cloudflare: + guard let tunnel = connection.resolvedCloudflareConfig else { return nil } + target = tunnel.accessHostname + case .cloudSQLProxy: + guard let proxy = connection.resolvedCloudSQLProxyConfig else { return nil } + target = proxy.instanceConnectionName + } + return String(format: String(localized: "%1$@: %2$@"), kind.displayName, target) + } + } + private func present(_ alert: NSAlert) async -> NSApplication.ModalResponse { guard let window = AlertHelper.resolveWindow(NSApp.keyWindow) else { return alert.runModal() diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+Connection.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+Connection.swift index efab53b296..459d789b2d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+Connection.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+Connection.swift @@ -52,7 +52,7 @@ internal extension MainSplitViewController { transition(to: .unavailable(.notConnected)) return } - connect(connection, cancellingPrevious: false) + connect(connection, cancellingPrevious: false, adoptsSSHProfileEdits: false) } // The menu bar's second connection command does what the state offers: Connect, Reconnect or Stop. @@ -97,23 +97,21 @@ internal extension MainSplitViewController { DatabaseManager.shared.cancelRecovery(for: connectionId) } - /// Reconnects the connection named, not whichever one the window happens to be showing. - /// Clicking a disconnected connection used to redial the selected one instead, tearing down - /// the session the user was working in. - internal func reconnectWorkspace(_ connectionId: UUID) { + // The connection named, not the one on screen: redialing the selected one tore down the session in use. A person's + // Connect or Reconnect is the one connect that moves an open session to an edited SSH profile; a link passes false. + internal func reconnectWorkspace(_ connectionId: UUID, adoptsSSHProfileEdits: Bool = true) { guard let workspace = workspaces.workspace(for: connectionId), let connection = workspace.connection else { return } workspaces.select(connectionId) - connect(connection, cancellingPrevious: true) + connect(connection, cancellingPrevious: true, adoptsSSHProfileEdits: adoptsSSHProfileEdits) } - /// Shows the connection and dials only when its phase allows a manual connect. Redialing one - /// that is already connecting cancels that attempt and restarts it, prompts included. - internal func reconnectWorkspaceIfIdle(_ connectionId: UUID) { + // Dials only when the phase allows a manual connect; one already connecting restarts, prompts included. + internal func reconnectWorkspaceIfIdle(_ connectionId: UUID, adoptsSSHProfileEdits: Bool = true) { guard let workspace = workspaces.workspace(for: connectionId) else { return } workspaces.select(connectionId) guard ConnectionWindowPhaseMachine.allowsManualConnect(phase: workspace.phase) else { return } - reconnectWorkspace(connectionId) + reconnectWorkspace(connectionId, adoptsSSHProfileEdits: adoptsSSHProfileEdits) } internal func isShowingInKeyWindow(_ connectionId: UUID) -> Bool { @@ -188,7 +186,7 @@ internal extension MainSplitViewController { ConnectionRecoveryPerformer.perform(action, for: connection) } - private func connect(_ connection: DatabaseConnection, cancellingPrevious: Bool) { + private func connect(_ connection: DatabaseConnection, cancellingPrevious: Bool, adoptsSSHProfileEdits: Bool) { guard let workspace = workspaces.workspace(for: connection.id) else { return } let token = UUID() workspace.attemptToken = token @@ -206,7 +204,7 @@ internal extension MainSplitViewController { await DatabaseManager.shared.cancelEnsureConnected(connection.id) } do { - try await DatabaseManager.shared.ensureConnected(connection) + try await DatabaseManager.shared.ensureConnected(connection, adoptsSSHProfileEdits: adoptsSSHProfileEdits) self?.finishAttempt(token, for: connection.id, outcome: nil) } catch { Self.connectionLogger.error( diff --git a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift index e78576bd25..4c917cc3e1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift @@ -165,7 +165,7 @@ internal final class TabRouter { /// installed for the whole of a connect, so asking the driver restarted one in flight. if let host = existing.contentViewController as? MainSplitViewController { if host.workspaces.contains(id) { - host.reconnectWorkspaceIfIdle(id) + host.reconnectWorkspaceIfIdle(id, adoptsSSHProfileEdits: false) } else { // Dialed by a workspace of its own, so a failure lands inline in its pane, not as an alert. if transientConnection != nil { @@ -176,7 +176,7 @@ internal final class TabRouter { autoConnect: false ) if adopted?.phase != .connected { - host.reconnectWorkspace(id) + host.reconnectWorkspace(id, adoptsSSHProfileEdits: false) } } return @@ -368,7 +368,7 @@ internal final class TabRouter { } guard await externalConnectionGate.authorize( - connection, scopeName: parsed.connectionName, filter: filter + connection, isSaved: !isTransient, scopeName: parsed.connectionName, filter: filter ) else { throw TabRouterError.userCancelled } diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift index 4af160575d..ed071c40e3 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift @@ -332,7 +332,7 @@ internal final class WindowManager { } bringToFront(targetHost.view.window) if DatabaseManager.shared.activeSessions[targetConnectionId]?.reportedStatus.isConnected != true { - targetHost.reconnectWorkspaceIfIdle(targetConnectionId) + targetHost.reconnectWorkspaceIfIdle(targetConnectionId, adoptsSSHProfileEdits: false) } target.queueMove(PendingTabMove(tabId: tabId, source: source) { [weak sourceHost] in sourceHost?.isShowingInKeyWindow(sourceConnectionId) ?? false diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 2048ba13f6..fc116783a5 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -159,9 +159,14 @@ final class AppSettingsManager: ObservableObject { } } + // Every writer, a reset from another pane included, has to reach the Keychain flag and the coordinator. @Published var sync: SyncSettings { didSet { storage.saveSync(sync) + passwordSyncDefaults.set(sync.syncsPasswords, forKey: KeychainHelper.passwordSyncEnabledKey) + if oldValue.enabled != sync.enabled { + switchSync(sync.enabled) + } } } @@ -200,6 +205,8 @@ final class AppSettingsManager: ObservableObject { private let mcpServerManager: MCPServerManager private let copilotService: CopilotService private let connectionListPreferences: ConnectionListPreferences + private let passwordSyncDefaults: UserDefaults + private let switchSync: @MainActor (Bool) -> Void private var isValidating = false init( @@ -211,7 +218,16 @@ final class AppSettingsManager: ObservableObject { queryHistoryManager: QueryHistoryManager = .shared, mcpServerManager: MCPServerManager = .shared, copilotService: CopilotService = .shared, - connectionListPreferences: ConnectionListPreferences = .shared + connectionListPreferences: ConnectionListPreferences = .shared, + passwordSyncDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, + switchSync: @escaping @MainActor (Bool) -> Void = { enabled in + // Read at call time, so building the shared settings never builds the coordinator. + if enabled { + SyncCoordinator.shared.enableSync() + } else { + SyncCoordinator.shared.disableSync() + } + } ) { self.storage = storage self.themeEngine = themeEngine @@ -222,6 +238,8 @@ final class AppSettingsManager: ObservableObject { self.mcpServerManager = mcpServerManager self.copilotService = copilotService self.connectionListPreferences = connectionListPreferences + self.passwordSyncDefaults = passwordSyncDefaults + self.switchSync = switchSync self.general = storage.loadGeneral() self.appearance = storage.loadAppearance() @@ -279,7 +297,7 @@ final class AppSettingsManager: ObservableObject { history = .default tabs = .default keyboard = .default - ai = .default + ai = ai.resetKeepingProviders sync = .default mcp = .default typography = .default diff --git a/apple/TablePro/Core/Storage/AppSettingsStorage.swift b/apple/TablePro/Core/Storage/AppSettingsStorage.swift index a67ae5946c..2b78d39e5b 100644 --- a/apple/TablePro/Core/Storage/AppSettingsStorage.swift +++ b/apple/TablePro/Core/Storage/AppSettingsStorage.swift @@ -311,7 +311,7 @@ final class AppSettingsStorage: Sendable { saveHistory(.default) saveTabs(.default) saveKeyboard(.default) - saveAI(.default) + saveAI(loadAI().resetKeepingProviders) saveSync(.default) saveMCP(.default) saveTypography(.default) diff --git a/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift b/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift index 6c89dfc86a..cc4147e58a 100644 --- a/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift +++ b/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift @@ -30,23 +30,26 @@ internal final class ConnectionApprovalStore { private let kind: Kind private let defaults: UserDefaults private let savedConnections: @MainActor () -> [DatabaseConnection]? + private let dialedDestination: @MainActor (DatabaseConnection) -> ConnectionDestination internal init( kind: Kind, defaults: UserDefaults = AppStorageEnvironment.shared.defaults, savedConnections: @escaping @MainActor () -> [DatabaseConnection]? = ConnectionApprovalStore - .trustedSavedConnections + .trustedSavedConnections, + dialedDestination: @escaping @MainActor (DatabaseConnection) -> ConnectionDestination = { $0.dialedDestination } ) { self.kind = kind self.defaults = defaults self.savedConnections = savedConnections + self.dialedDestination = dialedDestination } internal func isApproved(_ connection: DatabaseConnection) -> Bool { let items = kind.items(in: connection) guard !items.isEmpty else { return true } migrateIfNeeded() - let approved = approvals()[connection.id.uuidString]?[connection.destination.digest] ?? [] + let approved = approvals()[connection.id.uuidString]?[dialedDestination(connection).digest] ?? [] return items.isSubset(of: approved) } @@ -100,7 +103,7 @@ internal final class ConnectionApprovalStore { private func record(_ connection: DatabaseConnection, in all: inout Approvals) -> Bool { let items = kind.items(in: connection) guard !items.isEmpty else { return false } - let digest = connection.destination.digest + let digest = dialedDestination(connection).digest let approved = Set(all[connection.id.uuidString]?[digest] ?? []).union(items) all[connection.id.uuidString, default: [:]][digest] = approved.sorted() return true diff --git a/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift b/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift index 857199fdb0..51969fa7b5 100644 --- a/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift +++ b/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift @@ -56,12 +56,18 @@ final class IntegrityStampedFileStore { self.integrity = integrity } - /// Nil when the file exists and could not be decoded. An absent file is an empty list, which is - /// a fresh install rather than a failure. + // Only an absent file is an empty list, a fresh install; one that cannot be read or decoded is nil, never saved over. func load() -> [Element]? { - guard let data = try? Data(contentsOf: fileURL) else { + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { isTrusted = true return [] + } catch { + logger.error("Failed to read \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)") + isTrusted = false + return nil } switch integrity.verify(data, fileURL: fileURL) { diff --git a/apple/TablePro/Core/Utilities/Connection/ExternalConnectionTrustKey.swift b/apple/TablePro/Core/Utilities/Connection/ExternalConnectionTrustKey.swift index 415bc37b6f..464b9decf3 100644 --- a/apple/TablePro/Core/Utilities/Connection/ExternalConnectionTrustKey.swift +++ b/apple/TablePro/Core/Utilities/Connection/ExternalConnectionTrustKey.swift @@ -14,6 +14,8 @@ internal struct ExternalConnectionTrustKey: Hashable, Codable, Sendable { internal let scopeName: String // Optional so entries saved before sockets still decode. Trust covers this exact path only. internal let socketPath: String? + // The saved connection a link opened, nil for one built from the link alone, so trust never crosses between them. + internal let savedConnectionId: UUID? internal init( databaseType: String, @@ -21,10 +23,12 @@ internal struct ExternalConnectionTrustKey: Hashable, Codable, Sendable { database: String, username: String, scopeName: String, - socketPath: String? = nil + socketPath: String? = nil, + savedConnectionId: UUID? = nil ) { let socket = socketPath?.trimmingCharacters(in: .whitespaces) self.socketPath = socket?.isEmpty == false ? socket : nil + self.savedConnectionId = savedConnectionId self.databaseType = databaseType.lowercased() self.host = self.socketPath == nil ? host.trimmingCharacters(in: .whitespaces).lowercased() : "localhost" self.database = database @@ -32,14 +36,15 @@ internal struct ExternalConnectionTrustKey: Hashable, Codable, Sendable { self.scopeName = scopeName.trimmingCharacters(in: .whitespaces) } - internal init(connection: DatabaseConnection, scopeName: String?) { + internal init(connection: DatabaseConnection, scopeName: String?, isSaved: Bool = false) { self.init( databaseType: connection.type.rawValue, host: connection.host, database: connection.database, username: connection.username, scopeName: scopeName ?? "", - socketPath: connection.localSocketFile + socketPath: connection.localSocketFile, + savedConnectionId: isSaved ? connection.id : nil ) } diff --git a/apple/TablePro/Models/AI/AIModels.swift b/apple/TablePro/Models/AI/AIModels.swift index 778b3a5af8..f0ed6eb795 100644 --- a/apple/TablePro/Models/AI/AIModels.swift +++ b/apple/TablePro/Models/AI/AIModels.swift @@ -326,6 +326,16 @@ struct AISettings: Codable, Equatable, Sendable { composerHighlightEnabled: true ) + // A reset keeps the providers, whose keys can be iCloud Keychain items other Macs still use, and the switch that + // keeps them from being used. + var resetKeepingProviders: AISettings { + var reset = AISettings.default + reset.enabled = enabled + reset.providers = providers + reset.activeProviderID = activeProviderID + return reset + } + init( enabled: Bool = true, providers: [AIProviderConfig] = [], diff --git a/apple/TablePro/Models/Connection/DatabaseConnection+Destination.swift b/apple/TablePro/Models/Connection/DatabaseConnection+Destination.swift index e4bcfd6b39..c03966c6e6 100644 --- a/apple/TablePro/Models/Connection/DatabaseConnection+Destination.swift +++ b/apple/TablePro/Models/Connection/DatabaseConnection+Destination.swift @@ -21,6 +21,21 @@ extension DatabaseConnection { ) } + // Read through the linked SSH profile as it stands now, which is where the next connect dials. + @MainActor var dialedDestination: ConnectionDestination { + SSHProfileStorage.shared.refreshingLinkedProfile(self).destination + } + + // The SSH server and jump hosts this copy names, in order. A profile counts by its servers, never its id. + var destinationTunnel: ConnectionDestination.Tunnel { + let config = resolvedSSHConfig + guard config.enabled else { return .none } + return .ssh( + server: ConnectionDestination.Endpoint(host: config.host, port: config.port), + jumps: config.jumpHosts.map { ConnectionDestination.Endpoint(host: $0.host, port: $0.port) } + ) + } + // Host and port first, then every other server or project the connection may sign in to, so a prompt never // hides the real host behind a value the engine ignores, or a server behind "(+N more)". Where plugin fields name // the server, as DuckDB's Remote fields do, they stand in for Host, which nothing dials. @@ -87,19 +102,4 @@ extension DatabaseConnection { case .verifyIdentity: return .verifyIdentity } } - - private var destinationTunnel: ConnectionDestination.Tunnel { - switch sshTunnelMode { - case .disabled: - return .none - case .profile(let profileId, _): - return .profile(profileId) - case .inline(let config): - guard config.enabled else { return .none } - return .ssh( - server: ConnectionDestination.Endpoint(host: config.host, port: config.port), - jumps: config.jumpHosts.map { ConnectionDestination.Endpoint(host: $0.host, port: $0.port) } - ) - } - } } diff --git a/apple/TablePro/Models/Settings/SyncSettings.swift b/apple/TablePro/Models/Settings/SyncSettings.swift index bf8f97395b..55954bf595 100644 --- a/apple/TablePro/Models/Settings/SyncSettings.swift +++ b/apple/TablePro/Models/Settings/SyncSettings.swift @@ -77,6 +77,11 @@ struct SyncSettings: Codable, Equatable { syncSQLFavorites: true, syncTableFolders: true ) + + // Whether a secret saved now goes to iCloud Keychain. + var syncsPasswords: Bool { + enabled && syncConnections && syncPasswords + } } internal extension SyncSettings { diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 59ea7fab79..4f3636d045 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -62327,6 +62327,9 @@ } } } + }, + "Delete “/%@”?" : { + }, "Delete \"%@\"" : { "localizations" : { @@ -74900,6 +74903,9 @@ } } } + }, + "Every custom shortcut goes back to its default." : { + }, "Every database you picked is written into this folder." : { "localizations" : { @@ -112016,6 +112022,9 @@ }, "Move “%@” to Connection" : { + }, + "Move “%@” to the Trash?" : { + }, "Move Column Down" : { "localizations" : { @@ -150225,6 +150234,9 @@ } } } + }, + "Reset All Shortcuts?" : { + }, "Reset column widths, order, and visibility to defaults" : { "localizations" : { @@ -158092,6 +158104,9 @@ } } } + }, + "Saved connection “%@”" : { + }, "Saved Connections" : { "localizations" : { @@ -187122,6 +187137,9 @@ } } } + }, + "The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone." : { + }, "The command must contain %@, where the local port goes" : { "localizations" : { @@ -191186,6 +191204,9 @@ } } } + }, + "The plugin can't be loaded. You can put it back from the Trash." : { + }, "The plugin depends on a component that's missing or incompatible with this Mac." : { "localizations" : { @@ -194181,6 +194202,9 @@ "The SSH port %lld is not between 1 and 65535." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "The SSH profile this connection uses now points to another server. Click Reconnect in its window to use it." : { + }, "The SSH server closed the connection during the handshake." : { @@ -203233,6 +203257,9 @@ } } } + }, + "This will reset all settings across every section to their default values. AI providers, their API keys and Enable AI Features are kept." : { + }, "This workbook has no worksheets." : { "localizations" : { diff --git a/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift b/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift index 27c11ca7ba..3250049fca 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift @@ -7,6 +7,7 @@ // import AppKit +import TableProImport extension WelcomeViewModel { func publishConnectionsToTeamLibrary(_ connectionsToPublish: [DatabaseConnection], teamID: String) { @@ -38,8 +39,12 @@ extension WelcomeViewModel { confirm: @MainActor ([DatabaseConnection]) async -> Bool ) async -> TeamLibraryPublishOutcome { guard await confirm(connections) else { return .declined } + // A pull drops both, so sending them would only put a token typed into a command on the server. let plan = connections.map { - TeamLibraryPublishPlan.Connection(id: $0.id, settings: exporter.portableSettings(for: $0)) + TeamLibraryPublishPlan.Connection( + id: $0.id, + settings: exporter.portableSettings(for: $0).withoutStartupCommands().withoutTunnelCommand() + ) } do throws(TeamLibraryPublishError) { return .finished(try await sync.publishConnections(plan, to: teamID)) diff --git a/apple/TablePro/Views/Components/DiagramExporter.swift b/apple/TablePro/Views/Components/DiagramExporter.swift index c7d201013a..becaafb5f7 100644 --- a/apple/TablePro/Views/Components/DiagramExporter.swift +++ b/apple/TablePro/Views/Components/DiagramExporter.swift @@ -21,6 +21,10 @@ enum DiagramExporter { } static func pngData(_ image: NSImage?) -> Data? { + // A bitmap the image already holds encodes as it is, without a TIFF copy and a second decode. + if let rep = image?.representations.first(where: { $0 is NSBitmapImageRep }) as? NSBitmapImageRep { + return rep.representation(using: .png, properties: [:]) + } guard let tiffData = image?.tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiffData) else { return nil } diff --git a/apple/TablePro/Views/ERDiagram/ERDiagramScene.swift b/apple/TablePro/Views/ERDiagram/ERDiagramScene.swift index 167e1ac273..d14699c102 100644 --- a/apple/TablePro/Views/ERDiagram/ERDiagramScene.swift +++ b/apple/TablePro/Views/ERDiagram/ERDiagramScene.swift @@ -114,10 +114,33 @@ enum ERDiagramSceneRenderer { } } + // A copy or a PNG renders on the main actor, so a bigger bitmap costs seconds and gigabytes; PDF and SVG keep full size. + static let maxBitmapSide: CGFloat = 16_384 + static let maxBitmapPixels: CGFloat = 33_554_432 + + static func bitmapScale(for size: CGSize, requested scale: CGFloat) -> CGFloat { + guard size.width > 0, size.height > 0 else { return scale } + let bySide = maxBitmapSide / max(size.width, size.height) + let byArea = (maxBitmapPixels / (size.width * size.height)).squareRoot() + return min(scale, bySide, byArea) + } + static func image(_ scene: ERDiagramScene, appearance: NSAppearance, scale: CGFloat) -> NSImage? { + guard let rep = bitmap(scene, appearance: appearance, scale: scale) else { return nil } + let image = NSImage(size: rep.size) + image.addRepresentation(rep) + return image + } + + static func pngData(_ scene: ERDiagramScene, appearance: NSAppearance, scale: CGFloat) -> Data? { + bitmap(scene, appearance: appearance, scale: scale)?.representation(using: .png, properties: [:]) + } + + private static func bitmap(_ scene: ERDiagramScene, appearance: NSAppearance, scale requested: CGFloat) -> NSBitmapImageRep? { let frame = exportFrame(of: scene) - let pixelsWide = Int((frame.size.width * scale).rounded()) - let pixelsHigh = Int((frame.size.height * scale).rounded()) + let scale = bitmapScale(for: frame.size, requested: requested) + let pixelsWide = Int((frame.size.width * scale).rounded(.down)) + let pixelsHigh = Int((frame.size.height * scale).rounded(.down)) guard pixelsWide > 0, pixelsHigh > 0 else { return nil } guard let rep = NSBitmapImageRep( @@ -136,10 +159,7 @@ enum ERDiagramSceneRenderer { guard let base = NSGraphicsContext(bitmapImageRep: rep) else { return nil } renderExport(scene, frame: frame, appearance: appearance, into: base.cgContext) - - let image = NSImage(size: frame.size) - image.addRepresentation(rep) - return image + return rep } static func pdfData(_ scene: ERDiagramScene, appearance: NSAppearance, title: String) -> Data? { diff --git a/apple/TablePro/Views/ERDiagram/ERDiagramView.swift b/apple/TablePro/Views/ERDiagram/ERDiagramView.swift index ef7abaf74e..25a57bbc2b 100644 --- a/apple/TablePro/Views/ERDiagram/ERDiagramView.swift +++ b/apple/TablePro/Views/ERDiagram/ERDiagramView.swift @@ -210,7 +210,11 @@ struct ERDiagramView: View { private func exportData(_ format: ERDiagramExportFormat) -> Data? { switch format { case .png: - return DiagramExporter.pngData(exportImage()) + return ERDiagramSceneRenderer.pngData( + scene, + appearance: viewport.effectiveAppearance, + scale: DiagramExporter.renderScale + ) case .svg: let svg = ERDiagramSceneRenderer.svgDocument(scene, appearance: viewport.effectiveAppearance, title: exportTitle) return Data(svg.utf8) diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 0b707876c7..505177e9e7 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -48,8 +48,9 @@ struct AISettingsView: View { saveProvider(saved, apiKey: apiKey, isNew: false) editingProviderID = nil }, + // The sheet already asked; the parent alert is for the context menu only. onDelete: { - pendingDeleteID = provider.id + removeProvider(provider.id) editingProviderID = nil }, onCancel: { diff --git a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift index 4c9b2a599c..07487a6fac 100644 --- a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift +++ b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift @@ -10,6 +10,7 @@ struct CustomSlashCommandsSection: View { @State private var editing: CustomSlashCommand? @State private var isCreating = false @State private var saveError: String? + @State private var pendingDelete: CustomSlashCommand? var body: some View { Section { @@ -74,6 +75,22 @@ struct CustomSlashCommandsSection: View { } message: { message in Text(message) } + .alert( + pendingDelete.map { String(format: String(localized: "Delete “/%@”?"), $0.name) } ?? "", + isPresented: Binding( + get: { pendingDelete != nil }, + set: { if !$0 { pendingDelete = nil } } + ), + presenting: pendingDelete + ) { command in + Button(String(localized: "Delete"), role: .destructive) { + storage.delete(id: command.id) + pendingDelete = nil + } + Button(String(localized: "Cancel"), role: .cancel) { pendingDelete = nil } + } message: { _ in + Text(String(localized: "The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.")) + } } @ViewBuilder @@ -103,7 +120,7 @@ struct CustomSlashCommandsSection: View { } .controlSize(.small) Button(role: .destructive) { - storage.delete(id: command.id) + pendingDelete = command } label: { Image(systemName: "trash") } diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index d66319fbf1..dd574ad3db 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -149,7 +149,7 @@ struct GeneralSettingsView: View { Button(String(localized: "Reset"), role: .destructive) { onResetAll() } Button(String(localized: "Cancel"), role: .cancel) {} } message: { - Text("This will reset all settings across every section to their default values.") + Text("This will reset all settings across every section to their default values. AI providers, their API keys and Enable AI Features are kept.") } .onAppear { if initialLanguage == nil { initialLanguage = settings.language } diff --git a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift index 670755875e..499c040a9d 100644 --- a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift +++ b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift @@ -18,6 +18,7 @@ struct KeyboardSettingsView: View { @State private var systemReservedAlert: ShortcutAction? @State private var reservedAlert: ReservedAlertState? @State private var needsModifierAlert: ShortcutAction? + @State private var confirmsReset = false private var content: some View { VStack(spacing: 0) { @@ -45,7 +46,7 @@ struct KeyboardSettingsView: View { HStack { Spacer() Button(String(localized: "Reset to Defaults")) { - settings = .default + confirmsReset = true } .disabled(settings.shortcuts.isEmpty) } @@ -57,6 +58,14 @@ struct KeyboardSettingsView: View { var body: some View { content + .alert(String(localized: "Reset All Shortcuts?"), isPresented: $confirmsReset) { + Button(String(localized: "Reset"), role: .destructive) { + settings = .default + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text(String(localized: "Every custom shortcut goes back to its default.")) + } .alert( String(localized: "Shortcut Conflict"), isPresented: Binding( diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index 4197393625..a2e78f03f2 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -148,10 +148,12 @@ struct InstalledPluginsView: View { HStack(spacing: 8) { rejectedActionControl(for: plugin, action: action) - Button(String(localized: "Remove")) { - removeRejectedPlugin(plugin) + if pluginManager.canRemoveRejectedPlugin(plugin) { + Button(String(localized: "Remove")) { + removeRejectedPlugin(plugin) + } + .accessibilityLabel(String(format: String(localized: "Remove %@"), plugin.name)) } - .accessibilityLabel(String(format: String(localized: "Remove %@"), plugin.name)) } } .padding(20) @@ -199,20 +201,24 @@ struct InstalledPluginsView: View { } private func removeRejectedPlugin(_ plugin: RejectedPlugin) { - let fm = FileManager.default - if fm.fileExists(atPath: plugin.url.path) { + Task { + let confirmed = await AlertHelper.confirmDestructive( + title: String(format: String(localized: "Move “%@” to the Trash?"), plugin.name), + message: String(localized: "The plugin can't be loaded. You can put it back from the Trash."), + confirmButton: String(localized: "Move to Trash"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } do { - try fm.removeItem(at: plugin.url) - } catch CocoaError.fileNoSuchFile { + try pluginManager.removeRejectedPlugin(plugin) } catch { errorAlertTitle = String(localized: "Remove Failed") errorAlertMessage = error.localizedDescription showErrorAlert = true return } + if selection == .rejected(plugin.url) { selection = nil } } - pluginManager.removeFromRejected(url: plugin.url) - if selection == .rejected(plugin.url) { selection = nil } } // MARK: - Plugin List diff --git a/apple/TablePro/Views/Settings/Sections/SyncSection.swift b/apple/TablePro/Views/Settings/Sections/SyncSection.swift index 5d665fa927..ba96e48ba2 100644 --- a/apple/TablePro/Views/Settings/Sections/SyncSection.swift +++ b/apple/TablePro/Views/Settings/Sections/SyncSection.swift @@ -18,14 +18,6 @@ struct SyncSection: View { var body: some View { Section { Toggle("Sync this Mac with iCloud", isOn: $settingsManager.sync.enabled) - .onChange(of: settingsManager.sync.enabled) { newValue in - updatePasswordSyncFlag() - if newValue { - syncCoordinator.enableSync() - } else { - syncCoordinator.disableSync() - } - } .help("Syncs connections, table favorites, settings, and SSH profiles across your Macs via iCloud.") .disabled(!isProAvailable) @@ -92,15 +84,11 @@ struct SyncSection: View { .onChange(of: settingsManager.sync.syncConnections) { newValue in if !newValue, settingsManager.sync.syncPasswords { settingsManager.sync.syncPasswords = false - onPasswordSyncChanged(false) } } if settingsManager.sync.syncConnections { Toggle("Passwords", isOn: $settingsManager.sync.syncPasswords) - .onChange(of: settingsManager.sync.syncPasswords) { newValue in - onPasswordSyncChanged(newValue) - } .help("Syncs passwords via iCloud Keychain (end-to-end encrypted).") .padding(.leading, 20) @@ -121,17 +109,4 @@ struct SyncSection: View { Toggle("Saved Queries", isOn: $settingsManager.sync.syncSQLFavorites) } } - - // MARK: - Helpers - - private func onPasswordSyncChanged(_ enabled: Bool) { - let effective = settingsManager.sync.enabled && settingsManager.sync.syncConnections && enabled - AppStorageEnvironment.shared.defaults.set(effective, forKey: KeychainHelper.passwordSyncEnabledKey) - } - - private func updatePasswordSyncFlag() { - let sync = settingsManager.sync - let effective = sync.enabled && sync.syncConnections && sync.syncPasswords - AppStorageEnvironment.shared.defaults.set(effective, forKey: KeychainHelper.passwordSyncEnabledKey) - } } diff --git a/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift b/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift index 6a7d0de63b..e0a1dc3802 100644 --- a/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift +++ b/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift @@ -21,11 +21,16 @@ struct TrustedExternalConnectionsSection: View { .foregroundStyle(.secondary) } else { ForEach(entries) { entry in - LabeledContent(entry.key.displayDescription) { + LabeledContent { Button("Forget") { store.revoke(entry.key) refresh() } + } label: { + Text(entry.key.displayDescription) + if let name = savedConnectionName(of: entry) { + Text(String(format: String(localized: "Saved connection “%@”"), name)) + } } } @@ -42,6 +47,11 @@ struct TrustedExternalConnectionsSection: View { .onAppear(perform: refresh) } + // Two saved connections can share type, host, database and user, so the name tells their entries apart. + private func savedConnectionName(of entry: TrustedExternalConnection) -> String? { + entry.key.savedConnectionId.flatMap { ConnectionStorage.shared.loadConnection(id: $0)?.name } + } + private func refresh() { entries = store.entries().sorted { $0.trustedAt > $1.trustedAt } } diff --git a/apple/TablePro/Views/Settings/SyncSettingsView.swift b/apple/TablePro/Views/Settings/SyncSettingsView.swift index 6e4dceb9f4..c71657a438 100644 --- a/apple/TablePro/Views/Settings/SyncSettingsView.swift +++ b/apple/TablePro/Views/Settings/SyncSettingsView.swift @@ -89,7 +89,7 @@ private struct SyncNoticeSection: View { Task { await SyncCoordinator.shared.uploadAgain() } } case .turnOffSync: - // Through the setting, so the switch's own change handler also settles password sync. + // Through the setting, which also turns password sync off and stops the coordinator. Button(action.title) { AppSettingsManager.shared.sync.enabled = false } diff --git a/apple/TableProTests/Core/Database/DatabaseManagerTunnelTests.swift b/apple/TableProTests/Core/Database/DatabaseManagerTunnelTests.swift index 84bed140b7..5430093058 100644 --- a/apple/TableProTests/Core/Database/DatabaseManagerTunnelTests.swift +++ b/apple/TableProTests/Core/Database/DatabaseManagerTunnelTests.swift @@ -643,3 +643,42 @@ struct DatabaseManagerTunnelTests { #expect(phase == .unavailable(.disconnected(info))) } } + +extension GlobalStateSuites { + // Writes the shared SSH profile store across suspensions. + @MainActor + struct PinnedSSHRouteTests { + @Test("A pinned route is refused once the linked profile moves, and followed while it stays") + func pinnedRouteRefusesAMovedProfile() async throws { + let profiles = SSHProfileStorage.shared + let saved = profiles.loadProfiles() + let profile = SSHProfile(name: "Jump", host: "bastion-b.example", port: 22, username: "ops", authMethod: .password) + #expect(profiles.saveProfilesWithoutSync(saved + [profile])) + defer { profiles.saveProfilesWithoutSync(saved) } + var dialed = profile.toSSHConfiguration() + dialed.host = "bastion-a.example" + var connection = DatabaseConnection( + name: "file", + type: .duckdb, + additionalFields: ["duckdbMode": "local", "duckdbFilePath": "/tmp/tablepro-tests.duckdb"] + ) + connection.sshTunnelMode = .profile(id: profile.id, snapshot: dialed) + + await #expect(throws: ConnectionTunnelError.sshProfileMoved) { + try await DatabaseManager.shared.buildEffectiveConnection( + for: connection, + pinnedSSHRoute: connection.destinationTunnel, + deadline: ConnectionDeadline(configuredSeconds: 5) + ) + } + + let current = profiles.refreshingLinkedProfile(connection) + let effective = try await DatabaseManager.shared.buildEffectiveConnection( + for: connection, + pinnedSSHRoute: current.destinationTunnel, + deadline: ConnectionDeadline(configuredSeconds: 5) + ) + #expect(effective.additionalFields["duckdbFilePath"] == "/tmp/tablepro-tests.duckdb") + } + } +} diff --git a/apple/TableProTests/Core/Database/PromptedPasswordKeyTests.swift b/apple/TableProTests/Core/Database/PromptedPasswordKeyTests.swift index ad875df4ba..179591d704 100644 --- a/apple/TableProTests/Core/Database/PromptedPasswordKeyTests.swift +++ b/apple/TableProTests/Core/Database/PromptedPasswordKeyTests.swift @@ -30,6 +30,25 @@ struct PromptedPasswordKeyTests { #expect(DatabaseManager.promptCacheKey(for: linked) != DatabaseManager.promptCacheKey(for: moved)) } + @Test("A connection on an SSH profile asks again once the profile moves to another server") + func movedProfileDoesNotReuseTheAnswer() { + let profiles = SSHProfileStorage.shared + let saved = profiles.loadProfiles() + var profile = SSHProfile(name: "Jump", host: "bastion-a.example", port: 22, username: "ops", authMethod: .password) + #expect(profiles.saveProfilesWithoutSync(saved + [profile])) + defer { profiles.saveProfilesWithoutSync(saved) } + var linked = DatabaseConnection(name: "Orders", host: "127.0.0.1", port: 5_432, type: .postgresql) + linked.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + let before = DatabaseManager.promptCacheKey(for: linked) + + profile.host = "bastion-b.example" + #expect(profiles.saveProfilesWithoutSync(saved + [profile])) + + #expect(DatabaseManager.promptCacheKey(for: linked) != before) + #expect(LocalCredentialConsent.question(for: linked).destination.contains("bastion-b.example")) + #expect(EnvVarReferenceConsent.question(for: linked).destination.contains("bastion-b.example")) + } + @Test("The prompt names the host the engine dials first, before a field it ignores") func summaryLeadsWithTheHost() { let connection = DatabaseConnection( diff --git a/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift b/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift index 3ce71ed1b5..8600b2c143 100644 --- a/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift +++ b/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift @@ -10,7 +10,7 @@ import Testing @MainActor struct SessionRecoveryLoopTests { @MainActor - private struct Fixture { + fileprivate struct Fixture { let manager: DatabaseManager let clock: ManualClock let connection: DatabaseConnection @@ -30,7 +30,7 @@ struct SessionRecoveryLoopTests { serverMessage: "self-signed certificate in certificate chain" ) - private func makeFixture( + fileprivate func makeFixture( storage: ConnectionStorage = .shared, configure: (inout DatabaseConnection) -> Void = { _ in } ) -> Fixture { @@ -49,7 +49,7 @@ struct SessionRecoveryLoopTests { return Fixture(manager: manager, clock: clock, connection: connection, driver: driver) } - private func cleanUp(_ fixture: Fixture) async { + fileprivate func cleanUp(_ fixture: Fixture) async { fixture.manager.endRecoveryLoop(for: fixture.id) await fixture.manager.stopHealthMonitor(for: fixture.id) fixture.manager.removeSession(for: fixture.id) @@ -73,11 +73,11 @@ struct SessionRecoveryLoopTests { await cleanUp(fixture) } - private func loopTask(_ fixture: Fixture) throws -> Task { + fileprivate func loopTask(_ fixture: Fixture) throws -> Task { try #require(fixture.manager.recoveryLoops[fixture.id]?.task) } - private func runNextAttempt(_ fixture: Fixture) async { + fileprivate func runNextAttempt(_ fixture: Fixture) async { await fixture.clock.waitUntilSleeping() fixture.clock.advance(by: .seconds(DatabaseManager.maxRecoveryDelay)) } @@ -922,3 +922,85 @@ struct SessionRecoveryLoopTests { #expect(manager.recoveryLoops.isEmpty) } } + +extension GlobalStateSuites { + // Writes the shared SSH profile store across suspensions. + @MainActor + struct SessionRecoveryMovedProfileTests { + private let loop = SessionRecoveryLoopTests() + + private func movedProfileFixture() -> (SessionRecoveryLoopTests.Fixture, restore: () -> Void) { + let profiles = SSHProfileStorage.shared + let saved = profiles.loadProfiles() + let moved = SSHProfile(name: "Jump", host: "bastion-b.example", port: 22, username: "ops", authMethod: .password) + profiles.saveProfilesWithoutSync(saved + [moved]) + var dialed = moved.toSSHConfiguration() + dialed.host = "bastion-a.example" + let fixture = loop.makeFixture { connection in + connection.sshTunnelMode = .profile(id: moved.id, snapshot: dialed) + connection.sshConfig = dialed + } + return (fixture, { profiles.saveProfilesWithoutSync(saved) }) + } + + @Test("A recovery after the linked SSH profile moved to another server stops and dials nothing") + func movedProfileEndsTheLoop() async throws { + let (fixture, restore) = movedProfileFixture() + defer { restore() } + let expected = ConnectionFailureClassifier.info(for: ConnectionTunnelError.sshProfileMoved) + + fixture.manager.beginRecovery(for: fixture.id, cause: .stoppedResponding) + let task = try loop.loopTask(fixture) + await loop.runNextAttempt(fixture) + await task.value + + #expect(fixture.session?.liveness == .unreachable(expected)) + #expect(fixture.session?.driver === fixture.driver) + #expect(fixture.manager.recoveryLoops[fixture.id] == nil) + #expect(FakeMSSQLPlugin.configurations(for: fixture.id).isEmpty) + await loop.cleanUp(fixture) + } + + @Test("A connect no window asked for keeps a dialed session off the moved profile", arguments: [ + ConnectTrigger.request, .background, + ]) + func unattendedConnectKeepsTheDialedRoute(trigger: ConnectTrigger) async throws { + let (fixture, restore) = movedProfileFixture() + defer { restore() } + var dialed = try #require(fixture.session) + dialed.effectiveConnection = fixture.connection + fixture.manager.injectSession(dialed, for: fixture.id) + fixture.manager.markSessionUnreachable(fixture.id, startedWith: fixture.driver, info: nil) + let expected = ConnectionFailureClassifier.info(for: ConnectionTunnelError.sshProfileMoved) + + for _ in 1...2 { + await #expect(throws: ConnectionTunnelError.sshProfileMoved) { + try await fixture.manager.ensureConnected(fixture.connection, trigger: trigger) + } + } + + #expect(fixture.session?.liveness == .unreachable(expected)) + #expect(fixture.session?.driver === fixture.driver) + #expect(FakeMSSQLPlugin.configurations(for: fixture.id).isEmpty) + await loop.cleanUp(fixture) + } + + @Test("A connect that failed and took the session with it still keeps the route until a disconnect") + func failedConnectKeepsTheDialedRoute() async throws { + let (fixture, restore) = movedProfileFixture() + defer { restore() } + fixture.manager.dialedConnections[fixture.id] = fixture.connection + fixture.manager.removeSession(for: fixture.id) + + await #expect(throws: ConnectionTunnelError.sshProfileMoved) { + try await fixture.manager.ensureConnected(fixture.connection) + } + #expect(fixture.session == nil) + #expect(FakeMSSQLPlugin.configurations(for: fixture.id).isEmpty) + + await fixture.manager.disconnectSession(fixture.id) + #expect(fixture.manager.dialedConnections[fixture.id] == nil) + await loop.cleanUp(fixture) + } + } +} diff --git a/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift b/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift new file mode 100644 index 0000000000..8d9ecce183 --- /dev/null +++ b/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift @@ -0,0 +1,87 @@ +import Foundation +@testable import TablePro +import Testing + +@MainActor +private final class TrashRecorder { + var trashed: [URL] = [] +} + +@MainActor +struct RejectedPluginRemovalTests { + private let root = FileManager.default.temporaryDirectory + .appendingPathComponent("RejectedPluginRemovalTests-\(UUID().uuidString)", isDirectory: true) + + private func makeBundle(in directory: URL) throws -> RejectedPlugin { + let url = directory.appendingPathComponent("Broken.tableplugin", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return RejectedPlugin( + url: url, + bundleId: "com.example.broken", + registryId: nil, + name: "Broken", + reason: "Could not be loaded", + isOutdated: false, + providedDatabaseTypeIds: [] + ) + } + + @Test("A rejected plugin in the user's folder moves to the Trash and leaves the list") + func userPluginMovesToTheTrash() throws { + defer { try? FileManager.default.removeItem(at: root) } + let userPlugins = root.appendingPathComponent("Plugins", isDirectory: true) + let plugin = try makeBundle(in: userPlugins) + let manager = PluginManager(builtInPluginsURL: nil, userPluginsDir: userPlugins) + manager.rejectedPlugins = [plugin] + let recorder = TrashRecorder() + + #expect(manager.canRemoveRejectedPlugin(plugin)) + try manager.removeRejectedPlugin(plugin) { recorder.trashed.append($0) } + + #expect(recorder.trashed == [plugin.url]) + #expect(manager.rejectedPlugins.isEmpty) + } + + @Test("A rejected plugin outside the user's folder, such as one inside the app, is refused and kept") + func bundledPluginIsRefused() throws { + defer { try? FileManager.default.removeItem(at: root) } + let userPlugins = root.appendingPathComponent("Plugins", isDirectory: true) + try FileManager.default.createDirectory(at: userPlugins, withIntermediateDirectories: true) + let plugin = try makeBundle(in: root.appendingPathComponent("TablePro.app/Contents/PlugIns", isDirectory: true)) + let manager = PluginManager(builtInPluginsURL: nil, userPluginsDir: userPlugins) + manager.rejectedPlugins = [plugin] + let recorder = TrashRecorder() + + #expect(!manager.canRemoveRejectedPlugin(plugin)) + let error = #expect(throws: PluginError.self) { + try manager.removeRejectedPlugin(plugin) { recorder.trashed.append($0) } + } + guard case .cannotUninstallBuiltIn = error else { + Issue.record("expected cannotUninstallBuiltIn, got \(String(describing: error))") + return + } + + #expect(recorder.trashed.isEmpty) + #expect(FileManager.default.fileExists(atPath: plugin.url.path)) + #expect(manager.rejectedPlugins.map(\.url) == [plugin.url]) + } + + @Test("A path that climbs out of the user's folder is refused") + func climbingPathIsRefused() throws { + defer { try? FileManager.default.removeItem(at: root) } + let userPlugins = root.appendingPathComponent("Plugins", isDirectory: true) + try FileManager.default.createDirectory(at: userPlugins, withIntermediateDirectories: true) + let manager = PluginManager(builtInPluginsURL: nil, userPluginsDir: userPlugins) + let escaping = RejectedPlugin( + url: userPlugins.appendingPathComponent("../Other.tableplugin"), + bundleId: nil, + registryId: nil, + name: "Other", + reason: "", + isOutdated: false, + providedDatabaseTypeIds: [] + ) + + #expect(!manager.canRemoveRejectedPlugin(escaping)) + } +} diff --git a/apple/TableProTests/Core/Services/ClipboardServiceTests.swift b/apple/TableProTests/Core/Services/ClipboardServiceTests.swift index a0877b345b..2a2beb2255 100644 --- a/apple/TableProTests/Core/Services/ClipboardServiceTests.swift +++ b/apple/TableProTests/Core/Services/ClipboardServiceTests.swift @@ -101,3 +101,19 @@ struct ClipboardServiceTests { #expect(provider.readGridCells() == nil) } } + +extension GlobalStateSuites { + @Suite(.recordingClipboard) + @MainActor + struct ClipboardSecretWriteTests { + @Test("A secret copy through the shared service reaches the provider's concealed write") + func secretWriteReachesTheProvider() throws { + let clipboard = try #require(RecordingClipboard.current) + + ClipboardService.shared.writeSecretText("postgresql://app:hunter2@db.example.com/app") + + #expect(clipboard.secretWrites == ["postgresql://app:hunter2@db.example.com/app"]) + #expect(clipboard.text == "postgresql://app:hunter2@db.example.com/app") + } + } +} diff --git a/apple/TableProTests/Core/Services/Infrastructure/ExternalConnectionGateTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ExternalConnectionGateTests.swift index 3dbc86c75b..8d02d9fbad 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ExternalConnectionGateTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ExternalConnectionGateTests.swift @@ -1,3 +1,4 @@ +import AppKit import Foundation @testable import TablePro import TableProSSHConfig @@ -268,4 +269,71 @@ struct ExternalConnectionGateTests { #expect(prompt.callCount == 1) #expect(prompt.offeredAlwaysAllow == false) } + + // Each connection with the server or method the alert has to name for it. + private func routedConnections() -> [(connection: DatabaseConnection, named: String)] { + var socks = ddevConnection() + socks.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com")) + var command = ddevConnection() + command.tunnelCommandMode = .inline(TunnelCommandConfiguration(method: .custom, command: "ssh -N -L {port}:db:3306 prod")) + var cloudflare = ddevConnection() + cloudflare.cloudflareTunnelMode = .inline(CloudflareConfiguration(accessHostname: "db.example.com")) + var cloudSQL = ddevConnection() + cloudSQL.cloudSQLProxyMode = .inline(CloudSQLProxyConfiguration(instanceConnectionName: "p:r:i")) + var profile = ddevConnection() + profile.sshTunnelMode = .profile( + id: UUID(), + snapshot: SSHConfiguration(enabled: true, host: "bastion.example.com", username: "ops") + ) + return [ + (socks, "proxy.example.com:1080"), + (command, TunnelCommandMethod.custom.displayName), + (cloudflare, "db.example.com"), + (cloudSQL, "p:r:i"), + (profile, "bastion.example.com"), + ] + } + + @Test("A loopback link reached through a proxy, a tunnel command or an SSH profile asks every time") + func everyTransportIgnoresTrust() async throws { + for (connection, _) in routedConnections() { + let store = try makeStore() + store.trust(ExternalConnectionTrustKey(connection: ddevConnection(), scopeName: "ddev-shop")) + let prompt = SpyPrompt(decision: .alwaysAllow) + let gate = ExternalConnectionGate(trustStore: store, prompt: prompt) + + #expect(await gate.authorize(connection, scopeName: "ddev-shop")) + #expect(await gate.authorize(connection, scopeName: "ddev-shop")) + #expect(prompt.callCount == 2) + #expect(prompt.offeredAlwaysAllow == false) + #expect(store.entries().count == 1) + } + } + + @Test("Trust given to a link alone never covers a saved connection, and one saved connection never covers another") + func savedConnectionsKeepTheirOwnTrust() async throws { + let store = try makeStore() + store.trust(ExternalConnectionTrustKey(connection: ddevConnection(), scopeName: "ddev-shop")) + let prompt = SpyPrompt(decision: .alwaysAllow) + let gate = ExternalConnectionGate(trustStore: store, prompt: prompt) + let saved = ddevConnection() + + #expect(await gate.authorize(saved, isSaved: true, scopeName: "ddev-shop")) + #expect(prompt.callCount == 1) + #expect(prompt.offeredAlwaysAllow == true) + + #expect(await gate.authorize(saved, isSaved: true, scopeName: "ddev-shop")) + #expect(prompt.callCount == 1) + + #expect(await gate.authorize(ddevConnection(), isSaved: true, scopeName: "ddev-shop")) + #expect(prompt.callCount == 2) + } + + @Test("The alert names each transport a loopback link crosses") + func alertNamesTheTransports() { + for (connection, named) in routedConnections() { + let alert = ExternalConnectionAlertPrompt.makeAlert(for: connection, offerAlwaysAllow: false) + #expect(alert.informativeText.contains(named)) + } + } } diff --git a/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift b/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift index 3a986cf84a..b7b4918911 100644 --- a/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift +++ b/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift @@ -23,6 +23,29 @@ struct AppSettingsStorageResetTests { #expect(defaults.string(forKey: SidebarPersistenceKey.defaultLayout) == nil) } + @Test("Reset keeps the AI providers, the active one and the AI switch, and resets every other AI setting") + func resetKeepsAIProviders() throws { + let defaults = try pool.make().defaults + let storage = AppSettingsStorage(userDefaults: defaults) + let provider = AIProviderConfig(name: "Work", type: .claude) + var ai = AISettings.default + ai.providers = [provider] + ai.activeProviderID = provider.id + ai.enabled = false + ai.chatMode = .agent + ai.inlineSuggestionsEnabled = true + storage.saveAI(ai) + + storage.resetToDefaults() + + let reset = storage.loadAI() + #expect(reset.providers.map(\.id) == [provider.id]) + #expect(reset.activeProviderID == provider.id) + #expect(!reset.enabled) + #expect(reset.chatMode == AISettings.default.chatMode) + #expect(reset.inlineSuggestionsEnabled == AISettings.default.inlineSuggestionsEnabled) + } + @Test("Reset clears every remembered inspector field height and the geometry field's mode") func resetClearsInspectorFieldPreferences() throws { let defaults = try pool.make().defaults diff --git a/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift b/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift new file mode 100644 index 0000000000..b86783be7e --- /dev/null +++ b/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift @@ -0,0 +1,79 @@ +import AppKit +import Foundation +@testable import TablePro +import TableProSyncTransport +import TableProTheme +import Testing + +@MainActor +private final class SyncSwitchRecorder { + var calls: [Bool] = [] +} + +@MainActor +struct AppSettingsSyncSideEffectsTests { + private let pool = EphemeralDefaultsPool() + + private func makeManager( + flagDefaults: UserDefaults, + recorder: SyncSwitchRecorder, + root: URL + ) throws -> AppSettingsManager { + let tracker = SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: try pool.make().defaults)) + let catalog = ThemeCatalog( + userDirectory: root.appendingPathComponent("Themes", isDirectory: true), + bundleDirectory: nil, + notificationCenter: NotificationCenter(), + fileTrash: .folder(root.appendingPathComponent("Trash", isDirectory: true)), + syncTracker: tracker + ) + return AppSettingsManager( + storage: AppSettingsStorage(userDefaults: try pool.make().defaults), + themeEngine: ThemeEngine(catalog: catalog), + syncTracker: tracker, + appEvents: AppEvents(), + passwordSyncDefaults: flagDefaults, + switchSync: { recorder.calls.append($0) } + ) + } + + private static func makeRoot() -> URL { + FileManager.default.temporaryDirectory + .appendingPathComponent("AppSettingsSyncSideEffectsTests-\(UUID().uuidString)", isDirectory: true) + } + + @Test("Turning sync off from anywhere, a reset included, stops password sync and the coordinator") + func turningSyncOffReachesTheKeychainFlag() throws { + let flagDefaults = try pool.make().defaults + let recorder = SyncSwitchRecorder() + let root = Self.makeRoot() + defer { try? FileManager.default.removeItem(at: root) } + let manager = try makeManager(flagDefaults: flagDefaults, recorder: recorder, root: root) + + manager.sync.enabled = true + manager.sync.syncConnections = true + manager.sync.syncPasswords = true + #expect(flagDefaults.bool(forKey: KeychainHelper.passwordSyncEnabledKey)) + #expect(recorder.calls == [true]) + + manager.sync = .default + + #expect(!flagDefaults.bool(forKey: KeychainHelper.passwordSyncEnabledKey)) + #expect(recorder.calls == [true, false]) + } + + @Test("A change that leaves sync on or off as it was does not touch the coordinator") + func categoryChangeLeavesTheCoordinatorAlone() throws { + let flagDefaults = try pool.make().defaults + let recorder = SyncSwitchRecorder() + let root = Self.makeRoot() + defer { try? FileManager.default.removeItem(at: root) } + let manager = try makeManager(flagDefaults: flagDefaults, recorder: recorder, root: root) + + manager.sync.syncPasswords = true + manager.sync.syncTableFavorites = false + + #expect(recorder.calls.isEmpty) + #expect(!flagDefaults.bool(forKey: KeychainHelper.passwordSyncEnabledKey)) + } +} diff --git a/apple/TableProTests/Core/Storage/ConnectionApprovalStoreTests.swift b/apple/TableProTests/Core/Storage/ConnectionApprovalStoreTests.swift index 445e2a85d3..7de11bae94 100644 --- a/apple/TableProTests/Core/Storage/ConnectionApprovalStoreTests.swift +++ b/apple/TableProTests/Core/Storage/ConnectionApprovalStoreTests.swift @@ -6,6 +6,7 @@ import Foundation @testable import TablePro import TableProPluginKit +import TableProSSHConfig import Testing @MainActor @@ -143,6 +144,25 @@ struct ConnectionApprovalStoreTests { #expect(!store.isApproved(connection)) } + @Test("An approval through an SSH profile asks again once the profile moves to another server") + func movedProfileAsksAgain() { + let profiles = SSHProfileStorage.shared + let saved = profiles.loadProfiles() + var profile = SSHProfile(name: "Jump", host: "bastion-a.example", port: 22, username: "ops", authMethod: .password) + #expect(profiles.saveProfilesWithoutSync(saved + [profile])) + defer { profiles.saveProfilesWithoutSync(saved) } + var connection = referencing() + connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + let store = makeStore() + store.approve(connection) + #expect(store.isApproved(connection)) + + profile.host = "bastion-b.example" + #expect(profiles.saveProfilesWithoutSync(saved + [profile])) + + #expect(!store.isApproved(connection)) + } + @Test("Approving another destination keeps the earlier one") func approvalsAccumulatePerDestination() { let store = makeStore() diff --git a/apple/TableProTests/Core/Storage/ConnectionStoragePersistenceTests.swift b/apple/TableProTests/Core/Storage/ConnectionStoragePersistenceTests.swift index 3dab06d1c9..791d5a49b0 100644 --- a/apple/TableProTests/Core/Storage/ConnectionStoragePersistenceTests.swift +++ b/apple/TableProTests/Core/Storage/ConnectionStoragePersistenceTests.swift @@ -51,6 +51,28 @@ struct ConnectionStoragePersistenceTests { #expect(reloaded.contains { $0.id == connection.id }) } + @Test("A missing connections.json is a fresh, trusted library") + func missingFileIsAFreshLibrary() { + #expect(storage.loadConnections().isEmpty) + #expect(!storage.lastLoadFailed) + #expect(storage.storeIsTrusted) + } + + @Test("A connections.json that cannot be read is a failed load, never saved over") + func unreadableFileIsNeverOverwritten() throws { + try FileManager.default.createDirectory(at: fileURL, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: fileURL) } + + #expect(storage.loadConnections().isEmpty) + #expect(storage.lastLoadFailed) + #expect(!storage.storeIsTrusted) + #expect(!storage.saveConnections([DatabaseConnection(name: "Fresh")])) + + var isDirectory: ObjCBool = false + #expect(FileManager.default.fileExists(atPath: fileURL.path, isDirectory: &isDirectory)) + #expect(isDirectory.boolValue) + } + @Test("updateSafeModeLevel writes the new level through to disk") func updateSafeModeLevelWritesThrough() { let connection = DatabaseConnection( diff --git a/apple/TableProTests/Helpers/RecordingClipboard.swift b/apple/TableProTests/Helpers/RecordingClipboard.swift index 034d794186..10a41059d7 100644 --- a/apple/TableProTests/Helpers/RecordingClipboard.swift +++ b/apple/TableProTests/Helpers/RecordingClipboard.swift @@ -12,6 +12,7 @@ final class RecordingClipboard: ClipboardProvider { var gridCells: GridCellsClipboardPayload? private(set) var html: String? private(set) var writes: [String] = [] + private(set) var secretWrites: [String] = [] private(set) var images: [NSImage] = [] var hasText: Bool { text != nil } @@ -22,6 +23,11 @@ final class RecordingClipboard: ClipboardProvider { func readGridCells() -> GridCellsClipboardPayload? { gridCells } func writeText(_ text: String) { replace(text: text) } + + func writeSecretText(_ text: String) { + replace(text: text) + secretWrites.append(text) + } func writeCsv(_ csv: String) { replace(text: csv) } func writeImage(_ image: NSImage) { diff --git a/apple/TableProTests/ViewModels/WelcomeViewModelTeamLibraryTests.swift b/apple/TableProTests/ViewModels/WelcomeViewModelTeamLibraryTests.swift index 69fcdadaa9..9b310390fe 100644 --- a/apple/TableProTests/ViewModels/WelcomeViewModelTeamLibraryTests.swift +++ b/apple/TableProTests/ViewModels/WelcomeViewModelTeamLibraryTests.swift @@ -52,6 +52,30 @@ struct WelcomeViewModelTeamLibraryTests { #expect(fixture.sync.content.connections.map(\.settings.name) == ["Prod", "Staging"]) } + @Test("A published connection carries neither its tunnel command nor its startup commands") + func publishLeavesCommandsOut() async throws { + let fixture = try await TeamLibraryFixture() + var prod = DatabaseConnection(name: "Prod", type: .postgresql) + prod.tunnelCommandMode = .inline(TunnelCommandConfiguration( + method: .custom, + command: "cloudflared access tcp --url localhost:{port} --service-token-secret S3cret" + )) + prod.startupCommands = "SET app.token = 'S3cret';" + + let outcome = await WelcomeViewModel.publishConnections( + [prod], + to: TeamLibraryFixture.team, + through: fixture.sync, + confirm: { _ in true } + ) + + #expect(outcome == .finished(.published(1))) + let data = try #require(await fixture.pushes().first?.first?["data"] as? [String: Any]) + #expect(data["name"] as? String == "Prod") + #expect(data["tunnelCommand"] == nil) + #expect(data["startupCommands"] == nil) + } + @Test("A member who only reads the library gets told so, and nothing is pushed") func readerCannotPublish() async throws { let fixture = try await TeamLibraryFixture(role: "member") diff --git a/apple/TableProTests/Views/ERDiagram/ERDiagramBitmapExportTests.swift b/apple/TableProTests/Views/ERDiagram/ERDiagramBitmapExportTests.swift new file mode 100644 index 0000000000..e734ccc66a --- /dev/null +++ b/apple/TableProTests/Views/ERDiagram/ERDiagramBitmapExportTests.swift @@ -0,0 +1,75 @@ +import AppKit +@testable import TablePro +import Testing + +@MainActor +struct ERDiagramBitmapExportTests { + private func scene(tablesAt origins: [CGPoint]) -> ERDiagramScene { + let columns = [ERColumnDisplay(id: "id", name: "id", dataType: "integer", isPrimaryKey: true, isForeignKey: false, isNullable: false)] + var nodes: [ERTableNode] = [] + var rects: [UUID: CGRect] = [:] + var index: [String: UUID] = [:] + for (offset, origin) in origins.enumerated() { + let node = ERTableNode(id: UUID(), tableName: "t\(offset)", columns: columns, displayColumns: columns, clusterId: 0) + nodes.append(node) + rects[node.id] = CGRect( + origin: origin, + size: CGSize(width: ERDiagramLayout.nodeWidth, height: ERDiagramLayout.estimateHeight(columnCount: 1)) + ) + index[node.tableName] = node.id + } + return ERDiagramScene(nodes: nodes, edges: [], nodeRects: rects, nodeIndex: index) + } + + private func pixels(of image: NSImage?) throws -> (wide: Int, high: Int) { + let rep = try #require(image?.representations.first as? NSBitmapImageRep) + return (rep.pixelsWide, rep.pixelsHigh) + } + + private func appearance() throws -> NSAppearance { + try #require(NSAppearance(named: .aqua)) + } + + @Test("A small diagram still renders at twice its size") + func smallDiagramKeepsTheRequestedScale() throws { + let small = scene(tablesAt: [.zero, CGPoint(x: 400, y: 0)]) + let image = ERDiagramSceneRenderer.image(small, appearance: try appearance(), scale: 2) + let size = try #require(image?.size) + + let rendered = try pixels(of: image) + #expect(rendered.wide == Int((size.width * 2).rounded(.down))) + #expect(rendered.high == Int((size.height * 2).rounded(.down))) + } + + @Test("A diagram wider than the side limit renders within it") + func wideDiagramStaysWithinTheSideLimit() throws { + let wide = scene(tablesAt: [.zero, CGPoint(x: 20_000, y: 0)]) + + let rendered = try pixels(of: ERDiagramSceneRenderer.image(wide, appearance: try appearance(), scale: 2)) + + #expect(CGFloat(rendered.wide) <= ERDiagramSceneRenderer.maxBitmapSide) + #expect(rendered.wide > 16_000) + } + + @Test("A diagram of hundreds of tables is scaled to the pixel budget, never past the requested scale") + func largeDiagramStaysWithinThePixelBudget() { + let size = CGSize(width: 7_500, height: 7_600) + let scale = ERDiagramSceneRenderer.bitmapScale(for: size, requested: 2) + + let wide = (size.width * scale).rounded(.down) + let high = (size.height * scale).rounded(.down) + #expect(scale < 2) + #expect(wide * high <= ERDiagramSceneRenderer.maxBitmapPixels) + #expect(max(wide, high) <= ERDiagramSceneRenderer.maxBitmapSide) + #expect(ERDiagramSceneRenderer.bitmapScale(for: CGSize(width: 800, height: 600), requested: 2) == 2) + } + + @Test("PNG export encodes the capped bitmap") + func pngExportIsCapped() throws { + let wide = scene(tablesAt: [.zero, CGPoint(x: 20_000, y: 0)]) + let data = try #require(ERDiagramSceneRenderer.pngData(wide, appearance: try appearance(), scale: 2)) + let rep = try #require(NSBitmapImageRep(data: data)) + + #expect(CGFloat(rep.pixelsWide) <= ERDiagramSceneRenderer.maxBitmapSide) + } +} From 4f05f7efd088a8622d30ce9d610592dc69da3955 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 07:37:49 +0700 Subject: [PATCH 2/3] chore(changelog): add the fragments for the audit conn-settings lane --- apple/changelog.d/4222.changed.1.md | 1 + apple/changelog.d/4222.changed.md | 1 + apple/changelog.d/4222.fixed.1.md | 1 + apple/changelog.d/4222.fixed.2.md | 1 + apple/changelog.d/4222.fixed.3.md | 1 + apple/changelog.d/4222.fixed.4.md | 1 + apple/changelog.d/4222.fixed.md | 1 + apple/changelog.d/4222.security.1.md | 1 + apple/changelog.d/4222.security.2.md | 1 + apple/changelog.d/4222.security.3.md | 1 + apple/changelog.d/4222.security.4.md | 1 + apple/changelog.d/4222.security.5.md | 1 + apple/changelog.d/4222.security.md | 1 + 13 files changed, 13 insertions(+) create mode 100644 apple/changelog.d/4222.changed.1.md create mode 100644 apple/changelog.d/4222.changed.md create mode 100644 apple/changelog.d/4222.fixed.1.md create mode 100644 apple/changelog.d/4222.fixed.2.md create mode 100644 apple/changelog.d/4222.fixed.3.md create mode 100644 apple/changelog.d/4222.fixed.4.md create mode 100644 apple/changelog.d/4222.fixed.md create mode 100644 apple/changelog.d/4222.security.1.md create mode 100644 apple/changelog.d/4222.security.2.md create mode 100644 apple/changelog.d/4222.security.3.md create mode 100644 apple/changelog.d/4222.security.4.md create mode 100644 apple/changelog.d/4222.security.5.md create mode 100644 apple/changelog.d/4222.security.md diff --git a/apple/changelog.d/4222.changed.1.md b/apple/changelog.d/4222.changed.1.md new file mode 100644 index 0000000000..6e9b0ae25a --- /dev/null +++ b/apple/changelog.d/4222.changed.1.md @@ -0,0 +1 @@ +A connection on an SSH profile asks once more before it signs in with this Mac's credentials or environment variables. diff --git a/apple/changelog.d/4222.changed.md b/apple/changelog.d/4222.changed.md new file mode 100644 index 0000000000..cd892381fb --- /dev/null +++ b/apple/changelog.d/4222.changed.md @@ -0,0 +1 @@ +Reset All Settings keeps AI providers, their API keys and the Enable AI Features switch. diff --git a/apple/changelog.d/4222.fixed.1.md b/apple/changelog.d/4222.fixed.1.md new file mode 100644 index 0000000000..ed4a5fe886 --- /dev/null +++ b/apple/changelog.d/4222.fixed.1.md @@ -0,0 +1 @@ +Copying or exporting a large ER diagram as an image could freeze TablePro and use gigabytes of memory. diff --git a/apple/changelog.d/4222.fixed.2.md b/apple/changelog.d/4222.fixed.2.md new file mode 100644 index 0000000000..db0e508cfa --- /dev/null +++ b/apple/changelog.d/4222.fixed.2.md @@ -0,0 +1 @@ +Removing an AI provider from its sheet asked twice. diff --git a/apple/changelog.d/4222.fixed.3.md b/apple/changelog.d/4222.fixed.3.md new file mode 100644 index 0000000000..c492baacf6 --- /dev/null +++ b/apple/changelog.d/4222.fixed.3.md @@ -0,0 +1 @@ +Deleting a custom slash command or resetting all keyboard shortcuts happened on one click. diff --git a/apple/changelog.d/4222.fixed.4.md b/apple/changelog.d/4222.fixed.4.md new file mode 100644 index 0000000000..86fe3cec32 --- /dev/null +++ b/apple/changelog.d/4222.fixed.4.md @@ -0,0 +1 @@ +Remove on a plugin that failed to load deleted it at once, with no confirmation, bundled plugins included. diff --git a/apple/changelog.d/4222.fixed.md b/apple/changelog.d/4222.fixed.md new file mode 100644 index 0000000000..281c72ce45 --- /dev/null +++ b/apple/changelog.d/4222.fixed.md @@ -0,0 +1 @@ +A connections file that could not be read loaded as an empty library, and the next save or sync wrote over it. diff --git a/apple/changelog.d/4222.security.1.md b/apple/changelog.d/4222.security.1.md new file mode 100644 index 0000000000..a1617698c3 --- /dev/null +++ b/apple/changelog.d/4222.security.1.md @@ -0,0 +1 @@ +Sign-in approvals through an SSH profile still held after the profile moved to another server. diff --git a/apple/changelog.d/4222.security.2.md b/apple/changelog.d/4222.security.2.md new file mode 100644 index 0000000000..9130adb4f5 --- /dev/null +++ b/apple/changelog.d/4222.security.2.md @@ -0,0 +1 @@ +Copied connection strings and MCP tokens were not marked concealed, so clipboard history apps could keep them. diff --git a/apple/changelog.d/4222.security.3.md b/apple/changelog.d/4222.security.3.md new file mode 100644 index 0000000000..858a25ccf1 --- /dev/null +++ b/apple/changelog.d/4222.security.3.md @@ -0,0 +1 @@ +Publishing a connection to the team library uploaded its tunnel command and startup commands. diff --git a/apple/changelog.d/4222.security.4.md b/apple/changelog.d/4222.security.4.md new file mode 100644 index 0000000000..bc91f22f62 --- /dev/null +++ b/apple/changelog.d/4222.security.4.md @@ -0,0 +1 @@ +Always Allow was offered for a local link to a connection that goes through a proxy, tunnel command or SSH profile. diff --git a/apple/changelog.d/4222.security.5.md b/apple/changelog.d/4222.security.5.md new file mode 100644 index 0000000000..448b24f3b1 --- /dev/null +++ b/apple/changelog.d/4222.security.5.md @@ -0,0 +1 @@ +Reset All Settings left iCloud password sync on until relaunch, though the Sync pane showed it off. diff --git a/apple/changelog.d/4222.security.md b/apple/changelog.d/4222.security.md new file mode 100644 index 0000000000..88b269c07d --- /dev/null +++ b/apple/changelog.d/4222.security.md @@ -0,0 +1 @@ +A reconnect TablePro started on its own could follow an edited SSH profile to another server under an open window. From 6b0b917376d2510ad1155d767e79900e70fe6488 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 23:06:28 +0700 Subject: [PATCH 3/3] test(macos): build ThemeCatalog without the notification center #4229 removed --- .../Core/Storage/AppSettingsSyncSideEffectsTests.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift b/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift index b86783be7e..0dc7026d58 100644 --- a/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift +++ b/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift @@ -23,7 +23,6 @@ struct AppSettingsSyncSideEffectsTests { let catalog = ThemeCatalog( userDirectory: root.appendingPathComponent("Themes", isDirectory: true), bundleDirectory: nil, - notificationCenter: NotificationCenter(), fileTrash: .folder(root.appendingPathComponent("Trash", isDirectory: true)), syncTracker: tracker )