diff --git a/IOS_Client_Xcode/TM_Sonder_Client/Package.swift b/IOS_Client_Xcode/TM_Sonder_Client/Package.swift index ecd12b2..80d6109 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/Package.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/Package.swift @@ -3,7 +3,7 @@ import PackageDescription import Foundation // Exercise the actual client persistence code without a simulator or signing. -let sources = ["SonderClientModels.swift", "SonderOfflineDownloads.swift", "SonderAudiobookChapters.swift", "SonderProgressQueue.swift", "SonderEPUB.swift"] +let sources = ["SonderClientModels.swift", "SonderOfflineDownloads.swift", "SonderAudiobookChapters.swift", "SonderProgressQueue.swift", "SonderEPUB.swift", "SonderServerConnection.swift"] let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("TM_Sonder_Client") let excluded = (try? FileManager.default.contentsOfDirectory(atPath: directory.path))?.filter { !sources.contains($0) } ?? [] let package = Package( diff --git a/IOS_Client_Xcode/TM_Sonder_Client/ReleaseTests/ServerConnectionTests.swift b/IOS_Client_Xcode/TM_Sonder_Client/ReleaseTests/ServerConnectionTests.swift new file mode 100644 index 0000000..e077791 --- /dev/null +++ b/IOS_Client_Xcode/TM_Sonder_Client/ReleaseTests/ServerConnectionTests.swift @@ -0,0 +1,237 @@ +import XCTest +@testable import OfflineCore + +final class ServerAddressTests: XCTestCase { + func testParseAddsSchemeAndNormalizes() { + XCTAssertEqual(SonderServerAddresses.parse(" sonder.stoverparc.org/ ", defaultScheme: "https")?.absoluteString, + "https://sonder.stoverparc.org") + XCTAssertEqual(SonderServerAddresses.parse("10.20.0.117:8096", defaultScheme: "http")?.absoluteString, + "http://10.20.0.117:8096") + XCTAssertEqual(SonderServerAddresses.parse("HTTPS://Sonder.Example.org/base/?x=1#y", defaultScheme: "http")?.absoluteString, + "https://sonder.example.org/base") + } + + func testParseRejectsUnusableText() { + XCTAssertNil(SonderServerAddresses.parse("", defaultScheme: "https")) + XCTAssertNil(SonderServerAddresses.parse(" ", defaultScheme: "https")) + XCTAssertNil(SonderServerAddresses.parse("ftp://files.example.org", defaultScheme: "https")) + XCTAssertNil(SonderServerAddresses.parse("https://", defaultScheme: "https")) + } + + func testIdentityPrefersPublicAddress() { + let publicURL = URL(string: "https://sonder.example.org")! + let localURL = URL(string: "http://10.0.0.5:8096")! + XCTAssertEqual(SonderServerAddresses(publicURL: publicURL, localURL: localURL).identityURL, publicURL) + XCTAssertEqual(SonderServerAddresses(publicURL: nil, localURL: localURL).identityURL, localURL) + XCTAssertTrue(SonderServerAddresses().isEmpty) + } +} + +final class EndpointSelectorTests: XCTestCase { + private let publicURL = URL(string: "https://sonder.example.org")! + private let localURL = URL(string: "http://10.0.0.5:8096")! + + func testUsesLocalWhenItAnswers() async { + let probed = ProbeLog() + let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: localURL)) { url in + await probed.add(url); return true + } + XCTAssertEqual(choice, SonderEndpointChoice(url: localURL, route: .local)) + let urls = await probed.urls + XCTAssertEqual(urls, [localURL]) + } + + func testFallsBackToPublicWhenLocalDoesNotAnswer() async { + let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: localURL)) { _ in false } + XCTAssertEqual(choice, SonderEndpointChoice(url: publicURL, route: .public)) + } + + func testPublicOnlyIsNotProbed() async { + let probed = ProbeLog() + let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: nil)) { url in + await probed.add(url); return false + } + XCTAssertEqual(choice, SonderEndpointChoice(url: publicURL, route: .public)) + let urls = await probed.urls + XCTAssertTrue(urls.isEmpty) + } + + func testSameAddressTwiceIsTreatedAsPublic() async { + let probed = ProbeLog() + let choice = await SonderEndpointSelector.choose(.init(publicURL: publicURL, localURL: publicURL)) { url in + await probed.add(url); return true + } + XCTAssertEqual(choice?.route, .public) + let urls = await probed.urls + XCTAssertTrue(urls.isEmpty) + } + + func testLocalOnlyIsUsedEvenWhenUnreachable() async { + let choice = await SonderEndpointSelector.choose(.init(publicURL: nil, localURL: localURL)) { _ in false } + XCTAssertEqual(choice, SonderEndpointChoice(url: localURL, route: .local)) + } + + func testNoAddressesGivesNoChoice() async { + let choice = await SonderEndpointSelector.choose(.init()) { _ in true } + XCTAssertNil(choice) + } +} + +final class ServerProbeTests: XCTestCase { + override func tearDown() { StubURLProtocol.handler = nil } + + private var probe: SonderServerProbe { SonderServerProbe(session: StubURLProtocol.session(), timeout: 1) } + private let base = URL(string: "http://10.0.0.5:8096")! + + func testSonderIdentityHeaderCountsAsReachable() async { + StubURLProtocol.handler = { request in + XCTAssertEqual(request.url?.path, "/api/auth/session") + XCTAssertNil(request.value(forHTTPHeaderField: "Cookie")) + return (401, ["X-Sonder-Server": "tm-sonder"], Data()) + } + let reachable = await probe.isSonderServer(base) + XCTAssertTrue(reachable) + } + + func testOtherWebServerIsNotReachable() async { + StubURLProtocol.handler = { _ in (200, ["Content-Type": "text/html"], Data("portal".utf8)) } + let reachable = await probe.isSonderServer(base) + XCTAssertFalse(reachable) + } + + func testNetworkFailureIsNotReachable() async { + StubURLProtocol.handler = { _ in throw URLError(.cannotConnectToHost) } + let reachable = await probe.isSonderServer(base) + XCTAssertFalse(reachable) + } +} + +final class AccountSignInTests: XCTestCase { + override func tearDown() { StubURLProtocol.handler = nil } + + private var client: SonderAccountClient { SonderAccountClient(session: StubURLProtocol.session()) } + private let base = URL(string: "https://sonder.example.org")! + + func testSignInReturnsSessionCookieAsToken() async throws { + StubURLProtocol.handler = { request in + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.url?.path, "/api/auth/login") + XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json") + let body = try JSONSerialization.jsonObject(with: StubURLProtocol.body(of: request)) as? [String: String] + XCTAssertEqual(body?["username"], "sean") + XCTAssertEqual(body?["password"], "correct horse") + return (200, ["Set-Cookie": "sonder_session=abc123; Path=/; Expires=Wed, 02 Dec 2026 18:00:00 GMT; HttpOnly; Secure; SameSite=Lax", + "Content-Type": "application/json"], + Data(#"{"authenticated":true,"username":"sean","expiresAt":"2026-12-02T18:00:00.123456789Z"}"#.utf8)) + } + let result = try await client.signIn(baseURL: base, username: " sean ", password: "correct horse") + XCTAssertEqual(result.token, "abc123") + XCTAssertEqual(result.username, "sean") + XCTAssertEqual(result.expiresAt?.timeIntervalSince1970 ?? 0, 1_796_234_400.123, accuracy: 0.01) + } + + func testWrongPasswordFromSonderIsInvalidCredentials() async { + StubURLProtocol.handler = { _ in (401, ["X-Sonder-Server": "tm-sonder"], Data(#"{"error":"Invalid credentials"}"#.utf8)) } + await assertSignIn(throws: .invalidCredentials) + } + + func testUnauthorizedWithoutSonderHeaderIsNotSonder() async { + StubURLProtocol.handler = { _ in (401, [:], Data()) } + await assertSignIn(throws: .notSonderServer) + } + + func testThrottleCarriesRetryAfter() async { + StubURLProtocol.handler = { _ in (429, ["Retry-After": "900", "X-Sonder-Server": "tm-sonder"], Data()) } + await assertSignIn(throws: .throttled(retryAfterSeconds: 900)) + } + + func testNoAccountYetIsSetupRequired() async { + StubURLProtocol.handler = { _ in (409, ["X-Sonder-Server": "tm-sonder"], Data()) } + await assertSignIn(throws: .setupRequired) + } + + func testSuccessWithoutCookieIsReported() async { + StubURLProtocol.handler = { _ in (200, ["X-Sonder-Server": "tm-sonder"], Data(#"{"authenticated":true}"#.utf8)) } + await assertSignIn(throws: .noSessionIssued) + } + + func testSessionStatusSendsBearerToken() async throws { + StubURLProtocol.handler = { request in + XCTAssertEqual(request.url?.path, "/api/auth/session") + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer tok") + return (200, ["X-Sonder-Server": "tm-sonder"], + Data(#"{"authenticated":true,"googleLinked":false,"setupRequired":false,"username":"sean"}"#.utf8)) + } + let status = try await client.sessionStatus(baseURL: base, token: "tok") + XCTAssertEqual(status, SonderAuthSessionStatus(setupRequired: false, authenticated: true, username: "sean")) + } + + func testServerDateParsingAcceptsGoNanoseconds() { + XCTAssertNotNil(SonderAccountClient.parseServerDate("2026-12-02T18:00:00.123456789Z")) + XCTAssertNotNil(SonderAccountClient.parseServerDate("2026-12-02T18:00:00-05:00")) + XCTAssertNil(SonderAccountClient.parseServerDate("not a date")) + XCTAssertNil(SonderAccountClient.parseServerDate(nil)) + } + + private func assertSignIn(throws expected: SonderSignInError, file: StaticString = #filePath, line: UInt = #line) async { + do { + _ = try await client.signIn(baseURL: base, username: "sean", password: "pw") + XCTFail("Expected \(expected)", file: file, line: line) + } catch { + XCTAssertEqual(error as? SonderSignInError, expected, file: file, line: line) + } + } +} + +private actor ProbeLog { + var urls: [URL] = [] + func add(_ url: URL) { urls.append(url) } +} + +/// Serves canned responses so the networking code runs without a server. +final class StubURLProtocol: URLProtocol, @unchecked Sendable { + typealias Handler = @Sendable (URLRequest) throws -> (Int, [String: String], Data) + nonisolated(unsafe) static var handler: Handler? + + static func session() -> URLSession { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [StubURLProtocol.self] + return URLSession(configuration: configuration) + } + + static func body(of request: URLRequest) -> Data { + if let body = request.httpBody { return body } + guard let stream = request.httpBodyStream else { return Data() } + stream.open() + defer { stream.close() } + var data = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { + let count = stream.read(&buffer, maxLength: buffer.count) + if count <= 0 { break } + data.append(buffer, count: count) + } + return data + } + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + guard let handler = Self.handler else { + client?.urlProtocol(self, didFailWithError: URLError(.unknown)) + return + } + do { + let (status, headers, data) = try handler(request) + let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data) + client?.urlProtocolDidFinishLoading(self) + } catch { + client?.urlProtocol(self, didFailWithError: error) + } + } + + override func stopLoading() {} +} diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ContentView.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ContentView.swift index 53e9800..ae5b5c0 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ContentView.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ContentView.swift @@ -6,6 +6,7 @@ struct ContentView: View { @Environment(\.scenePhase) private var scenePhase @StateObject private var model = SonderClientModel() @StateObject private var browser = SonderServerBrowser() + @State private var signInDismissed = false var body: some View { NavigationStack { @@ -37,6 +38,15 @@ struct ContentView: View { guard let endpoint = endpoints.first(where: model.shouldAutomaticallyUseDiscoveredEndpoint) else { return } Task { await model.connect(to: endpoint) } } + .onChange(of: model.needsSignIn) { _, needsSignIn in + if needsSignIn == false { signInDismissed = false } + } + .sheet(isPresented: Binding( + get: { model.hasConfiguredServer && model.needsSignIn && signInDismissed == false }, + set: { if $0 == false { signInDismissed = true } } + )) { + ServerSignInView(model: model) { signInDismissed = true } + } .tint(SonderPalette.accent) } } @@ -44,8 +54,10 @@ struct ContentView: View { struct ServerOnboardingView: View { @ObservedObject var model: SonderClientModel @ObservedObject var browser: SonderServerBrowser - @State private var manualURL = "" + @State private var publicURLText = "" + @State private var localURLText = "" @State private var token = "" + @State private var addressError: String? var body: some View { ScrollView { @@ -117,7 +129,7 @@ struct ServerOnboardingView: View { Text("Searching for Sonder on your local network") .font(.subheadline.weight(.semibold)) .foregroundStyle(SonderPalette.text) - Text("Make sure LAN sharing is enabled on the Mac server. Tailscale and private URLs can be entered below.") + Text("Make sure LAN sharing is enabled on the server, or enter its address below.") .font(.caption) .foregroundStyle(SonderPalette.textLight) } @@ -160,24 +172,17 @@ struct ServerOnboardingView: View { private var manualPanel: some View { VStack(alignment: .leading, spacing: 12) { - Label("Manual or Tailscale", systemImage: "link") + Label("Server address", systemImage: "link") .font(.headline) .foregroundStyle(SonderPalette.text) - TextField("http://sonder.local:8797", text: $manualURL) - .textFieldStyle(.plain) - .autocorrectionDisabled() - .textInputAutocapitalization(.never) - .padding(12) - .background(SonderPalette.surfaceDeep, in: RoundedRectangle(cornerRadius: 8)) - .overlay(RoundedRectangle(cornerRadius: 8).stroke(SonderPalette.border)) + ServerAddressFields(publicText: $publicURLText, localText: $localURLText, pairingToken: $token) - SecureField("Optional token for restricted servers", text: $token) - .textFieldStyle(.plain) - .autocorrectionDisabled() - .padding(12) - .background(SonderPalette.surfaceDeep, in: RoundedRectangle(cornerRadius: 8)) - .overlay(RoundedRectangle(cornerRadius: 8).stroke(SonderPalette.border)) + if let addressError { + Label(addressError, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundStyle(SonderPalette.ironGrey) + } Button { connectManualURL() @@ -186,7 +191,8 @@ struct ServerOnboardingView: View { .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) - .disabled(URL(string: manualURL.trimmingCharacters(in: .whitespacesAndNewlines)) == nil) + .disabled(publicURLText.trimmingCharacters(in: .whitespaces).isEmpty && localURLText.trimmingCharacters(in: .whitespaces).isEmpty) + .accessibilityIdentifier("server.connect") } .padding(16) .background(SonderPalette.surface, in: RoundedRectangle(cornerRadius: 8)) @@ -194,9 +200,15 @@ struct ServerOnboardingView: View { } private func connectManualURL() { - guard let url = URL(string: manualURL.trimmingCharacters(in: .whitespacesAndNewlines)) else { return } - model.saveServer(baseURL: url, accessToken: token) - Task { await model.reload() } + switch ServerAddressFields.addresses(publicText: publicURLText, localText: localURLText) { + case let .failure(error): + addressError = error.message + case let .success(addresses): + addressError = nil + let pairing = token.trimmingCharacters(in: .whitespacesAndNewlines) + guard model.saveServer(addresses: addresses, pairingToken: pairing.isEmpty ? nil : pairing) else { return } + Task { await model.reload() } + } } } diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryArtworkViews.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryArtworkViews.swift index 288526d..cfe5f00 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryArtworkViews.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryArtworkViews.swift @@ -85,6 +85,7 @@ struct CachedPosterImage: View { // Posters dominate initial rendering. Allow URLSession's disk-backed // cache to satisfy repeat launches instead of redownloading every card. request.cachePolicy = .returnCacheDataElseLoad + request.httpShouldHandleCookies = false let token = accessToken.trimmingCharacters(in: .whitespacesAndNewlines) if token.isEmpty == false { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryHomeViews.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryHomeViews.swift index 4fcabcd..9bce2ec 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryHomeViews.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryHomeViews.swift @@ -21,7 +21,7 @@ struct LibraryHomeTab: View { LibrarySearchBar(model: model) if model.filteredItems.isEmpty && model.isLoading == false { - EmptyLibraryState() + EmptyLibraryState(needsSignIn: model.needsSignIn) } else { if inProgressItems.isEmpty == false { MediaShelf(title: "Continue Watching", subtitle: "Pick up where you left off", items: Array(inProgressItems.prefix(12)), model: model, selectedItem: $selectedItem) @@ -100,7 +100,7 @@ struct MediaKindTab: View { LibrarySearchBar(model: model) if items.isEmpty { - EmptyLibraryState() + EmptyLibraryState(needsSignIn: model.needsSignIn) } else { LazyVGrid(columns: [GridItem(.adaptive(minimum: 126, maximum: 150), spacing: 16)], spacing: 18) { ForEach(items) { item in @@ -218,8 +218,12 @@ struct SectionHeader: View { } struct EmptyLibraryState: View { + var needsSignIn = false + var body: some View { - ContentUnavailableView("No Titles", systemImage: "rectangle.stack", description: Text("Check the server URL or adjust the current filters.")) + ContentUnavailableView(needsSignIn ? "Sign In to See Your Library" : "No Titles", + systemImage: needsSignIn ? "person.crop.circle.badge.exclamationmark" : "rectangle.stack", + description: Text(needsSignIn ? "The server answered and needs your Sonder account. Sign in from Settings." : "Check the server address or adjust the current filters.")) .foregroundStyle(SonderPalette.text) .frame(maxWidth: .infinity, minHeight: 260) } diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryReadingHomeViews.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryReadingHomeViews.swift index 0e337c2..09e88ea 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryReadingHomeViews.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryReadingHomeViews.swift @@ -48,7 +48,7 @@ struct ReadingLibraryTab: View { VerificationShelf(items: needsAttention, model: model, selectedItem: $selectedItem) } if items.isEmpty { - EmptyLibraryState() + EmptyLibraryState(needsSignIn: model.needsSignIn) } else { Text("All \(title)") .font(.title3.bold()) diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibrarySettingsViews.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibrarySettingsViews.swift index e637f71..eea04fb 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibrarySettingsViews.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibrarySettingsViews.swift @@ -3,13 +3,16 @@ import SonderAPI struct ServerSettingsTab: View { @ObservedObject var model: SonderClientModel - @State private var serverText: String - @State private var tokenText: String + @State private var publicText: String + @State private var localText: String + @State private var tokenText = "" + @State private var addressError: String? + @State private var showsSignIn = false init(model: SonderClientModel) { self.model = model - _serverText = State(initialValue: model.serverBaseURL.absoluteString) - _tokenText = State(initialValue: model.accessToken) + _publicText = State(initialValue: model.addresses.publicURL?.absoluteString ?? "") + _localText = State(initialValue: model.addresses.localURL?.absoluteString ?? "") } var body: some View { @@ -17,6 +20,7 @@ struct ServerSettingsTab: View { VStack(alignment: .leading, spacing: 18) { SectionHeader(title: "Server", subtitle: "Connection, discovery, and sync", count: nil) connectionCard + accountCard manualConnectionCard DisclosureGroup("Offline storage") { offlineDownloadsCard } .sonderPanel() @@ -32,6 +36,12 @@ struct ServerSettingsTab: View { await model.reload() } .navigationTitle("Settings") + .sheet(isPresented: $showsSignIn) { + ServerSignInView(model: model) { showsSignIn = false } + } + .onChange(of: model.needsSignIn) { _, needsSignIn in + if needsSignIn == false { showsSignIn = false } + } } private var connectionCard: some View { @@ -53,11 +63,35 @@ struct ServerSettingsTab: View { Spacer() } - Text(model.serverBaseURL.absoluteString) - .font(.caption) - .foregroundStyle(SonderPalette.textLight) - .lineLimit(1) - .truncationMode(.middle) + HStack(spacing: 8) { + Image(systemName: model.activeRoute == .local ? "house.fill" : "globe") + .foregroundStyle(SonderPalette.ironGrey) + VStack(alignment: .leading, spacing: 1) { + Text(model.isSelectingRoute ? "Checking local address…" : "Active: \(model.activeRoute.label)") + .font(.caption.weight(.semibold)) + .foregroundStyle(SonderPalette.text) + .accessibilityIdentifier("server.activeRoute") + Text(model.activeBaseURL.absoluteString) + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer() + if model.addresses.localURL != nil { + Button { + Task { + await model.selectRoute() + await model.reload() + } + } label: { + Image(systemName: "arrow.triangle.2.circlepath") + } + .buttonStyle(.borderless) + .disabled(model.isSelectingRoute || model.isLoading) + .accessibilityLabel("Check the local address again") + } + } if model.pendingProgressCount > 0 { Label( @@ -89,27 +123,64 @@ struct ServerSettingsTab: View { .sonderPanel() } + private var accountCard: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Account") + .font(.headline) + .foregroundStyle(SonderPalette.text) + if let username = model.signedInUsername, model.needsSignIn == false, model.accessToken.isEmpty == false { + Label("Signed in as \(username)", systemImage: "person.crop.circle.badge.checkmark") + .font(.subheadline) + .foregroundStyle(SonderPalette.text) + Button(role: .destructive) { + Task { await model.signOut() } + } label: { + Label("Sign Out", systemImage: "rectangle.portrait.and.arrow.right") + } + .buttonStyle(.bordered) + } else { + Text(model.needsSignIn ? "This server needs you to sign in." : "Sign in with your Sonder account.") + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + Button { + showsSignIn = true + } label: { + Label("Sign In", systemImage: "person.crop.circle") + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .tint(SonderPalette.ironGrey) + .accessibilityIdentifier("settings.signIn") + } + } + .sonderPanel() + } + private var manualConnectionCard: some View { VStack(alignment: .leading, spacing: 12) { - Text("Manual or Tailscale") + Text("Server addresses") .font(.headline) .foregroundStyle(SonderPalette.text) - TextField("http://sonder.local:8797", text: $serverText) - .textFieldStyle(.plain) - .autocorrectionDisabled() - .textInputAutocapitalization(.never) - .sonderInput() + ServerAddressFields(publicText: $publicText, localText: $localText, pairingToken: $tokenText) - SecureField("Optional token for restricted servers", text: $tokenText) - .textFieldStyle(.plain) - .autocorrectionDisabled() - .sonderInput() + if let addressError { + Label(addressError, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundStyle(SonderPalette.ironGrey) + } Button { - if let url = URL(string: serverText.trimmingCharacters(in: .whitespacesAndNewlines)) { - model.saveServer(baseURL: url, accessToken: tokenText) - Task { await model.reload() } + switch ServerAddressFields.addresses(publicText: publicText, localText: localText) { + case let .failure(error): + addressError = error.message + case let .success(addresses): + addressError = nil + let pairing = tokenText.trimmingCharacters(in: .whitespacesAndNewlines) + if model.saveServer(addresses: addresses, pairingToken: pairing.isEmpty ? nil : pairing) { + tokenText = "" + Task { await model.reload() } + } } } label: { Label("Save and Sync", systemImage: "arrow.triangle.2.circlepath") diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryTVViews.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryTVViews.swift index e87ba53..1b28e28 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryTVViews.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/LibraryTVViews.swift @@ -24,7 +24,7 @@ struct TVShowsTab: View { LibrarySearchBar(model: model) if shows.isEmpty { - EmptyLibraryState() + EmptyLibraryState(needsSignIn: model.needsSignIn) } else { LazyVGrid(columns: [GridItem(.adaptive(minimum: 150, maximum: 180), spacing: 16)], spacing: 18) { ForEach(shows) { show in diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ServerSignInViews.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ServerSignInViews.swift new file mode 100644 index 0000000..e7d270c --- /dev/null +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/ServerSignInViews.swift @@ -0,0 +1,207 @@ +import SwiftUI +import SonderAPI + +/// Account sign-in, shown when the server answers 401. +struct ServerSignInView: View { + @ObservedObject var model: SonderClientModel + var onDismiss: () -> Void + + @State private var username = "" + @State private var password = "" + @State private var isSigningIn = false + @State private var errorText: String? + @FocusState private var focusedField: Field? + + private enum Field { case username, password } + + var body: some View { + NavigationStack { + Form { + Section { + HStack(spacing: 12) { + Image(systemName: "server.rack") + .font(.title3.weight(.semibold)) + .foregroundStyle(SonderPalette.ironGrey) + .frame(width: 34, height: 34) + .background(SonderPalette.accentMuted, in: RoundedRectangle(cornerRadius: 8)) + VStack(alignment: .leading, spacing: 2) { + Text(model.discovery?.name ?? "TM Sonder") + .font(.headline) + Text(model.activeBaseURL.absoluteString) + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + .lineLimit(1) + .truncationMode(.middle) + } + } + ServerAnswerRow(model: model) + } + + if model.authStatus?.setupRequired == true { + Section { + Label("This server has no account yet. Open it in a browser to create the owner account, then sign in here.", + systemImage: "person.badge.plus") + .font(.callout) + } + } + + Section("Account") { + TextField("Username", text: $username) + .textContentType(.username) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .focused($focusedField, equals: .username) + .submitLabel(.next) + .onSubmit { focusedField = .password } + .accessibilityIdentifier("signin.username") + SecureField("Password", text: $password) + .textContentType(.password) + .focused($focusedField, equals: .password) + .submitLabel(.go) + .onSubmit(signIn) + .accessibilityIdentifier("signin.password") + } + + if let errorText { + Section { + Label(errorText, systemImage: "exclamationmark.triangle") + .font(.callout) + .foregroundStyle(.red) + } + } + + Section { + Button(action: signIn) { + HStack { + Spacer() + if isSigningIn { ProgressView().padding(.trailing, 6) } + Text("Sign In").fontWeight(.semibold) + Spacer() + } + } + .disabled(isSigningIn || username.trimmingCharacters(in: .whitespaces).isEmpty || password.isEmpty) + .accessibilityIdentifier("signin.submit") + } footer: { + Text("Use the same account as the Sonder website. You stay signed in on both the local and public address.") + } + } + .navigationTitle("Sign In") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Not Now", action: onDismiss) + } + } + .onAppear { + if username.isEmpty, let known = model.signedInUsername { username = known } + focusedField = username.isEmpty ? .username : .password + } + } + .interactiveDismissDisabled(isSigningIn) + } + + private func signIn() { + guard isSigningIn == false, username.isEmpty == false, password.isEmpty == false else { return } + isSigningIn = true + errorText = nil + Task { + defer { isSigningIn = false } + do { + try await model.signIn(username: username, password: password) + password = "" + } catch { + errorText = error.localizedDescription + } + } + } +} + +/// Shows whether the server answered the unauthenticated session check, and on which route. +struct ServerAnswerRow: View { + @ObservedObject var model: SonderClientModel + + var body: some View { + if model.isSelectingRoute { + Label("Checking the local address…", systemImage: "antenna.radiowaves.left.and.right") + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + } else if model.authStatus != nil { + Label("Server answered over the \(model.activeRoute.label.lowercased()). Sign-in required.", + systemImage: "checkmark.seal") + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + } else { + Label("Using the \(model.activeRoute.label.lowercased()) address.", systemImage: routeIcon) + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + } + } + + private var routeIcon: String { + model.activeRoute == .local ? "house" : "globe" + } +} + +/// The public + optional local address fields, shared by onboarding and Settings. +struct ServerAddressFields: View { + @Binding var publicText: String + @Binding var localText: String + @Binding var pairingToken: String + @State private var showsAdvanced = false + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Public address") + .font(.caption.weight(.semibold)) + .foregroundStyle(SonderPalette.textLight) + TextField("https://sonder.example.org", text: $publicText) + .textFieldStyle(.plain) + .keyboardType(.URL) + .textContentType(.URL) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .sonderInput() + .accessibilityIdentifier("server.publicURL") + + Text("Local address (optional)") + .font(.caption.weight(.semibold)) + .foregroundStyle(SonderPalette.textLight) + TextField("http://192.168.1.20:8096", text: $localText) + .textFieldStyle(.plain) + .keyboardType(.URL) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .sonderInput() + .accessibilityIdentifier("server.localURL") + Text("Used when your phone can reach it, for faster streaming at home. Otherwise the public address is used.") + .font(.caption) + .foregroundStyle(SonderPalette.textLight) + .fixedSize(horizontal: false, vertical: true) + + DisclosureGroup("Advanced", isExpanded: $showsAdvanced) { + SecureField("Pairing token (older servers only)", text: $pairingToken) + .textFieldStyle(.plain) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .sonderInput() + .padding(.top, 6) + } + .font(.subheadline) + .tint(SonderPalette.textLight) + } + } + + /// Parsed addresses, or nil with a message when the text is not usable. + static func addresses(publicText: String, localText: String) -> Result { + let publicTrimmed = publicText.trimmingCharacters(in: .whitespacesAndNewlines) + let localTrimmed = localText.trimmingCharacters(in: .whitespacesAndNewlines) + let publicURL = SonderServerAddresses.parse(publicTrimmed, defaultScheme: "https") + let localURL = SonderServerAddresses.parse(localTrimmed, defaultScheme: "http") + if publicTrimmed.isEmpty == false, publicURL == nil { return .failure(.init(message: "The public address is not a valid URL.")) } + if localTrimmed.isEmpty == false, localURL == nil { return .failure(.init(message: "The local address is not a valid URL.")) } + if publicURL == nil, localURL == nil { return .failure(.init(message: "Enter the server's public address.")) } + return .success(SonderServerAddresses(publicURL: publicURL, localURL: localURL)) + } + + struct AddressError: Error { var message: String } +} diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderClientAPI.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderClientAPI.swift index 27ad9cb..6af67ff 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderClientAPI.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderClientAPI.swift @@ -1,11 +1,25 @@ import AVFoundation import Combine import Foundation +import Network import SonderAPI @MainActor final class SonderClientModel: ObservableObject { + /// The server's stable identity (its public address, or the local one when + /// that is the only address). Everything stored per server is keyed by it. + /// Requests go to `activeBaseURL`. @Published var serverBaseURL: URL + /// Where requests go right now: the local address when it answered the + /// last probe, otherwise the public address. + @Published private(set) var activeBaseURL: URL + @Published private(set) var activeRoute: SonderServerRoute + @Published private(set) var addresses: SonderServerAddresses + @Published private(set) var isSelectingRoute = false + /// True when the server answered but wants an account sign-in. + @Published var needsSignIn = false + @Published private(set) var signedInUsername: String? + @Published private(set) var authStatus: SonderAuthSessionStatus? @Published var accessToken: String @Published var hasConfiguredServer: Bool @Published var items: [SonderMediaItem] = [] @@ -36,7 +50,15 @@ final class SonderClientModel: ObservableObject { let audiobookPlayer = SonderAudiobookPlayer() - private let defaultsURLKey = "sonder.serverBaseURL" + private static let legacyDefaultsURLKey = "sonder.serverBaseURL" + private static let defaultsPublicURLKey = "sonder.publicServerURL" + private static let defaultsLocalURLKey = "sonder.localServerURL" + private static let defaultsUsernamesKey = "sonder.signedInUsernameByServer" + private let accountClient = SonderAccountClient() + private let probe = SonderServerProbe() + private let networkWatcher = SonderNetworkWatcher() + private var routeNeedsSelection = true + private var networkChangeTask: Task? /// Legacy UserDefaults key; migrated into Keychain on first launch then cleared. private let legacyDefaultsTokenKey = "sonder.serverAccessToken" private let defaultsLibraryETagsKey = "sonder.libraryETagsByServer" @@ -50,31 +72,63 @@ final class SonderClientModel: ObservableObject { private var isFlushingProgress = false init() { - let stored = UserDefaults.standard.string(forKey: defaultsURLKey) - self.serverBaseURL = URL(string: stored ?? "http://127.0.0.1:8797")! - self.accessToken = Self.loadStoredAccessToken() - self.hasConfiguredServer = stored != nil - if stored != nil { progressQueue.adoptLegacy(for: serverBaseURL) } + let addresses = Self.loadStoredAddresses() + let identity = addresses.identityURL ?? URL(string: "http://127.0.0.1:8797")! + self.addresses = addresses + self.serverBaseURL = identity + self.activeBaseURL = addresses.publicURL ?? identity + self.activeRoute = addresses.publicURL == nil ? .local : .public + self.accessToken = Self.loadStoredAccessToken(for: addresses.identityURL) + self.hasConfiguredServer = addresses.isEmpty == false + self.signedInUsername = Self.storedUsername(for: identity) + if hasConfiguredServer { progressQueue.adoptLegacy(for: serverBaseURL) } self.pendingProgressCount = progressQueue.pending(for: serverBaseURL).count self.offlineDownloads = offlineDownloadStore.downloads(for: serverBaseURL) refreshOfflineDownloads() + networkWatcher.onChange = { [weak self] in + Task { @MainActor in self?.networkDidChange() } + } + networkWatcher.start() Task { await loadCachedLibrary() } } - private static func loadStoredAccessToken() -> String { - if let keychainToken = SonderKeychain.loadAccessToken(), keychainToken.isEmpty == false { + /// Older builds stored one server URL; it becomes the public address. + private static func loadStoredAddresses() -> SonderServerAddresses { + let defaults = UserDefaults.standard + func url(_ key: String) -> URL? { + defaults.string(forKey: key).flatMap(URL.init(string:)).flatMap(SonderServerAddresses.normalize) + } + return SonderServerAddresses( + publicURL: url(defaultsPublicURLKey) ?? url(legacyDefaultsURLKey), + localURL: url(defaultsLocalURLKey) + ) + } + + private static func loadStoredAccessToken(for server: URL?) -> String { + if let keychainToken = SonderKeychain.loadAccessToken(for: server), keychainToken.isEmpty == false { return keychainToken } // One-time migration from older builds that stored the token in UserDefaults. if let legacy = UserDefaults.standard.string(forKey: "sonder.serverAccessToken"), legacy.isEmpty == false { - SonderKeychain.saveAccessToken(legacy) + SonderKeychain.saveAccessToken(legacy, for: server) UserDefaults.standard.removeObject(forKey: "sonder.serverAccessToken") return legacy } return "" } + private static func storedUsername(for server: URL) -> String? { + (UserDefaults.standard.dictionary(forKey: defaultsUsernamesKey) as? [String: String])?[server.absoluteString] + } + + private func storeUsername(_ username: String?) { + var values = UserDefaults.standard.dictionary(forKey: Self.defaultsUsernamesKey) as? [String: String] ?? [:] + values[serverBaseURL.absoluteString] = username + UserDefaults.standard.set(values, forKey: Self.defaultsUsernamesKey) + signedInUsername = username + } + func loadIfNeeded() async { guard didLoadOnce == false else { return } didLoadOnce = true @@ -89,35 +143,141 @@ final class SonderClientModel: ObservableObject { errorMessage = nil defer { isLoading = false } + if routeNeedsSelection { await selectRoute() } + do { + try await sync() + } catch where activeRoute == .local && Self.isTransportError(error) && addresses.publicURL != nil { + // The local address answered the probe but not the sync (for + // example, the phone just left home Wi-Fi). Fall back to public now + // and probe again on the next refresh. + logEvent("Local address unreachable", detail: error.localizedDescription) + if let publicURL = addresses.publicURL { setActive(SonderEndpointChoice(url: publicURL, route: .public)) } + routeNeedsSelection = true + do { try await sync() } catch { await handleSyncFailure(error) } + } catch { + await handleSyncFailure(error) + } + } + + private func sync() async throws { async let discoveryResponse = fetchDiscovery() async let healthResponse = fetchHealth() async let libraryResponse = fetchLibrary() + async let sessionResponse = accountClient.sessionStatus(baseURL: activeBaseURL, token: accessToken) - do { - if let response = try await libraryResponse { - apply(response, cached: false, date: Date()) - saveCachedLibrary(response) - } else { - // 304 Not Modified — keep in-memory catalog, refresh connection metadata. - isShowingCachedData = false - lastSyncedAt = Date() - } - discovery = try? await discoveryResponse - health = try? await healthResponse - connectionMode = resolvedConnectionMode() - await flushPendingProgress() - } catch { - if isUnauthorized(error) { - connectionMode = .unauthorized - } else { - connectionMode = items.isEmpty ? .offline : .stale + if let response = try await libraryResponse { + apply(response, cached: false, date: Date()) + saveCachedLibrary(response) + } else { + // 304 Not Modified — keep in-memory catalog, refresh connection metadata. + isShowingCachedData = false + lastSyncedAt = Date() + } + needsSignIn = false + discovery = try? await discoveryResponse + health = try? await healthResponse + if let status = try? await sessionResponse { + authStatus = status + if let username = status.username, username.isEmpty == false, username != signedInUsername { + storeUsername(username) } - isShowingCachedData = items.isEmpty == false - errorMessage = error.localizedDescription - logEvent("Sync failed", detail: error.localizedDescription) + } + connectionMode = resolvedConnectionMode() + await flushPendingProgress() + } + + private func handleSyncFailure(_ error: Error) async { + if isUnauthorized(error) { + connectionMode = .unauthorized + // 403 means LAN access is off on the host; signing in will not help. + needsSignIn = (error as? HTTPStatusError)?.statusCode == 401 + // Unauthenticated and always reachable: shows that the server answered. + authStatus = try? await accountClient.sessionStatus(baseURL: activeBaseURL, token: "") + } else { + connectionMode = items.isEmpty ? .offline : .stale + } + isShowingCachedData = items.isEmpty == false + errorMessage = error.localizedDescription + logEvent("Sync failed", detail: "\(activeBaseURL.absoluteString): \(error.localizedDescription)") + } + + // MARK: - Local / public route + + /// Probes the local address (short timeout) and falls back to public. + func selectRoute() async { + routeNeedsSelection = false + let addresses = self.addresses + guard addresses.localURL != nil else { + if let publicURL = addresses.publicURL { setActive(SonderEndpointChoice(url: publicURL, route: .public)) } + return + } + isSelectingRoute = true + defer { isSelectingRoute = false } + let probe = self.probe + let choice = await SonderEndpointSelector.choose(addresses) { await probe.isSonderServer($0) } + guard let choice, addresses == self.addresses else { return } + setActive(choice) + } + + private func setActive(_ choice: SonderEndpointChoice) { + let changed = choice.url != activeBaseURL || choice.route != activeRoute + activeBaseURL = choice.url + activeRoute = choice.route + if changed { logEvent("Using \(choice.route.label.lowercased()) address", detail: choice.url.absoluteString) } + } + + private func networkDidChange() { + routeNeedsSelection = true + guard hasConfiguredServer, addresses.localURL != nil else { return } + networkChangeTask?.cancel() + networkChangeTask = Task { [weak self] in + // Let the new network settle (DHCP, DNS) before probing. + try? await Task.sleep(for: .seconds(1)) + guard let self, Task.isCancelled == false, self.isLoading == false else { return } + let before = self.activeBaseURL + await self.selectRoute() + if self.activeBaseURL != before { await self.reload() } + } + } + + /// True for a URL on either configured address, so stream and artwork URLs + /// keep their credentials whichever route produced them. + func isServerURL(_ url: URL) -> Bool { + [activeBaseURL, addresses.publicURL, addresses.localURL].compactMap { $0 }.contains { + $0.scheme == url.scheme && $0.host == url.host && $0.port == url.port } } + private static func isTransportError(_ error: Error) -> Bool { + (error as NSError).domain == NSURLErrorDomain + } + + // MARK: - Account sign-in + + func signIn(username: String, password: String) async throws { + if routeNeedsSelection { await selectRoute() } + let result = try await accountClient.signIn(baseURL: activeBaseURL, username: username, password: password) + accessToken = result.token + SonderKeychain.saveAccessToken(result.token, for: serverBaseURL) + storeUsername(result.username) + needsSignIn = false + errorMessage = nil + logEvent("Signed in", detail: "\(result.username) via \(activeRoute.label.lowercased())") + await reload() + } + + func signOut() async { + let token = accessToken + if token.isEmpty == false { await accountClient.signOut(baseURL: activeBaseURL, token: token) } + accessToken = "" + SonderKeychain.deleteAccessToken(for: serverBaseURL) + storeUsername(nil) + authStatus = nil + connectionMode = .unauthorized + needsSignIn = true + logEvent("Signed out", detail: serverBaseURL.absoluteString) + } + var filteredItems: [SonderMediaItem] { selectedKind == .all ? filteredItemsByKind[.all] ?? [] : filteredItemsByKind[selectedKind] ?? [] } @@ -137,7 +297,7 @@ final class SonderClientModel: ObservableObject { } func streamURL(for item: SonderMediaItem) -> URL { - serverBaseURL.appendingPathComponent("stream").appendingPathComponent(item.id.uuidString.lowercased()) + activeBaseURL.appendingPathComponent("stream").appendingPathComponent(item.id.uuidString.lowercased()) } func audiobookChapters(for item: SonderMediaItem) async throws -> [SonderAudiobookChapter] { @@ -148,7 +308,7 @@ final class SonderClientModel: ObservableObject { let chapters = try? JSONDecoder.sonder.decode([SonderAudiobookChapter].self, from: data) { return chapters } - let url = serverBaseURL + let url = activeBaseURL .appendingPathComponent("api/audiobooks") .appendingPathComponent(item.id.uuidString.lowercased()) .appendingPathComponent("chapters") @@ -222,6 +382,7 @@ final class SonderClientModel: ObservableObject { guard supportsOfflineDownload(for: item), localMediaURL(for: item) == nil, downloadingItemIDs.contains(item.id) == false else { return } downloadingItemIDs.insert(item.id) let downloadServerURL = serverBaseURL + let requestBaseURL = activeBaseURL offlineDownloadProgress[item.id] = SonderOfflineDownloadProgress(bytesWritten: 0, bytesExpected: 0, bytesPerSecond: 0, isPaused: false) if supportsPreparedVideo(item) { persistVideoPreparation(item, serverURL: downloadServerURL, remove: false) @@ -229,7 +390,7 @@ final class SonderClientModel: ObservableObject { preparationTasks[item.id] = Task { [weak self] in guard let self else { return } do { - let url = try await self.prepareVideoForOffline(item, serverURL: downloadServerURL) + let url = try await self.prepareVideoForOffline(item, serverURL: requestBaseURL) try Task.checkCancellation() guard self.serverBaseURL == downloadServerURL else { throw CancellationError() } self.preparingOfflineItemIDs.remove(item.id) @@ -248,8 +409,7 @@ final class SonderClientModel: ObservableObject { } let request = authorizedRequest(for: streamURL(for: item), timeout: 60) if item.kind == .audiobook { _ = try? await audiobookChapters(for: item) } - if let coverURL = artworkURL(for: item), !coverURL.isFileURL, - coverURL.host == downloadServerURL.host, coverURL.port == downloadServerURL.port { + if let coverURL = artworkURL(for: item), !coverURL.isFileURL, isServerURL(coverURL) { let poster = offlineDownloadStore.posterURL(itemID: item.id, serverURL: downloadServerURL) if let (data, response) = try? await URLSession.shared.data(for: authorizedRequest(for: coverURL)), let http = response as? HTTPURLResponse, http.statusCode == 200, data.count <= 20 * 1024 * 1024 { @@ -351,13 +511,13 @@ final class SonderClientModel: ObservableObject { onPreparing: @MainActor () -> Void = {}) async throws -> URL { if let local = localMediaURL(for: item) { return local } if supportsPreparedVideo(item) { - if let status = try? await videoPreparation(item, serverURL: serverBaseURL), - let url = preparedPlaylistURL(status, serverURL: serverBaseURL) { return url } + if let status = try? await videoPreparation(item, serverURL: activeBaseURL), + let url = preparedPlaylistURL(status, serverURL: activeBaseURL) { return url } // A raw MKV/WebM URL is not an AVPlayer fallback. Wait for a complete // VOD timeline so native saved-position resume and seeking work. if !item.format.isPlayableInAVPlayer || URLComponents(url: fallback, resolvingAgainstBaseURL: true)?.queryItems?.contains(where: { $0.name == "transcode" && $0.value == "1" }) == true { onPreparing() - return try await prepareVideoForOffline(item, serverURL: serverBaseURL) + return try await prepareVideoForOffline(item, serverURL: activeBaseURL) } } if isVideo(item), !item.format.isPlayableInAVPlayer { @@ -454,9 +614,7 @@ final class SonderClientModel: ObservableObject { } func streamAsset(for url: URL) -> AVURLAsset { - guard url.scheme == serverBaseURL.scheme, url.host == serverBaseURL.host, url.port == serverBaseURL.port else { - return AVURLAsset(url: url) - } + guard isServerURL(url) else { return AVURLAsset(url: url) } let token = accessToken.trimmingCharacters(in: .whitespacesAndNewlines) var components = URLComponents(url: url, resolvingAgainstBaseURL: true) if !token.isEmpty { @@ -473,7 +631,7 @@ final class SonderClientModel: ObservableObject { if let absoluteURL = URL(string: rawValue), absoluteURL.scheme != nil { return absoluteURL } - return URL(string: rawValue, relativeTo: serverBaseURL)?.absoluteURL + return URL(string: rawValue, relativeTo: activeBaseURL)?.absoluteURL } func artworkURL(for item: SonderMediaItem) -> URL? { @@ -485,7 +643,7 @@ final class SonderClientModel: ObservableObject { if let absoluteURL = URL(string: rawURL), absoluteURL.scheme != nil { return absoluteURL } - return serverBaseURL.appendingPathComponent(rawURL.trimmingCharacters(in: CharacterSet(charactersIn: "/"))) + return activeBaseURL.appendingPathComponent(rawURL.trimmingCharacters(in: CharacterSet(charactersIn: "/"))) } func progress(for item: SonderMediaItem) -> SonderProgress { @@ -609,7 +767,14 @@ final class SonderClientModel: ObservableObject { } func connect(to endpoint: SonderServerEndpoint) async { - saveServer(baseURL: endpoint.url, accessToken: accessToken) + // A discovered LAN server is the local route when a public address is + // already set (and is not a simulator loopback leftover). + let publicHost = addresses.publicURL?.host?.lowercased() + if let publicHost, ["localhost", "127.0.0.1", "::1"].contains(publicHost) == false { + saveServer(addresses: SonderServerAddresses(publicURL: addresses.publicURL, localURL: endpoint.url), pairingToken: nil) + } else { + saveServer(addresses: SonderServerAddresses(publicURL: endpoint.url, localURL: addresses.localURL), pairingToken: nil) + } discovery = endpoint.discovery connectionMode = endpoint.mode await reload() @@ -627,18 +792,47 @@ final class SonderClientModel: ObservableObject { @discardableResult func saveServer(baseURL: URL, accessToken: String) -> Bool { - guard let normalizedURL = Self.normalizedServerURL(baseURL) else { - errorMessage = "Enter a complete http:// or https:// server URL." + saveServer(addresses: SonderServerAddresses(publicURL: baseURL, localURL: addresses.localURL), pairingToken: accessToken) + } + + /// Saves the public and optional local address. `pairingToken` nil keeps + /// the stored credential for this server; a string replaces it (empty clears it). + @discardableResult + func saveServer(addresses newAddresses: SonderServerAddresses, pairingToken: String?) -> Bool { + let normalized = SonderServerAddresses( + publicURL: newAddresses.publicURL.flatMap(SonderServerAddresses.normalize), + localURL: newAddresses.localURL.flatMap(SonderServerAddresses.normalize) + ) + guard (newAddresses.publicURL == nil || normalized.publicURL != nil), + (newAddresses.localURL == nil || normalized.localURL != nil), + let normalizedURL = normalized.identityURL else { + errorMessage = "Enter a complete http:// or https:// server address." return false } let serverChanged = normalizedURL != serverBaseURL if serverChanged { audiobookPlayer.stop() } + addresses = normalized serverBaseURL = normalizedURL - self.accessToken = accessToken.trimmingCharacters(in: .whitespacesAndNewlines) + activeBaseURL = normalized.publicURL ?? normalizedURL + activeRoute = normalized.publicURL == nil ? .local : .public + routeNeedsSelection = true + if let pairingToken { + self.accessToken = pairingToken.trimmingCharacters(in: .whitespacesAndNewlines) + SonderKeychain.saveAccessToken(self.accessToken, for: normalizedURL) + } else if serverChanged { + self.accessToken = Self.loadStoredAccessToken(for: normalizedURL) + } + if serverChanged { + signedInUsername = Self.storedUsername(for: normalizedURL) + authStatus = nil + needsSignIn = false + } hasConfiguredServer = true - UserDefaults.standard.set(normalizedURL.absoluteString, forKey: defaultsURLKey) - UserDefaults.standard.removeObject(forKey: legacyDefaultsTokenKey) - SonderKeychain.saveAccessToken(self.accessToken) + let defaults = UserDefaults.standard + defaults.set(normalized.publicURL?.absoluteString, forKey: Self.defaultsPublicURLKey) + defaults.set(normalized.localURL?.absoluteString, forKey: Self.defaultsLocalURLKey) + defaults.removeObject(forKey: Self.legacyDefaultsURLKey) + defaults.removeObject(forKey: legacyDefaultsTokenKey) offlineDownloads = offlineDownloadStore.downloads(for: normalizedURL) if serverChanged { // Validators are meaningful only for the server that issued them. @@ -709,20 +903,17 @@ final class SonderClientModel: ObservableObject { } private func resolvedConnectionMode() -> SonderConnectionMode { - if serverBaseURL.host == "127.0.0.1" || serverBaseURL.host == "localhost" { + if activeBaseURL.host == "127.0.0.1" || activeBaseURL.host == "localhost" { return .local } - if serverBaseURL.host?.localizedCaseInsensitiveContains("ts.net") == true { + if activeBaseURL.host?.localizedCaseInsensitiveContains("ts.net") == true { return .tailscale } - if health?.allowLAN == true || serverSettings?.allowLAN == true || discovery?.allowLAN == true { - return .lan - } - return .manual + return activeRoute == .local ? .lan : .manual } private func fetchDiscovery() async throws -> SonderDiscoveryResponse { - let request = authorizedRequest(for: serverBaseURL.appendingPathComponent("api/discovery")) + let request = authorizedRequest(for: activeBaseURL.appendingPathComponent("api/discovery")) let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse, 200..<300 ~= http.statusCode else { throw URLError(.badServerResponse) @@ -731,7 +922,7 @@ final class SonderClientModel: ObservableObject { } private func fetchHealth() async throws -> SonderHealthResponse { - let request = authorizedRequest(for: serverBaseURL.appendingPathComponent("api/health")) + let request = authorizedRequest(for: activeBaseURL.appendingPathComponent("api/health")) let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse, 200..<300 ~= http.statusCode else { throw URLError(.badServerResponse) @@ -741,7 +932,7 @@ final class SonderClientModel: ObservableObject { /// Returns a fresh library payload, or `nil` when the server responds `304 Not Modified`. private func fetchLibrary() async throws -> SonderLibraryResponse? { - var request = authorizedRequest(for: serverBaseURL.appendingPathComponent("api/library"), timeout: 20) + var request = authorizedRequest(for: activeBaseURL.appendingPathComponent("api/library"), timeout: 20) if let libraryETag, libraryETag.isEmpty == false { request.setValue(libraryETag, forHTTPHeaderField: "If-None-Match") } @@ -763,7 +954,7 @@ final class SonderClientModel: ObservableObject { } private func postProgress(itemID: UUID, seconds: Double, duration: Double) async throws { - let url = serverBaseURL + let url = activeBaseURL .appendingPathComponent("api/progress") .appendingPathComponent(itemID.uuidString.lowercased()) var request = authorizedRequest(for: url) @@ -786,7 +977,7 @@ final class SonderClientModel: ObservableObject { subtitlesEnabled: Bool?, updatedAt: Date? = nil ) async throws -> SonderPlaybackResponse { - let url = serverBaseURL + let url = activeBaseURL .appendingPathComponent("api/playback") .appendingPathComponent(itemID.uuidString.lowercased()) var request = authorizedRequest(for: url) @@ -816,7 +1007,7 @@ final class SonderClientModel: ObservableObject { subtitleTrackID: String?, subtitlesEnabled: Bool? ) async throws -> SonderPlaybackResponse { - let url = serverBaseURL + let url = activeBaseURL .appendingPathComponent("api/playback") .appendingPathComponent(itemID.uuidString.lowercased()) .appendingPathComponent("refresh-tracks") @@ -846,6 +1037,9 @@ final class SonderClientModel: ObservableObject { private func authorizedRequest(for url: URL, timeout: TimeInterval = 5) -> URLRequest { var request = URLRequest(url: url, timeoutInterval: timeout) request.cachePolicy = .reloadIgnoringLocalCacheData + // The server reads a session cookie before the Authorization header; + // never let a stale shared cookie shadow the stored Bearer token. + request.httpShouldHandleCookies = false let token = accessToken.trimmingCharacters(in: .whitespacesAndNewlines) if token.isEmpty == false { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") @@ -917,18 +1111,6 @@ final class SonderClientModel: ObservableObject { UserDefaults.standard.set(values, forKey: defaultsLibraryETagsKey) } - private static func normalizedServerURL(_ url: URL) -> URL? { - guard let scheme = url.scheme?.lowercased(), - ["http", "https"].contains(scheme), - url.host?.isEmpty == false else { return nil } - var components = URLComponents(url: url, resolvingAgainstBaseURL: false) - let path = components?.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? "" - components?.path = path - components?.query = nil - components?.fragment = nil - return components?.url - } - private func isUnauthorized(_ error: Error) -> Bool { (error as? HTTPStatusError)?.statusCode == 401 || (error as? HTTPStatusError)?.statusCode == 403 } @@ -996,13 +1178,43 @@ struct SonderServerEndpoint: Identifiable, Hashable { var discovery: SonderDiscoveryResponse? } +/// Reports network path changes (Wi-Fi joined or left, cellular, VPN) so the +/// app can re-probe the local address. The first update after start is the +/// current path, not a change, and is ignored. +final class SonderNetworkWatcher: @unchecked Sendable { + var onChange: (@Sendable () -> Void)? + private let monitor = NWPathMonitor() + private let queue = DispatchQueue(label: "com.techmore.tmsonder.network-watcher") + private var lastSignature: String? + + func start() { + monitor.pathUpdateHandler = { [weak self] path in + guard let self else { return } + let signature = Self.signature(of: path) + defer { self.lastSignature = signature } + guard let last = self.lastSignature, last != signature else { return } + self.onChange?() + } + monitor.start(queue: queue) + } + + private static func signature(of path: NWPath) -> String { + let interfaces = path.availableInterfaces.map { "\($0.type)-\($0.name)" }.joined(separator: ",") + return "\(path.status)|\(interfaces)|\(path.gateways.map { "\($0)" }.joined(separator: ","))" + } + + deinit { monitor.cancel() } +} + struct HTTPStatusError: LocalizedError { var statusCode: Int var errorDescription: String? { switch statusCode { - case 401, 403: - return "This server is restricted. Add a token in Server settings or disable restrictions on the host." + case 401: + return "Sign in to this server to load your library." + case 403: + return "This server refused the connection. Check that LAN or remote access is enabled on the host." default: return "Server returned HTTP \(statusCode)." } diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderKeychain.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderKeychain.swift index 01e7485..53e7f28 100644 --- a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderKeychain.swift +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderKeychain.swift @@ -1,46 +1,65 @@ import Foundation import Security -/// Minimal Keychain helper for the LAN pairing token. -/// Tokens must not live in UserDefaults (backups / device sync). +/// Minimal Keychain helper for server credentials (account session or legacy +/// pairing token). Tokens must not live in UserDefaults (backups / device sync). +/// Each server identity has its own entry; older builds kept one global entry, +/// which is adopted by the first server that asks for it. enum SonderKeychain { private static let service = "com.tmsonder.client" - private static let accessTokenAccount = "serverAccessToken" + private static let legacyAccount = "serverAccessToken" - static func loadAccessToken() -> String? { - let query: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: service, - kSecAttrAccount as String: accessTokenAccount, - kSecReturnData as String: true, - kSecMatchLimit as String: kSecMatchLimitOne - ] - var item: CFTypeRef? - let status = SecItemCopyMatching(query as CFDictionary, &item) - guard status == errSecSuccess, let data = item as? Data else { return nil } - return String(data: data, encoding: .utf8) + static func account(for server: URL?) -> String { + guard let server else { return legacyAccount } + return "\(legacyAccount)|\(server.absoluteString)" } - static func saveAccessToken(_ token: String) { + static func loadAccessToken(for server: URL?) -> String? { + if let token = load(account: account(for: server)), token.isEmpty == false { return token } + guard server != nil, let legacy = load(account: legacyAccount), legacy.isEmpty == false else { return nil } + saveAccessToken(legacy, for: server) + delete(account: legacyAccount) + return legacy + } + + static func saveAccessToken(_ token: String, for server: URL?) { let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines) - deleteAccessToken() + let account = account(for: server) + delete(account: account) guard trimmed.isEmpty == false else { return } - let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, - kSecAttrAccount as String: accessTokenAccount, + kSecAttrAccount as String: account, kSecValueData as String: Data(trimmed.utf8), kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly ] SecItemAdd(query as CFDictionary, nil) } - static func deleteAccessToken() { + static func deleteAccessToken(for server: URL?) { + delete(account: account(for: server)) + } + + private static func load(account: String) -> String? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + guard status == errSecSuccess, let data = item as? Data else { return nil } + return String(data: data, encoding: .utf8) + } + + private static func delete(account: String) { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, - kSecAttrAccount as String: accessTokenAccount + kSecAttrAccount as String: account ] SecItemDelete(query as CFDictionary) } diff --git a/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderServerConnection.swift b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderServerConnection.swift new file mode 100644 index 0000000..6ef565b --- /dev/null +++ b/IOS_Client_Xcode/TM_Sonder_Client/TM_Sonder_Client/SonderServerConnection.swift @@ -0,0 +1,259 @@ +import Foundation + +/// The addresses a person gives for one Sonder server: a public address that +/// works anywhere, and an optional local address used when it is reachable. +struct SonderServerAddresses: Codable, Equatable, Sendable { + var publicURL: URL? + var localURL: URL? + + /// Stable identity for everything stored per server (sign-in token, offline + /// copies, queued progress, caches). It does not change when the app + /// switches between the local and public route to the same server. + var identityURL: URL? { publicURL ?? localURL } + + var isEmpty: Bool { publicURL == nil && localURL == nil } + + /// Parses what someone typed into an address field. Text without a scheme + /// gets `defaultScheme`, so `sonder.example.org` works as well as a full URL. + static func parse(_ text: String, defaultScheme: String) -> URL? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.isEmpty == false else { return nil } + let candidate = trimmed.contains("://") ? trimmed : "\(defaultScheme)://\(trimmed)" + guard let url = URL(string: candidate) else { return nil } + return normalize(url) + } + + /// Accepts only complete http(s) URLs and drops trailing slashes, query and fragment. + static func normalize(_ url: URL) -> URL? { + guard let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme), + let host = url.host, host.isEmpty == false, + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } + components.scheme = scheme + components.host = host.lowercased() + components.path = components.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + if components.path.isEmpty == false { components.path = "/" + components.path } + components.query = nil + components.fragment = nil + components.user = nil + components.password = nil + return components.url + } +} + +enum SonderServerRoute: String, Codable, Sendable { + case local + case `public` + + var label: String { + switch self { + case .local: "Local network" + case .public: "Public internet" + } + } +} + +struct SonderEndpointChoice: Equatable, Sendable { + var url: URL + var route: SonderServerRoute +} + +enum SonderEndpointSelector { + /// Prefers the local address when it answers as a Sonder server, otherwise + /// uses the public address. Only the local address is probed: the public + /// address is the fallback, and its errors surface through normal requests. + static func choose( + _ addresses: SonderServerAddresses, + isReachable: @Sendable (URL) async -> Bool + ) async -> SonderEndpointChoice? { + if let local = addresses.localURL, local != addresses.publicURL, await isReachable(local) { + return SonderEndpointChoice(url: local, route: .local) + } + if let publicURL = addresses.publicURL { + return SonderEndpointChoice(url: publicURL, route: .public) + } + if let local = addresses.localURL { + // Local is the only address. Use it so requests report the real error. + return SonderEndpointChoice(url: local, route: .local) + } + return nil + } +} + +/// A quick check that a base URL is a reachable Sonder server. It asks the +/// unauthenticated `/api/auth/session` route and requires Sonder's identity +/// header, so a captive portal or another web server does not count. +struct SonderServerProbe: Sendable { + static let identityHeader = "X-Sonder-Server" + static let identityValue = "tm-sonder" + + var session: URLSession + var timeout: TimeInterval + + init(session: URLSession? = nil, timeout: TimeInterval = 1.5) { + self.timeout = timeout + if let session { + self.session = session + } else { + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = timeout + configuration.timeoutIntervalForResource = timeout + 0.5 + configuration.waitsForConnectivity = false + configuration.httpShouldSetCookies = false + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + self.session = URLSession(configuration: configuration) + } + } + + func isSonderServer(_ baseURL: URL) async -> Bool { + var request = URLRequest(url: baseURL.appendingPathComponent("api/auth/session"), + cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) + request.httpShouldHandleCookies = false + request.setValue("application/json", forHTTPHeaderField: "Accept") + guard let (_, response) = try? await session.data(for: request), + let http = response as? HTTPURLResponse else { return false } + return http.value(forHTTPHeaderField: Self.identityHeader)?.lowercased() == Self.identityValue + } +} + +/// `GET /api/auth/session`: whether the server needs first-time setup and +/// whether the credential sent with the request is accepted. +struct SonderAuthSessionStatus: Decodable, Equatable, Sendable { + var setupRequired: Bool + var authenticated: Bool + var username: String? +} + +enum SonderSignInError: LocalizedError, Equatable { + case invalidCredentials + case throttled(retryAfterSeconds: Int?) + case setupRequired + case noSessionIssued + case notSonderServer + case server(statusCode: Int) + + var errorDescription: String? { + switch self { + case .invalidCredentials: + "Incorrect username or password." + case let .throttled(seconds): + if let seconds, seconds > 0 { + "Too many sign-in attempts. Try again in \(max(1, seconds / 60)) minute\(seconds >= 120 ? "s" : "")." + } else { + "Too many sign-in attempts. Try again later." + } + case .setupRequired: + "This server has no account yet. Create the owner account in a browser first." + case .noSessionIssued: + "The server accepted the sign-in but did not return a session." + case .notSonderServer: + "That address did not answer as a TM Sonder server." + case let .server(statusCode): + "Sign-in failed: the server returned HTTP \(statusCode)." + } + } +} + +struct SonderSignInResult: Equatable, Sendable { + var token: String + var username: String + var expiresAt: Date? +} + +/// Account sign-in for the native client. `POST /api/auth/login` answers with +/// an HTTP-only `sonder_session` cookie; the same value is accepted as a +/// Bearer token, which works on both the local and public address. +struct SonderAccountClient: Sendable { + static let sessionCookieName = "sonder_session" + + var session: URLSession = .shared + + func signIn(baseURL: URL, username: String, password: String) async throws -> SonderSignInResult { + let trimmedUser = username.trimmingCharacters(in: .whitespacesAndNewlines) + let url = baseURL.appendingPathComponent("api/auth/login") + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) + request.httpMethod = "POST" + // Keep the cookie out of the shared cookie store: the server reads a + // cookie before the Authorization header, so a stale cookie for one + // address would hide a valid Bearer token. + request.httpShouldHandleCookies = false + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.httpBody = try JSONEncoder().encode(["username": trimmedUser, "password": password]) + + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { throw SonderSignInError.server(statusCode: -1) } + switch http.statusCode { + case 200..<300: + break + case 401: + throw http.value(forHTTPHeaderField: SonderServerProbe.identityHeader) == nil + ? SonderSignInError.notSonderServer : SonderSignInError.invalidCredentials + case 404: + throw SonderSignInError.notSonderServer + case 409: + throw SonderSignInError.setupRequired + case 429: + throw SonderSignInError.throttled(retryAfterSeconds: http.value(forHTTPHeaderField: "Retry-After").flatMap(Int.init)) + default: + throw SonderSignInError.server(statusCode: http.statusCode) + } + guard let token = Self.sessionToken(from: http, url: url) else { throw SonderSignInError.noSessionIssued } + let body = try? JSONDecoder().decode(LoginResponse.self, from: data) + let username = body?.username.flatMap { $0.isEmpty ? nil : $0 } ?? trimmedUser + return SonderSignInResult(token: token, username: username, expiresAt: Self.parseServerDate(body?.expiresAt)) + } + + func sessionStatus(baseURL: URL, token: String) async throws -> SonderAuthSessionStatus { + var request = URLRequest(url: baseURL.appendingPathComponent("api/auth/session"), + cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 8) + request.httpShouldHandleCookies = false + request.setValue("application/json", forHTTPHeaderField: "Accept") + let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty == false { request.setValue("Bearer \(trimmed)", forHTTPHeaderField: "Authorization") } + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse, 200..<300 ~= http.statusCode else { + throw SonderSignInError.server(statusCode: (response as? HTTPURLResponse)?.statusCode ?? -1) + } + return try JSONDecoder().decode(SonderAuthSessionStatus.self, from: data) + } + + /// Best effort: revoke the session on the server. + func signOut(baseURL: URL, token: String) async { + var request = URLRequest(url: baseURL.appendingPathComponent("api/auth/logout"), timeoutInterval: 8) + request.httpMethod = "POST" + request.httpShouldHandleCookies = false + request.setValue("\(Self.sessionCookieName)=\(token)", forHTTPHeaderField: "Cookie") + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + _ = try? await session.data(for: request) + } + + static func sessionToken(from response: HTTPURLResponse, url: URL) -> String? { + var headers: [String: String] = [:] + for (key, value) in response.allHeaderFields { + if let key = key as? String, let value = value as? String { headers[key] = value } + } + return HTTPCookie.cookies(withResponseHeaderFields: headers, for: url) + .first { $0.name == sessionCookieName && $0.value.isEmpty == false }?.value + } + + private struct LoginResponse: Decodable { + var username: String? + var expiresAt: String? + } +} + +extension SonderAccountClient { + /// Go encodes times as RFC 3339 with up to nine fractional digits, which + /// ISO8601DateFormatter rejects; trim to milliseconds first. + static func parseServerDate(_ raw: String?) -> Date? { + guard var raw, raw.isEmpty == false else { return nil } + if let dot = raw.firstIndex(of: "."), + let zone = raw[dot...].firstIndex(where: { $0 == "Z" || $0 == "+" || $0 == "-" }) { + let digits = raw[raw.index(after: dot)..