Linux + iPhone Continuity / iMessage / SMS
refactor into shared framework
Zack Bartel1a5209141d65
diff --git a/apple/Tether/ContentView.swift b/apple/Tether/ContentView.swiftindex c9fe396..9306354 100644--- a/apple/Tether/ContentView.swift+++ b/apple/Tether/ContentView.swift@@ -6,6 +6,7 @@//import SwiftUI+import TetherFrameworkstruct ContentView: View {@Environment(TetherViewModel.self) private var viewModeldiff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swiftindex c780544..e8e4fa7 100644--- a/apple/Tether/ViewModels/TetherViewModel.swift+++ b/apple/Tether/ViewModels/TetherViewModel.swift@@ -10,6 +10,7 @@ import Foundationimport SwiftUIimport UniformTypeIdentifiersimport UIKit+import TetherFramework// High-level app state.enum AppConnectionState: Equatable {@@ -195,6 +196,8 @@ final class TetherViewModel {manualDisconnect = falseappState = .connectingconnectedDeviceName = host.name+ // Persist the service name so the Share Extension can connect without discovery.+ ShareSender.persistLastServiceName(host.name)connection.connect(to: host.endpoint, identity: identity)}@@ -257,6 +260,12 @@ final class TetherViewModel {connection.send(.clipboardGet())}+ // Send an OTP code to the tetherd vault (`new_otp`).+ // The daemon stores it so the browser extension can retrieve it via `request_otp`.+ func sendNewOtp(_ code: String, source: String = "iPhone") {+ connection.send(.newOtp(code, source: source))+ }+// Copy a clipboard entry to the iOS pasteboard.func copyToLocalClipboard(_ text: String) {#if canImport(UIKit)diff --git a/apple/Tether/Views/Components/ConnectionStatusView.swift b/apple/Tether/Views/Components/ConnectionStatusView.swiftindex f306eee..6d8d084 100644--- a/apple/Tether/Views/Components/ConnectionStatusView.swift+++ b/apple/Tether/Views/Components/ConnectionStatusView.swift@@ -6,6 +6,7 @@//import SwiftUI+import TetherFrameworkstruct ConnectionStatusView: View {let state: AppConnectionStatediff --git a/apple/Tether/Views/DashboardView.swift b/apple/Tether/Views/DashboardView.swiftindex 185474d..74320d0 100644--- a/apple/Tether/Views/DashboardView.swift+++ b/apple/Tether/Views/DashboardView.swift@@ -6,6 +6,7 @@//import SwiftUI+import TetherFrameworkstruct DashboardView: View {@Environment(TetherViewModel.self) private var viewModeldiff --git a/apple/Tether/Views/PairingView.swift b/apple/Tether/Views/PairingView.swiftindex ec56383..de6cd1a 100644--- a/apple/Tether/Views/PairingView.swift+++ b/apple/Tether/Views/PairingView.swift@@ -6,6 +6,7 @@//import SwiftUI+import TetherFrameworkstruct PairingView: View {@Environment(TetherViewModel.self) private var viewModeldiff --git a/apple/Tether/Views/SettingsView.swift b/apple/Tether/Views/SettingsView.swiftindex 9a6525a..9327613 100644--- a/apple/Tether/Views/SettingsView.swift+++ b/apple/Tether/Views/SettingsView.swift@@ -6,6 +6,7 @@//import SwiftUI+import TetherFrameworkstruct SettingsView: View {@Environment(TetherViewModel.self) private var viewModeldiff --git a/apple/TetherFramework/Package.swift b/apple/TetherFramework/Package.swiftnew file mode 100644index 0000000..d1b6882--- /dev/null+++ b/apple/TetherFramework/Package.swift@@ -0,0 +1,30 @@+// swift-tools-version: 5.9+//+// Package.swift+// TetherFramework+//+// Shared library used by both the Tether main app and the TetherShareExtension.+// Contains all protocol, networking, and certificate management code.+//++import PackageDescription++let package = Package(+ name: "TetherFramework",+ platforms: [+ .iOS(.v17),+ .macOS(.v14),+ ],+ products: [+ .library(+ name: "TetherFramework",+ targets: ["TetherFramework"]+ ),+ ],+ targets: [+ .target(+ name: "TetherFramework",+ path: "Sources/TetherFramework"+ ),+ ]+)diff --git a/apple/Tether/Services/BonjourDiscovery.swift b/apple/TetherFramework/Sources/TetherFramework/BonjourDiscovery.swiftsimilarity index 69%rename from apple/Tether/Services/BonjourDiscovery.swiftrename to apple/TetherFramework/Sources/TetherFramework/BonjourDiscovery.swiftindex f27c296..4312a04 100644--- a/apple/Tether/Services/BonjourDiscovery.swift+++ b/apple/TetherFramework/Sources/TetherFramework/BonjourDiscovery.swift@@ -1,6 +1,6 @@//// BonjourDiscovery.swift-// Tether+// TetherFramework//// NetServiceBrowser-based mDNS/Bonjour discovery for `_tether._tcp` services.// Using NetService to correctly parse TXT records which NWBrowser ignores.@@ -10,41 +10,51 @@ import Foundationimport Network// A single discovered `tetherd` instance on the local network.-struct DiscoveredHost: Identifiable, Sendable {- let id = UUID()- let name: String- let endpoint: NWEndpoint- let fingerprint: String+public struct DiscoveredHost: Identifiable, Sendable {+ public let id = UUID()+ public let name: String+ public let endpoint: NWEndpoint+ public let fingerprint: String++ public init(name: String, endpoint: NWEndpoint, fingerprint: String) {+ self.name = name+ self.endpoint = endpoint+ self.fingerprint = fingerprint+ }}// Scans the local network for `tetherd` daemons advertising `_tether._tcp`// via Bonjour/mDNS and exposes the results as an observable list.@Observable-final class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDelegate {+public final class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDelegate {private static let serviceType = "_tether._tcp"private static let serviceDomain = "local."// Our own fingerprint, to filter ourselves out of the results.- var localFingerprint: String?+ public var localFingerprint: String?// Our own device name, as a fallback filter if the TXT record hasn't arrived.- var localDeviceName: String?+ public var localDeviceName: String?// Currently discovered hosts (updated live as services appear/disappear).- private(set) var hosts: [DiscoveredHost] = []+ public private(set) var hosts: [DiscoveredHost] = []// Whether the browser is actively scanning.- private(set) var isScanning = false+ public private(set) var isScanning = falseprivate var browser: NetServiceBrowser?private var activeServices: Set<NetService> = []- @ObservationIgnored var onHostsChanged: (([DiscoveredHost]) -> Void)?+ @ObservationIgnored public var onHostsChanged: (([DiscoveredHost]) -> Void)?++ public override init() {+ super.init()+ }// MARK: - Public// Start scanning for `_tether._tcp` services.- func startScanning(forceRestart: Bool = false) {+ public func startScanning(forceRestart: Bool = false) {if forceRestart {stopScanning(clearHosts: true)}@@ -60,7 +70,7 @@ final class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDel}// Stop scanning.- func stopScanning(clearHosts: Bool = false) {+ public func stopScanning(clearHosts: Bool = false) {browser?.stop()browser = nilisScanning = false@@ -75,32 +85,32 @@ final class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDel// MARK: - NetServiceBrowserDelegate- func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {+ public func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {activeServices.insert(service)service.delegate = selfservice.resolve(withTimeout: 5.0)}- func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {+ public func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {activeServices.remove(service)hosts.removeAll { $0.name == service.name }onHostsChanged?(hosts)}- func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {+ public func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String: NSNumber]) {print("BonjourDiscovery: Browser failed to search: \(errorDict)")isScanning = falseself.browser = nil}- func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) {+ public func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) {isScanning = false}// MARK: - NetServiceDelegate- func netServiceDidResolveAddress(_ sender: NetService) {+ public func netServiceDidResolveAddress(_ sender: NetService) {let name = sender.namelet endpoint = NWEndpoint.service(name: name, type: Self.serviceType, domain: Self.serviceDomain, interface: nil)var fingerprint = ""@@ -131,7 +141,7 @@ final class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDelonHostsChanged?(hosts)}- func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {+ public func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {netServiceDidResolveAddress(sender)}}diff --git a/apple/Tether/Services/CertificateManager.swift b/apple/TetherFramework/Sources/TetherFramework/CertificateManager.swiftsimilarity index 80%rename from apple/Tether/Services/CertificateManager.swiftrename to apple/TetherFramework/Sources/TetherFramework/CertificateManager.swiftindex f6c4ac0..a192bb9 100644--- a/apple/Tether/Services/CertificateManager.swift+++ b/apple/TetherFramework/Sources/TetherFramework/CertificateManager.swift@@ -1,56 +1,80 @@//// CertificateManager.swift-// Tether+// TetherFramework//// Self-signed X.509 certificate generation, Keychain identity management,// and SHA-256 fingerprint computation — all in pure Swift (no OpenSSL).//+// Shared between the main app and the Share Extension via a common+// App Group (group.net.jeedup.Tether) and Keychain access group.+//import Foundationimport Securityimport CryptoKit++#if canImport(UIKit)import UIKit+#endif// Manages the app's TLS identity (self-signed RSA cert + private key)// and the set of known remote host fingerprints.+//+// All Keychain items are stored in the shared access group so both the+// main app and the Share Extension can read them.+// All UserDefaults are stored in the shared App Group suite.@Observable-final class CertificateManager {+public final class CertificateManager {+ // Shared App Group identifier — must match both targets' entitlements.+ public static let appGroupID = "group.net.jeedup.Tether"++ // Shared Keychain access group — must match both targets' entitlements.+ // The prefix is omitted here; we set kSecAttrAccessGroup directly.+ private static let keychainAccessGroup = "group.net.jeedup.Tether"+private static let keyTag = "net.jeedup.Tether.key"private static let certLabel = "net.jeedup.Tether.cert"private static let knownHostsKey = "TetherKnownHosts"private static let localDeviceNameKey = "TetherLocalDeviceName"private static let lastConnectedFingerprintKey = "TetherLastConnectedFingerprint"+ // Shared UserDefaults suite backed by the App Group container.+ private static var sharedDefaults: UserDefaults {+ UserDefaults(suiteName: appGroupID) ?? .standard+ }+// SHA-256 fingerprint of our own certificate (lowercase hex, no separators).- private(set) var myFingerprint: String = ""+ public private(set) var myFingerprint: String = ""// Map of known host fingerprints → device name.- private(set) var knownHosts: [String: String] = [:]+ public private(set) var knownHosts: [String: String] = [:]// The fingerprint of the host we most recently connected to.- var lastConnectedFingerprint: String? {+ public var lastConnectedFingerprint: String? {didSet {- UserDefaults.standard.set(lastConnectedFingerprint, forKey: Self.lastConnectedFingerprintKey)+ Self.sharedDefaults.set(lastConnectedFingerprint, forKey: Self.lastConnectedFingerprintKey)}}// Name of this device as presented to others.- var localDeviceName: String = "" {+ public var localDeviceName: String = "" {didSet {- UserDefaults.standard.set(localDeviceName, forKey: Self.localDeviceNameKey)+ Self.sharedDefaults.set(localDeviceName, forKey: Self.localDeviceNameKey)}}// The `SecIdentity` used for mTLS client authentication.private var identity: SecIdentity?+ public init() {}+// MARK: - Initialization// Load or create the TLS identity and populate known hosts.- func initialize() {+ public func initialize() {loadKnownHosts()loadLocalDeviceName()- lastConnectedFingerprint = UserDefaults.standard.string(forKey: Self.lastConnectedFingerprintKey)+ lastConnectedFingerprint = Self.sharedDefaults.string(forKey: Self.lastConnectedFingerprintKey)if let existing = loadIdentityFromKeychain() {identity = existing@@ -68,22 +92,22 @@ final class CertificateManager {}// Returns the `SecIdentity` for use with `Network.framework` TLS options.- func getIdentity() -> SecIdentity? {+ public func getIdentity() -> SecIdentity? {identity}// MARK: - Known Hosts- func isHostKnown(_ fingerprint: String) -> Bool {+ public func isHostKnown(_ fingerprint: String) -> Bool {knownHosts[fingerprint] != nil}- func addKnownHost(fingerprint: String, name: String) {+ public func addKnownHost(fingerprint: String, name: String) {knownHosts[fingerprint] = namesaveKnownHosts()}- func removeKnownHost(fingerprint: String) {+ public func removeKnownHost(fingerprint: String) {knownHosts.removeValue(forKey: fingerprint)saveKnownHosts()}@@ -92,7 +116,7 @@ final class CertificateManager {// Compute the SHA-256 fingerprint of a DER-encoded certificate.// Output matches the daemon's `generate_fingerprint`: lowercase hex, no separators.- static func fingerprint(ofCertificate cert: SecCertificate) -> String {+ public static func fingerprint(ofCertificate cert: SecCertificate) -> String {let der = SecCertificateCopyData(cert) as Datalet hash = SHA256.hash(data: der)return hash.map { String(format: "%02x", $0) }.joined()@@ -101,11 +125,12 @@ final class CertificateManager {// MARK: - Private — Keychainprivate func loadIdentityFromKeychain() -> SecIdentity? {- // First check if the private key exists+ // First check if the private key exists in the shared access grouplet keyQuery: [String: Any] = [kSecClass as String: kSecClassKey,kSecAttrApplicationTag as String: Self.keyTag.data(using: .utf8)!,kSecAttrKeyType as String: kSecAttrKeyTypeRSA,+ kSecAttrAccessGroup as String: Self.keychainAccessGroup,kSecReturnRef as String: true,]var keyResult: CFTypeRef?@@ -113,10 +138,11 @@ final class CertificateManager {return nil}- // Now look for the identity (cert + key pair)+ // Now look for the identity (cert + key pair) in the shared access grouplet identityQuery: [String: Any] = [kSecClass as String: kSecClassIdentity,kSecAttrApplicationTag as String: Self.keyTag.data(using: .utf8)!,+ kSecAttrAccessGroup as String: Self.keychainAccessGroup,kSecReturnRef as String: true,]var identityResult: CFTypeRef?@@ -135,7 +161,7 @@ final class CertificateManager {}private func loadKnownHosts() {- if let data = UserDefaults.standard.data(forKey: Self.knownHostsKey),+ if let data = Self.sharedDefaults.data(forKey: Self.knownHostsKey),let hosts = try? JSONDecoder().decode([String: String].self, from: data){knownHosts = hosts@@ -144,12 +170,12 @@ final class CertificateManager {private func saveKnownHosts() {if let data = try? JSONEncoder().encode(knownHosts) {- UserDefaults.standard.set(data, forKey: Self.knownHostsKey)+ Self.sharedDefaults.set(data, forKey: Self.knownHostsKey)}}private func loadLocalDeviceName() {- if let name = UserDefaults.standard.string(forKey: Self.localDeviceNameKey) {+ if let name = Self.sharedDefaults.string(forKey: Self.localDeviceNameKey) {localDeviceName = name} else {// Default name@@ -164,15 +190,16 @@ final class CertificateManager {// MARK: - Private — Certificate Generation// Generate a 2048-bit RSA keypair + self-signed X.509v3 certificate and- // store both in the Keychain as a `SecIdentity`.+ // store both in the Keychain in the shared access group as a `SecIdentity`.private func generateAndStoreIdentity() -> SecIdentity? {- // 1. Generate RSA 2048 keypair in Keychain+ // 1. Generate RSA 2048 keypair in Keychain (shared access group)let keyAttrs: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeRSA,kSecAttrKeySizeInBits as String: 2048,kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: true,kSecAttrApplicationTag as String: Self.keyTag.data(using: .utf8)!,+ kSecAttrAccessGroup as String: Self.keychainAccessGroup,kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,] as [String: Any],]@@ -204,7 +231,7 @@ final class CertificateManager {return nil}- // 4. Import certificate into Keychain+ // 4. Import certificate into Keychain (shared access group)guard let certificate = SecCertificateCreateWithData(nil, certDER as CFData) else {print("CertificateManager: Failed to create SecCertificate from DER")return nil@@ -214,6 +241,7 @@ final class CertificateManager {kSecClass as String: kSecClassCertificate,kSecValueRef as String: certificate,kSecAttrLabel as String: Self.certLabel,+ kSecAttrAccessGroup as String: Self.keychainAccessGroup,kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,]let addStatus = SecItemAdd(addCertQuery as CFDictionary, nil)diff --git a/apple/TetherFramework/Sources/TetherFramework/SharePayload.swift b/apple/TetherFramework/Sources/TetherFramework/SharePayload.swiftnew file mode 100644index 0000000..0df3dd2--- /dev/null+++ b/apple/TetherFramework/Sources/TetherFramework/SharePayload.swift@@ -0,0 +1,23 @@+//+// SharePayload.swift+// TetherFramework+//+// Typed representation of content that the Share Extension can send to tetherd.+//++import Foundation++/// The kind of content being shared via the Tether Share Extension.+public enum SharePayload: Sendable {+ /// Send text to the Linux Wayland clipboard (`clipboard_set`).+ case clipboard(String)++ /// Send an OTP/2FA code to the tetherd vault (`new_otp`).+ /// - Parameters:+ /// - code: The OTP digits or secret string.+ /// - source: Human-readable label (email subject, website name, etc.).+ case otp(String, source: String)++ /// Send binary data as a file transfer (`file_start` / `file_chunk` / `file_end`).+ case file(Data, filename: String)+}diff --git a/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift b/apple/TetherFramework/Sources/TetherFramework/ShareSender.swiftnew file mode 100644index 0000000..050cfc6--- /dev/null+++ b/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift@@ -0,0 +1,228 @@+//+// ShareSender.swift+// TetherFramework+//+// Bootstraps a fresh mTLS connection from the Share Extension context,+// sends a SharePayload to the last-known tetherd daemon, and disconnects.+//+// Design constraints:+// - The Share Extension process is short-lived with no pre-existing connection.+// - We connect on-demand to the last-known host (stored in the shared App Group UserDefaults).+// - We do NOT run BonjourDiscovery; instead we connect directly to the last known+// NWEndpoint service name which persists in UserDefaults.+//++import Foundation+import Network++/// Errors that can occur during a share send operation.+public enum ShareSenderError: LocalizedError {+ case notPaired+ case noKnownHost+ case identityUnavailable+ case connectionFailed(String)+ case timeout+ case fileTransferFailed(String)++ public var errorDescription: String? {+ switch self {+ case .notPaired:+ return "This device is not paired with a Tether host. Open the Tether app to pair first."+ case .noKnownHost:+ return "No Tether host found. Open the Tether app and connect to your desktop first."+ case .identityUnavailable:+ return "TLS identity unavailable. Open the Tether app to initialize it."+ case .connectionFailed(let msg):+ return "Connection failed: \(msg)"+ case .timeout:+ return "Connection timed out. Make sure tetherd is running on your desktop."+ case .fileTransferFailed(let msg):+ return "File transfer failed: \(msg)"+ }+ }+}++/// Async helper used by the Share Extension to send a payload to tetherd.+///+/// Usage:+/// ```swift+/// let result = await ShareSender.send(.clipboard("Hello, world!"))+/// ```+public actor ShareSender {+ // Keys for the last-known Bonjour service name, stored in shared UserDefaults.+ private static let lastServiceNameKey = "TetherLastServiceName"+ private static let serviceType = "_tether._tcp"+ private static let serviceDomain = "local."++ // Chunk size for file transfers (48 KB raw → ~64 KB base64).+ private static let fileChunkSize = 48 * 1024++ // Maximum seconds to wait for the connection to become ready.+ private static let connectionTimeoutSeconds: Double = 8++ /// Send a `SharePayload` to the paired tetherd daemon.+ ///+ /// - Parameter payload: The content to send.+ /// - Returns: `Result<Void, Error>` — success or a descriptive error.+ public static func send(_ payload: SharePayload) async -> Result<Void, Error> {+ // 1. Initialize certificate manager (reads from shared Keychain + UserDefaults)+ let certManager = CertificateManager()+ certManager.initialize()++ guard let identity = certManager.getIdentity() else {+ return .failure(ShareSenderError.identityUnavailable)+ }++ // 2. Determine last-known fingerprint+ guard let targetFingerprint = certManager.lastConnectedFingerprint,+ certManager.isHostKnown(targetFingerprint) else {+ return .failure(ShareSenderError.noKnownHost)+ }++ // 3. Resolve endpoint — use the last-known service name stored by the main app+ let sharedDefaults = UserDefaults(suiteName: CertificateManager.appGroupID) ?? .standard+ guard let serviceName = sharedDefaults.string(forKey: lastServiceNameKey),+ !serviceName.isEmpty else {+ return .failure(ShareSenderError.noKnownHost)+ }++ let endpoint = NWEndpoint.service(+ name: serviceName,+ type: serviceType,+ domain: serviceDomain,+ interface: nil+ )++ // 4. Connect+ let connection = TetherConnection()+ do {+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in+ var resumed = false++ connection.onStateChange = { state in+ guard !resumed else { return }+ switch state {+ case .connected:+ resumed = true+ continuation.resume()+ case .failed(let msg):+ resumed = true+ continuation.resume(throwing: ShareSenderError.connectionFailed(msg))+ default:+ break+ }+ }++ connection.connect(to: endpoint, identity: identity)++ // Timeout guard+ Task {+ try? await Task.sleep(for: .seconds(connectionTimeoutSeconds))+ if !resumed {+ resumed = true+ connection.disconnect()+ continuation.resume(throwing: ShareSenderError.timeout)+ }+ }+ }+ } catch {+ return .failure(error)+ }++ // 5. Send payload+ let sendResult: Result<Void, Error>+ switch payload {+ case .clipboard(let text):+ connection.send(.clipboardSet(text))+ // Give the message time to flush before disconnecting+ try? await Task.sleep(for: .milliseconds(300))+ sendResult = .success(())++ case .otp(let code, let source):+ connection.send(.newOtp(code, source: source))+ try? await Task.sleep(for: .milliseconds(300))+ sendResult = .success(())++ case .file(let data, let filename):+ sendResult = await sendFile(data: data, filename: filename, via: connection)+ }++ connection.disconnect()+ return sendResult+ }++ // MARK: - Private — File Transfer++ private static func sendFile(+ data fileData: Data,+ filename: String,+ via connection: TetherConnection+ ) async -> Result<Void, Error> {+ let transferId = UUID().uuidString+ let totalSize = Int64(fileData.count)++ // Listen for file_status confirmation+ let statusResult: Result<Void, Error> = await withCheckedContinuation { continuation in+ var resumed = false++ connection.onMessage = { message in+ guard !resumed else { return }+ switch message.parsedCommand {+ case .fileStatus:+ if message.transferId == transferId, message.status == "success" {+ resumed = true+ continuation.resume(returning: .success(()))+ }+ case .error:+ resumed = true+ let msg = message.message ?? "Unknown error from daemon"+ continuation.resume(returning: .failure(ShareSenderError.fileTransferFailed(msg)))+ default:+ break+ }+ }++ // Send file_start+ connection.send(.fileStart(filename: filename, size: totalSize, transferId: transferId))++ // Stream chunks+ Task {+ var offset = 0+ var chunkIndex = 0+ while offset < fileData.count {+ let end = min(offset + fileChunkSize, fileData.count)+ let chunk = fileData[offset..<end]+ let base64 = chunk.base64EncodedString()++ connection.send(.fileChunk(transferId: transferId, chunkIndex: chunkIndex, data: base64))+ offset = end+ chunkIndex += 1+ try? await Task.sleep(for: .milliseconds(10))+ }++ // Send file_end+ connection.send(.fileEnd(transferId: transferId))++ // Timeout for file_status+ try? await Task.sleep(for: .seconds(30))+ if !resumed {+ resumed = true+ continuation.resume(returning: .failure(ShareSenderError.timeout))+ }+ }+ }++ return statusResult+ }+}++// MARK: - Main App Helper++extension ShareSender {+ /// Called by the main app whenever it connects to a host, so the Share Extension+ /// can later resolve the Bonjour service name without running its own discovery.+ public static func persistLastServiceName(_ name: String) {+ let sharedDefaults = UserDefaults(suiteName: CertificateManager.appGroupID) ?? .standard+ sharedDefaults.set(name, forKey: lastServiceNameKey)+ }+}diff --git a/apple/Tether/Services/TetherConnection.swift b/apple/TetherFramework/Sources/TetherFramework/TetherConnection.swiftsimilarity index 90%rename from apple/Tether/Services/TetherConnection.swiftrename to apple/TetherFramework/Sources/TetherFramework/TetherConnection.swiftindex f2aef78..079eadd 100644--- a/apple/Tether/Services/TetherConnection.swift+++ b/apple/TetherFramework/Sources/TetherFramework/TetherConnection.swift@@ -1,6 +1,6 @@//// TetherConnection.swift-// Tether+// TetherFramework//// NWConnection-based TCP + TLS client with mTLS client-certificate// authentication for communicating with the tetherd daemon.@@ -11,7 +11,7 @@ import Networkimport Security// Connection state exposed to the UI.-enum ConnectionState: Sendable, Equatable {+public enum ConnectionState: Sendable, Equatable {case disconnectedcase connectingcase connected(isInbound: Bool)@@ -25,21 +25,23 @@ enum ConnectionState: Sendable, Equatable {// - Accept any server certificate (the daemon also uses self-signed certs).// - Capture the server's SHA-256 fingerprint during the TLS handshake.@Observable-final class TetherConnection {+public final class TetherConnection {// Current connection state.- private(set) var state: ConnectionState = .disconnected+ public private(set) var state: ConnectionState = .disconnected// The server's TLS certificate fingerprint, captured during handshake.- private(set) var serverFingerprint: String = ""+ public private(set) var serverFingerprint: String = ""private var connection: NWConnection?private var receiveBuffer = Data()// Callback invoked on the main queue for each decoded message.- var onMessage: ((TetherMessage) -> Void)?+ public var onMessage: ((TetherMessage) -> Void)?// Callback invoked when the connection state changes.- var onStateChange: ((ConnectionState) -> Void)?+ public var onStateChange: ((ConnectionState) -> Void)?++ public init() {}// MARK: - Public API@@ -48,7 +50,7 @@ final class TetherConnection {// - Parameters:// - endpoint: The Bonjour or direct `NWEndpoint` to connect to.// - identity: The client's `SecIdentity` for mTLS authentication.- func connect(to endpoint: NWEndpoint, identity: SecIdentity) {+ public func connect(to endpoint: NWEndpoint, identity: SecIdentity) {disconnect()let tlsOptions = NWProtocolTLS.Options()@@ -84,7 +86,7 @@ final class TetherConnection {}// Connect directly to a host:port (for manual connection).- func connect(host: String, port: UInt16, identity: SecIdentity) {+ public func connect(host: String, port: UInt16, identity: SecIdentity) {let endpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(host),port: NWEndpoint.Port(rawValue: port)!@@ -93,27 +95,27 @@ final class TetherConnection {}// Accept a pre-established incoming connection from `TetherServer`.- //+ //// - Parameters:// - connection: The `NWConnection` already established and in `.ready` state.// - fingerprint: The verified TLS fingerprint of the incoming client.- func accept(incomingConnection conn: NWConnection, fingerprint: String) {+ public func accept(incomingConnection conn: NWConnection, fingerprint: String) {disconnect()self.serverFingerprint = fingerprintself.connection = conn-+// Re-bind the state update handler for the accepted connectionconn.stateUpdateHandler = { [weak self] nwState inself?.handleStateUpdate(nwState)}-+// It's already ready, so we just jump straight to receivingupdateState(.connected(isInbound: true))startReceiving()}// Disconnect and tear down the connection.- func disconnect() {+ public func disconnect() {connection?.cancel()connection = nilreceiveBuffer = Data()@@ -122,9 +124,9 @@ final class TetherConnection {}// Send a protocol message to the daemon.- func send(_ message: TetherMessage) {+ public func send(_ message: TetherMessage) {guard let conn = connection else { return }-+if case .connected = state {do {let data = try TetherProtocol.encode(message)diff --git a/apple/Tether/Protocol/TetherMessage.swift b/apple/TetherFramework/Sources/TetherFramework/TetherMessage.swiftsimilarity index 51%rename from apple/Tether/Protocol/TetherMessage.swiftrename to apple/TetherFramework/Sources/TetherFramework/TetherMessage.swiftindex dfb7e49..ef60764 100644--- a/apple/Tether/Protocol/TetherMessage.swift+++ b/apple/TetherFramework/Sources/TetherFramework/TetherMessage.swift@@ -1,6 +1,6 @@//// TetherMessage.swift-// Tether+// TetherFramework//// Codable models matching the tetherd newline-delimited JSON protocol.//@@ -10,7 +10,7 @@ import Foundation// MARK: - Command Enum// All known command types in the Tether protocol.-enum TetherCommand: String, Codable, Sendable {+public enum TetherCommand: String, Codable, Sendable {// Client → Daemoncase clipboardSet = "clipboard_set"case clipboardGet = "clipboard_get"@@ -18,6 +18,7 @@ enum TetherCommand: String, Codable, Sendable {case fileChunk = "file_chunk"case fileEnd = "file_end"case pairRequest = "pair_request"+ case newOtp = "new_otp"// Daemon → Clientcase clipboardUpdated = "clipboard_updated"@@ -35,61 +36,100 @@ enum TetherCommand: String, Codable, Sendable {// Uses a flat structure with optional fields — the daemon's JSON payloads// share a unified shape where only the relevant fields are present// for each command type.-struct TetherMessage: Codable, Sendable {- let command: String+public struct TetherMessage: Codable, Sendable {+ public let command: String// Clipboard- var content: String?+ public var content: String?// File transfer- var filename: String?- var size: Int64?- var transferId: String?- var chunkIndex: Int?- var data: String? // Base64 encoded chunk+ public var filename: String?+ public var size: Int64?+ public var transferId: String?+ public var chunkIndex: Int?+ public var data: String? // Base64 encoded chunk// Pairing- var deviceName: String?+ public var deviceName: String?++ // OTP (new_otp command uses "otp" and optional "source" keys)+ public var otp: String?+ public var source: String?// Status / Error- var status: String?- var message: String?+ public var status: String?+ public var message: String?- enum CodingKeys: String, CodingKey {+ public enum CodingKeys: String, CodingKey {case command, content, filename, sizecase transferId = "transfer_id"case chunkIndex = "chunk_index"case datacase deviceName = "device_name"+ case otp, sourcecase status, message}++ public init(+ command: String,+ content: String? = nil,+ filename: String? = nil,+ size: Int64? = nil,+ transferId: String? = nil,+ chunkIndex: Int? = nil,+ data: String? = nil,+ deviceName: String? = nil,+ otp: String? = nil,+ source: String? = nil,+ status: String? = nil,+ message: String? = nil+ ) {+ self.command = command+ self.content = content+ self.filename = filename+ self.size = size+ self.transferId = transferId+ self.chunkIndex = chunkIndex+ self.data = data+ self.deviceName = deviceName+ self.otp = otp+ self.source = source+ self.status = status+ self.message = message+ }}// MARK: - Convenience Initializersextension TetherMessage {// Create a `clipboard_set` message.- static func clipboardSet(_ text: String) -> TetherMessage {+ public static func clipboardSet(_ text: String) -> TetherMessage {TetherMessage(command: TetherCommand.clipboardSet.rawValue, content: text)}// Create a `clipboard_get` request.- static func clipboardGet() -> TetherMessage {+ public static func clipboardGet() -> TetherMessage {TetherMessage(command: TetherCommand.clipboardGet.rawValue)}+ // Create a `new_otp` message.+ // Uses the `otp` key to match the daemon's Unix socket handler and TCP handler.+ public static func newOtp(_ code: String, source: String = "iPhone Share") -> TetherMessage {+ TetherMessage(command: TetherCommand.newOtp.rawValue, otp: code, source: source)+ }+// Create a `pair_request` message.- static func pairRequest(deviceName: String) -> TetherMessage {+ public static func pairRequest(deviceName: String) -> TetherMessage {TetherMessage(command: TetherCommand.pairRequest.rawValue, deviceName: deviceName)}// Create a `pair_accepted` message (replying to a request).- static var pairAccepted: TetherMessage {+ public static var pairAccepted: TetherMessage {TetherMessage(command: TetherCommand.pairAccepted.rawValue)}// Create a `file_start` message.- static func fileStart(filename: String, size: Int64, transferId: String) -> TetherMessage {+ public static func fileStart(filename: String, size: Int64, transferId: String) -> TetherMessage {TetherMessage(command: TetherCommand.fileStart.rawValue,filename: filename,@@ -99,7 +139,7 @@ extension TetherMessage {}// Create a `file_chunk` message.- static func fileChunk(transferId: String, chunkIndex: Int, data: String) -> TetherMessage {+ public static func fileChunk(transferId: String, chunkIndex: Int, data: String) -> TetherMessage {TetherMessage(command: TetherCommand.fileChunk.rawValue,transferId: transferId,@@ -109,12 +149,12 @@ extension TetherMessage {}// Create a `file_end` message.- static func fileEnd(transferId: String) -> TetherMessage {+ public static func fileEnd(transferId: String) -> TetherMessage {TetherMessage(command: TetherCommand.fileEnd.rawValue, transferId: transferId)}// The parsed command enum, if recognized.- var parsedCommand: TetherCommand? {+ public var parsedCommand: TetherCommand? {TetherCommand(rawValue: command)}}diff --git a/apple/Tether/Protocol/TetherProtocol.swift b/apple/TetherFramework/Sources/TetherFramework/TetherProtocol.swiftsimilarity index 90%rename from apple/Tether/Protocol/TetherProtocol.swiftrename to apple/TetherFramework/Sources/TetherFramework/TetherProtocol.swiftindex f8b58ba..4e7df0f 100644--- a/apple/Tether/Protocol/TetherProtocol.swift+++ b/apple/TetherFramework/Sources/TetherFramework/TetherProtocol.swift@@ -1,6 +1,6 @@//// TetherProtocol.swift-// Tether+// TetherFramework//// Newline-delimited JSON framing over raw byte streams.//@@ -9,7 +9,7 @@ import Foundation// Handles encoding and decoding of `TetherMessage` values using the// newline-delimited JSON wire format spoken by `tetherd`.-enum TetherProtocol {+public enum TetherProtocol {private static let encoder: JSONEncoder = {let e = JSONEncoder()e.keyEncodingStrategy = .useDefaultKeys@@ -27,7 +27,7 @@ enum TetherProtocol {// MARK: - Encoding// Encode a message to its wire representation (JSON + trailing newline).- static func encode(_ message: TetherMessage) throws -> Data {+ public static func encode(_ message: TetherMessage) throws -> Data {var data = try encoder.encode(message)data.append(newline)return data@@ -42,7 +42,7 @@ enum TetherProtocol {//// Lines that fail JSON parsing (e.g. the daemon's bare `OK\n` response)// are silently skipped.- static func decode(buffer: inout Data) -> [TetherMessage] {+ public static func decode(buffer: inout Data) -> [TetherMessage] {var messages: [TetherMessage] = []while let newlineIndex = buffer.firstIndex(of: newline) {diff --git a/apple/Tether/Services/TetherServer.swift b/apple/TetherFramework/Sources/TetherFramework/TetherServer.swiftsimilarity index 87%rename from apple/Tether/Services/TetherServer.swiftrename to apple/TetherFramework/Sources/TetherFramework/TetherServer.swiftindex 4cfcf7a..c699979 100644--- a/apple/Tether/Services/TetherServer.swift+++ b/apple/TetherFramework/Sources/TetherFramework/TetherServer.swift@@ -1,6 +1,6 @@//// TetherServer.swift-// Tether+// TetherFramework//// NWListener-based TCP + TLS server to accept incoming connections// from `tetherd` instances (making iOS a symmetrical peer).@@ -11,34 +11,38 @@ import Networkimport Security@Observable-final class TetherServer: NSObject, NetServiceDelegate {+public final class TetherServer: NSObject, NetServiceDelegate {private var listener: NWListener?private var netService: NetService?-- var isListening = false-++ public var isListening = false+// Callback when a verified inbound connection is received- var onNewConnection: ((NWConnection, String) -> Void)?-- func start(identity: SecIdentity, localDeviceName: String, fingerprint: String) {+ public var onNewConnection: ((NWConnection, String) -> Void)?++ public override init() {+ super.init()+ }++ public func start(identity: SecIdentity, localDeviceName: String, fingerprint: String) {stop()-+let tlsOptions = NWProtocolTLS.Options()let secOptions = tlsOptions.securityProtocolOptions-+let secIdentity = sec_identity_create(identity)!sec_protocol_options_set_local_identity(secOptions, secIdentity)-+sec_protocol_options_set_min_tls_protocol_version(secOptions, .TLSv12)sec_protocol_options_set_max_tls_protocol_version(secOptions, .TLSv12)-+// As a server, require the client to present its certificatesec_protocol_options_set_peer_authentication_required(secOptions, true)-+// Temporarily store the fingerprint. In a high-concurrency server we'd use a robust map,// but for a single peer-to-peer mobile app, a simple property is more than sufficient.var temporaryHandshakeFingerprint = ""-+// Accept the certificate and capture the fingerprintsec_protocol_options_set_verify_block(secOptions, { metadata, trust, completion inlet secTrust = sec_trust_copy_ref(trust).takeRetainedValue()@@ -46,19 +50,19 @@ final class TetherServer: NSObject, NetServiceDelegate {let clientCert = certChain.first {temporaryHandshakeFingerprint = CertificateManager.fingerprint(ofCertificate: clientCert)}- completion(true)+ completion(true)}, .main)-+let params = NWParameters(tls: tlsOptions, tcp: .init())params.includePeerToPeer = true-+do {let nwListener = try NWListener(using: params)-+nwListener.newConnectionHandler = { [weak self] connection inself?.handleNewConnection(connection, capturedFingerprint: temporaryHandshakeFingerprint)}-+nwListener.stateUpdateHandler = { [weak self] state inguard let self = self else { return }switch state {@@ -78,57 +82,57 @@ final class TetherServer: NSObject, NetServiceDelegate {break}}-+nwListener.start(queue: .main)self.listener = nwListener-+} catch {print("TetherServer: Failed to create listener: \(error)")}}-- func stop() {++ public func stop() {listener?.cancel()listener = nil-+netService?.stop()netService = nil-+isListening = false}-+private func publishBonjour(port: UInt16, deviceName: String, fingerprint: String) {netService = NetService(domain: "local.", type: "_tether._tcp", name: deviceName, port: Int32(port))-+if let fpData = fingerprint.data(using: .utf8) {let txtDict = ["fp": fpData]let txtRecord = NetService.data(fromTXTRecord: txtDict)netService?.setTXTRecord(txtRecord)}-+netService?.delegate = selfnetService?.publish()}-+private func handleNewConnection(_ connection: NWConnection, capturedFingerprint: @escaping @autoclosure () -> String) {connection.stateUpdateHandler = { [weak self] state inguard let self = self else { return }print("TetherServer: Inbound connection state: \(state)")if case .ready = state {print("TetherServer: Inbound connection established and ready.")- self.onNewConnection?(connection, capturedFingerprint())+ self.onNewConnection?(connection, capturedFingerprint())}}-+connection.start(queue: .main)}-+// NetServiceDelegate- func netServiceDidPublish(_ sender: NetService) {+ public func netServiceDidPublish(_ sender: NetService) {print("TetherServer: Bonjour service published successfully.")}-- func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) {++ public func netService(_ sender: NetService, didNotPublish errorDict: [String: NSNumber]) {print("TetherServer: Bonjour publish failed: \(errorDict)")}}