Skip to content

Linux + iPhone Continuity / iMessage / SMS

initial iphone app implementation

Zack Bartel7e1d88a6a274
diff --git a/apple/Tether/ContentView.swift b/apple/Tether/ContentView.swift
index f4e1973..c9fe396 100644
--- a/apple/Tether/ContentView.swift
+++ b/apple/Tether/ContentView.swift
@@ -8,17 +8,46 @@
import SwiftUI
struct ContentView: View {
+ @Environment(TetherViewModel.self) private var viewModel
+
var body: some View {
- VStack {
- Image(systemName: "globe")
- .imageScale(.large)
- .foregroundStyle(.tint)
- Text("Hello, world!")
+ @Bindable var vm = viewModel
+
+ TabView {
+ Tab("Dashboard", systemImage: "antenna.radiowaves.left.and.right") {
+ DashboardView()
+ }
+
+ Tab("Clipboard", systemImage: "clipboard") {
+ ClipboardView()
+ }
+
+ Tab("Files", systemImage: "arrow.up.arrow.down") {
+ FilesView()
+ }
+
+ Tab("Settings", systemImage: "gearshape") {
+ SettingsView()
+ }
+ }
+ .tint(.teal)
+ .sheet(isPresented: $vm.showPairingSheet) {
+ PairingView()
+ .environment(viewModel)
+ .interactiveDismissDisabled()
+ }
+ .alert("Error", isPresented: .init(
+ get: { viewModel.errorMessage != nil },
+ set: { if !$0 { vm.errorMessage = nil } }
+ )) {
+ Button("OK") { vm.errorMessage = nil }
+ } message: {
+ Text(viewModel.errorMessage ?? "")
}
- .padding()
}
}
#Preview {
ContentView()
+ .environment(TetherViewModel())
}
diff --git a/apple/Tether/Protocol/TetherMessage.swift b/apple/Tether/Protocol/TetherMessage.swift
new file mode 100644
index 0000000..00ce1b2
--- /dev/null
+++ b/apple/Tether/Protocol/TetherMessage.swift
@@ -0,0 +1,114 @@
+//
+// TetherMessage.swift
+// Tether
+//
+// Codable models matching the tetherd newline-delimited JSON protocol.
+//
+
+import Foundation
+
+// MARK: - Command Enum
+
+/// All known command types in the Tether protocol.
+enum TetherCommand: String, Codable, Sendable {
+ // Client → Daemon
+ case clipboardSet = "clipboard_set"
+ case clipboardGet = "clipboard_get"
+ case fileStart = "file_start"
+ case fileChunk = "file_chunk"
+ case fileEnd = "file_end"
+ case pairRequest = "pair_request"
+
+ // Daemon → Client
+ case clipboardUpdated = "clipboard_updated"
+ case clipboardContent = "clipboard_content"
+ case fileStatus = "file_status"
+ case pairPending = "pair_pending"
+ case error = "error"
+}
+
+// MARK: - Message
+
+/// A single Tether protocol message.
+///
+/// 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
+
+ // Clipboard
+ var content: String?
+
+ // File transfer
+ var filename: String?
+ var size: Int64?
+ var transferId: String?
+ var chunkIndex: Int?
+ var data: String? // Base64 encoded chunk
+
+ // Pairing
+ var deviceName: String?
+
+ // Status / Error
+ var status: String?
+ var message: String?
+
+ enum CodingKeys: String, CodingKey {
+ case command, content, filename, size
+ case transferId = "transfer_id"
+ case chunkIndex = "chunk_index"
+ case data
+ case deviceName = "device_name"
+ case status, message
+ }
+}
+
+// MARK: - Convenience Initializers
+
+extension TetherMessage {
+ /// Create a `clipboard_set` message.
+ static func clipboardSet(_ text: String) -> TetherMessage {
+ TetherMessage(command: TetherCommand.clipboardSet.rawValue, content: text)
+ }
+
+ /// Create a `clipboard_get` request.
+ static func clipboardGet() -> TetherMessage {
+ TetherMessage(command: TetherCommand.clipboardGet.rawValue)
+ }
+
+ /// Create a `pair_request` message.
+ static func pairRequest(deviceName: String) -> TetherMessage {
+ TetherMessage(command: TetherCommand.pairRequest.rawValue, deviceName: deviceName)
+ }
+
+ /// Create a `file_start` message.
+ static func fileStart(filename: String, size: Int64, transferId: String) -> TetherMessage {
+ TetherMessage(
+ command: TetherCommand.fileStart.rawValue,
+ filename: filename,
+ size: size,
+ transferId: transferId
+ )
+ }
+
+ /// Create a `file_chunk` message.
+ static func fileChunk(transferId: String, chunkIndex: Int, data: String) -> TetherMessage {
+ TetherMessage(
+ command: TetherCommand.fileChunk.rawValue,
+ chunkIndex: chunkIndex,
+ data: data,
+ transferId: transferId
+ )
+ }
+
+ /// Create a `file_end` message.
+ static func fileEnd(transferId: String) -> TetherMessage {
+ TetherMessage(command: TetherCommand.fileEnd.rawValue, transferId: transferId)
+ }
+
+ /// The parsed command enum, if recognized.
+ var parsedCommand: TetherCommand? {
+ TetherCommand(rawValue: command)
+ }
+}
diff --git a/apple/Tether/Protocol/TetherProtocol.swift b/apple/Tether/Protocol/TetherProtocol.swift
new file mode 100644
index 0000000..59ba13d
--- /dev/null
+++ b/apple/Tether/Protocol/TetherProtocol.swift
@@ -0,0 +1,64 @@
+//
+// TetherProtocol.swift
+// Tether
+//
+// Newline-delimited JSON framing over raw byte streams.
+//
+
+import Foundation
+
+/// Handles encoding and decoding of `TetherMessage` values using the
+/// newline-delimited JSON wire format spoken by `tetherd`.
+enum TetherProtocol {
+ private static let encoder: JSONEncoder = {
+ let e = JSONEncoder()
+ e.keyEncodingStrategy = .useDefaultKeys
+ return e
+ }()
+
+ private static let decoder: JSONDecoder = {
+ let d = JSONDecoder()
+ d.keyDecodingStrategy = .useDefaultKeys
+ return d
+ }()
+
+ private static let newline = UInt8(ascii: "\n")
+
+ // MARK: - Encoding
+
+ /// Encode a message to its wire representation (JSON + trailing newline).
+ static func encode(_ message: TetherMessage) throws -> Data {
+ var data = try encoder.encode(message)
+ data.append(newline)
+ return data
+ }
+
+ // MARK: - Decoding
+
+ /// Scan a mutable buffer for complete newline-delimited messages.
+ ///
+ /// Parsed messages are returned and their bytes are consumed from `buffer`.
+ /// Any trailing partial line is left in `buffer` for the next call.
+ ///
+ /// Lines that fail JSON parsing (e.g. the daemon's bare `OK\n` response)
+ /// are silently skipped.
+ static func decode(buffer: inout Data) -> [TetherMessage] {
+ var messages: [TetherMessage] = []
+
+ while let newlineIndex = buffer.firstIndex(of: newline) {
+ let lineData = buffer[buffer.startIndex..<newlineIndex]
+ buffer = Data(buffer[buffer.index(after: newlineIndex)...])
+
+ guard !lineData.isEmpty else { continue }
+
+ do {
+ let message = try decoder.decode(TetherMessage.self, from: Data(lineData))
+ messages.append(message)
+ } catch {
+ // Non-JSON lines (like "OK") are silently ignored.
+ }
+ }
+
+ return messages
+ }
+}
diff --git a/apple/Tether/Services/BonjourDiscovery.swift b/apple/Tether/Services/BonjourDiscovery.swift
new file mode 100644
index 0000000..d975094
--- /dev/null
+++ b/apple/Tether/Services/BonjourDiscovery.swift
@@ -0,0 +1,106 @@
+//
+// BonjourDiscovery.swift
+// Tether
+//
+// NWBrowser-based mDNS/Bonjour discovery for `_tether._tcp` services.
+//
+
+import Foundation
+import 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
+}
+
+/// 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 {
+ private static let serviceType = "_tether._tcp"
+
+ /// Currently discovered hosts (updated live as services appear/disappear).
+ private(set) var hosts: [DiscoveredHost] = []
+
+ /// Whether the browser is actively scanning.
+ private(set) var isScanning = false
+
+ private var browser: NWBrowser?
+
+ // MARK: - Public
+
+ /// Start scanning for `_tether._tcp` services.
+ func startScanning() {
+ guard !isScanning else { return }
+
+ let params = NWParameters()
+ params.includePeerToPeer = true
+
+ let browser = NWBrowser(
+ for: .bonjour(type: Self.serviceType, domain: nil),
+ using: params
+ )
+
+ browser.stateUpdateHandler = { [weak self] state in
+ switch state {
+ case .ready:
+ self?.isScanning = true
+ case .failed(let error):
+ print("BonjourDiscovery: Browser failed: \(error)")
+ self?.isScanning = false
+ case .cancelled:
+ self?.isScanning = false
+ default:
+ break
+ }
+ }
+
+ browser.browseResultsChangedHandler = { [weak self] results, _ in
+ self?.handleResults(results)
+ }
+
+ browser.start(queue: .main)
+ self.browser = browser
+ }
+
+ /// Stop scanning.
+ func stopScanning() {
+ browser?.cancel()
+ browser = nil
+ isScanning = false
+ }
+
+ // MARK: - Private
+
+ private func handleResults(_ results: Set<NWBrowser.Result>) {
+ hosts = results.compactMap { result -> DiscoveredHost? in
+ guard case .service(let name, _, _, _) = result.endpoint else {
+ return nil
+ }
+
+ let fingerprint = extractFingerprint(from: result.metadata)
+ return DiscoveredHost(
+ name: name,
+ endpoint: result.endpoint,
+ fingerprint: fingerprint
+ )
+ }
+ }
+
+ /// Extract the `fp=<sha256>` value from the Bonjour TXT record.
+ private func extractFingerprint(from metadata: NWBrowser.Result.Metadata) -> String {
+ guard case .bonjour(let txtRecord) = metadata else {
+ return ""
+ }
+
+ if let fpEntry = txtRecord.getEntry(for: "fp"),
+ case .string(let value) = fpEntry
+ {
+ return value
+ }
+ return ""
+ }
+}
diff --git a/apple/Tether/Services/CertificateManager.swift b/apple/Tether/Services/CertificateManager.swift
new file mode 100644
index 0000000..d728ae6
--- /dev/null
+++ b/apple/Tether/Services/CertificateManager.swift
@@ -0,0 +1,321 @@
+//
+// CertificateManager.swift
+// Tether
+//
+// Self-signed X.509 certificate generation, Keychain identity management,
+// and SHA-256 fingerprint computation — all in pure Swift (no OpenSSL).
+//
+
+import Foundation
+import Security
+import CryptoKit
+
+/// Manages the app's TLS identity (self-signed RSA cert + private key)
+/// and the set of known remote host fingerprints.
+@Observable
+final class CertificateManager {
+ private static let keyTag = "net.jeedup.Tether.key"
+ private static let certLabel = "net.jeedup.Tether.cert"
+ private static let knownHostsKey = "TetherKnownHosts"
+
+ /// SHA-256 fingerprint of our own certificate (lowercase hex, no separators).
+ private(set) var myFingerprint: String = ""
+
+ /// Map of known host fingerprints → device name.
+ private(set) var knownHosts: [String: String] = [:]
+
+ /// The `SecIdentity` used for mTLS client authentication.
+ private var identity: SecIdentity?
+
+ // MARK: - Initialization
+
+ /// Load or create the TLS identity and populate known hosts.
+ func initialize() {
+ loadKnownHosts()
+
+ if let existing = loadIdentityFromKeychain() {
+ identity = existing
+ myFingerprint = fingerprintFromIdentity(existing) ?? ""
+ return
+ }
+
+ // First launch — generate a new self-signed identity.
+ guard let newIdentity = generateAndStoreIdentity() else {
+ print("CertificateManager: Failed to generate TLS identity")
+ return
+ }
+ identity = newIdentity
+ myFingerprint = fingerprintFromIdentity(newIdentity) ?? ""
+ }
+
+ /// Returns the `SecIdentity` for use with `Network.framework` TLS options.
+ func getIdentity() -> SecIdentity? {
+ identity
+ }
+
+ // MARK: - Known Hosts
+
+ func isHostKnown(_ fingerprint: String) -> Bool {
+ knownHosts[fingerprint] != nil
+ }
+
+ func addKnownHost(fingerprint: String, name: String) {
+ knownHosts[fingerprint] = name
+ saveKnownHosts()
+ }
+
+ func removeKnownHost(fingerprint: String) {
+ knownHosts.removeValue(forKey: fingerprint)
+ saveKnownHosts()
+ }
+
+ // MARK: - Fingerprint
+
+ /// 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 {
+ let der = SecCertificateCopyData(cert) as Data
+ let hash = SHA256.hash(data: der)
+ return hash.map { String(format: "%02x", $0) }.joined()
+ }
+
+ // MARK: - Private — Keychain
+
+ private func loadIdentityFromKeychain() -> SecIdentity? {
+ // First check if the private key exists
+ let keyQuery: [String: Any] = [
+ kSecClass as String: kSecClassKey,
+ kSecAttrApplicationTag as String: Self.keyTag.data(using: .utf8)!,
+ kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
+ kSecReturnRef as String: true,
+ ]
+ var keyResult: CFTypeRef?
+ guard SecItemCopyMatching(keyQuery as CFDictionary, &keyResult) == errSecSuccess else {
+ return nil
+ }
+
+ // Now look for the identity (cert + key pair)
+ let identityQuery: [String: Any] = [
+ kSecClass as String: kSecClassIdentity,
+ kSecAttrApplicationTag as String: Self.keyTag.data(using: .utf8)!,
+ kSecReturnRef as String: true,
+ ]
+ var identityResult: CFTypeRef?
+ guard SecItemCopyMatching(identityQuery as CFDictionary, &identityResult) == errSecSuccess else {
+ return nil
+ }
+ return (identityResult as! SecIdentity)
+ }
+
+ private func fingerprintFromIdentity(_ identity: SecIdentity) -> String? {
+ var cert: SecCertificate?
+ guard SecIdentityCopyCertificate(identity, &cert) == errSecSuccess, let cert else {
+ return nil
+ }
+ return Self.fingerprint(ofCertificate: cert)
+ }
+
+ private func loadKnownHosts() {
+ if let data = UserDefaults.standard.data(forKey: Self.knownHostsKey),
+ let hosts = try? JSONDecoder().decode([String: String].self, from: data)
+ {
+ knownHosts = hosts
+ }
+ }
+
+ private func saveKnownHosts() {
+ if let data = try? JSONEncoder().encode(knownHosts) {
+ UserDefaults.standard.set(data, forKey: Self.knownHostsKey)
+ }
+ }
+
+ // MARK: - Private — Certificate Generation
+
+ /// Generate a 2048-bit RSA keypair + self-signed X.509v3 certificate and
+ /// store both in the Keychain as a `SecIdentity`.
+ private func generateAndStoreIdentity() -> SecIdentity? {
+ // 1. Generate RSA 2048 keypair in Keychain
+ 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)!,
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,
+ ] as [String: Any],
+ ]
+
+ var error: Unmanaged<CFError>?
+ guard let privateKey = SecKeyCreateRandomKey(keyAttrs as CFDictionary, &error) else {
+ print("CertificateManager: Key generation failed: \(error!.takeRetainedValue())")
+ return nil
+ }
+
+ guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
+ print("CertificateManager: Failed to derive public key")
+ return nil
+ }
+
+ // 2. Get public key PKCS#1 DER
+ guard let pubKeyDER = SecKeyCopyExternalRepresentation(publicKey, nil) as Data? else {
+ print("CertificateManager: Failed to export public key")
+ return nil
+ }
+
+ // 3. Build self-signed X.509v3 certificate
+ guard let certDER = buildSelfSignedCertificate(
+ publicKeyDER: pubKeyDER,
+ privateKey: privateKey,
+ commonName: "Tether-iOS"
+ ) else {
+ print("CertificateManager: Failed to build certificate")
+ return nil
+ }
+
+ // 4. Import certificate into Keychain
+ guard let certificate = SecCertificateCreateWithData(nil, certDER as CFData) else {
+ print("CertificateManager: Failed to create SecCertificate from DER")
+ return nil
+ }
+
+ let addCertQuery: [String: Any] = [
+ kSecClass as String: kSecClassCertificate,
+ kSecValueRef as String: certificate,
+ kSecAttrLabel as String: Self.certLabel,
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,
+ ]
+ let addStatus = SecItemAdd(addCertQuery as CFDictionary, nil)
+ guard addStatus == errSecSuccess || addStatus == errSecDuplicateItem else {
+ print("CertificateManager: Failed to add certificate to keychain: \(addStatus)")
+ return nil
+ }
+
+ // 5. Retrieve the paired identity
+ return loadIdentityFromKeychain()
+ }
+
+ // MARK: - ASN.1 DER Construction
+
+ /// Build a minimal self-signed X.509v3 certificate in DER format.
+ private func buildSelfSignedCertificate(
+ publicKeyDER: Data,
+ privateKey: SecKey,
+ commonName: String
+ ) -> Data? {
+ let now = Date()
+ let tenYears = now.addingTimeInterval(315_360_000) // 10 years in seconds
+
+ // OIDs
+ let oidSHA256RSA: [UInt8] = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B]
+ let oidRSA: [UInt8] = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01]
+ let oidCN: [UInt8] = [0x55, 0x04, 0x03]
+
+ // AlgorithmIdentifier: sha256WithRSAEncryption
+ let sigAlgId = asn1Sequence(asn1OID(oidSHA256RSA) + asn1Null())
+
+ // Name: CN=commonName
+ let nameAttr = asn1Sequence(asn1OID(oidCN) + asn1UTF8String(commonName))
+ let nameRDN = asn1Set(nameAttr)
+ let name = asn1Sequence(nameRDN)
+
+ // Validity
+ let validity = asn1Sequence(asn1UTCTime(now) + asn1UTCTime(tenYears))
+
+ // SubjectPublicKeyInfo
+ let spkiAlg = asn1Sequence(asn1OID(oidRSA) + asn1Null())
+ let spki = asn1Sequence(spkiAlg + asn1BitString(Array(publicKeyDER)))
+
+ // Serial number (random 8 bytes)
+ var serialBytes = [UInt8](repeating: 0, count: 8)
+ _ = SecRandomCopyBytes(kSecRandomDefault, serialBytes.count, &serialBytes)
+ serialBytes[0] &= 0x7F // Ensure positive
+
+ // TBSCertificate
+ let version = asn1ExplicitTag(0, asn1Integer([0x02])) // v3
+ let serial = asn1Integer(serialBytes)
+
+ let tbsContents = version + serial + sigAlgId + name + validity + name + spki
+ let tbsDER = asn1Sequence(tbsContents)
+
+ // Sign the TBSCertificate with the private key
+ var signError: Unmanaged<CFError>?
+ guard let signatureData = SecKeyCreateSignature(
+ privateKey,
+ .rsaSignatureMessagePKCS1v15SHA256,
+ Data(tbsDER) as CFData,
+ &signError
+ ) as Data? else {
+ print("CertificateManager: Signing failed: \(signError!.takeRetainedValue())")
+ return nil
+ }
+
+ // Final Certificate structure
+ let certContents = tbsDER + sigAlgId + asn1BitString(Array(signatureData))
+ let certDER = asn1Sequence(certContents)
+
+ return Data(certDER)
+ }
+
+ // MARK: - ASN.1 Primitives
+
+ private func asn1Length(_ length: Int) -> [UInt8] {
+ if length < 128 {
+ return [UInt8(length)]
+ } else if length < 256 {
+ return [0x81, UInt8(length)]
+ } else if length < 65536 {
+ return [0x82, UInt8(length >> 8), UInt8(length & 0xFF)]
+ } else {
+ return [0x83, UInt8(length >> 16), UInt8((length >> 8) & 0xFF), UInt8(length & 0xFF)]
+ }
+ }
+
+ private func asn1Sequence(_ contents: [UInt8]) -> [UInt8] {
+ [0x30] + asn1Length(contents.count) + contents
+ }
+
+ private func asn1Set(_ contents: [UInt8]) -> [UInt8] {
+ [0x31] + asn1Length(contents.count) + contents
+ }
+
+ private func asn1Integer(_ value: [UInt8]) -> [UInt8] {
+ var bytes = value
+ // Ensure the integer is positive (leading bit must be 0)
+ if let first = bytes.first, first & 0x80 != 0 {
+ bytes.insert(0x00, at: 0)
+ }
+ return [0x02] + asn1Length(bytes.count) + bytes
+ }
+
+ private func asn1BitString(_ contents: [UInt8]) -> [UInt8] {
+ // Prepend the "unused bits" count (always 0 for byte-aligned data)
+ let payload = [0x00] + contents
+ return [0x03] + asn1Length(payload.count) + payload
+ }
+
+ private func asn1Null() -> [UInt8] {
+ [0x05, 0x00]
+ }
+
+ private func asn1OID(_ oid: [UInt8]) -> [UInt8] {
+ [0x06, UInt8(oid.count)] + oid
+ }
+
+ private func asn1UTF8String(_ string: String) -> [UInt8] {
+ let bytes = Array(string.utf8)
+ return [0x0C] + asn1Length(bytes.count) + bytes
+ }
+
+ private func asn1UTCTime(_ date: Date) -> [UInt8] {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyMMddHHmmss'Z'"
+ formatter.timeZone = TimeZone(identifier: "UTC")
+ let bytes = Array(formatter.string(from: date).utf8)
+ return [0x17, UInt8(bytes.count)] + bytes
+ }
+
+ private func asn1ExplicitTag(_ tag: UInt8, _ contents: [UInt8]) -> [UInt8] {
+ let tagByte = 0xA0 | tag
+ return [tagByte] + asn1Length(contents.count) + contents
+ }
+}
diff --git a/apple/Tether/Services/TetherConnection.swift b/apple/Tether/Services/TetherConnection.swift
new file mode 100644
index 0000000..6f6a373
--- /dev/null
+++ b/apple/Tether/Services/TetherConnection.swift
@@ -0,0 +1,188 @@
+//
+// TetherConnection.swift
+// Tether
+//
+// NWConnection-based TCP + TLS client with mTLS client-certificate
+// authentication for communicating with the tetherd daemon.
+//
+
+import Foundation
+import Network
+import Security
+
+/// Connection state exposed to the UI.
+enum ConnectionState: Sendable, Equatable {
+ case disconnected
+ case connecting
+ case connected
+ case failed(String)
+}
+
+/// Manages a single TCP+TLS connection to a `tetherd` instance.
+///
+/// Uses `Network.framework` (`NWConnection`) with custom TLS options that:
+/// - Present our self-signed client certificate for mTLS.
+/// - 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 {
+ /// Current connection state.
+ private(set) var state: ConnectionState = .disconnected
+
+ /// The server's TLS certificate fingerprint, captured during handshake.
+ 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)?
+
+ /// Callback invoked when the connection state changes.
+ var onStateChange: ((ConnectionState) -> Void)?
+
+ // MARK: - Public API
+
+ /// Connect to a discovered tetherd endpoint using mTLS.
+ ///
+ /// - 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) {
+ disconnect()
+
+ let tlsOptions = NWProtocolTLS.Options()
+ let secOptions = tlsOptions.securityProtocolOptions
+
+ // Present our client certificate for mTLS
+ let secIdentity = sec_identity_create(identity)!
+ sec_protocol_options_set_local_identity(secOptions, secIdentity)
+
+ // TLS 1.2 minimum
+ sec_protocol_options_set_min_tls_protocol_version(secOptions, .TLSv12)
+
+ // Accept any server certificate (daemon uses self-signed)
+ // and capture the server's fingerprint.
+ sec_protocol_options_set_verify_block(secOptions, { [weak self] metadata, trust, completion in
+ self?.captureServerFingerprint(trust: trust)
+ completion(true)
+ }, .main)
+
+ let params = NWParameters(tls: tlsOptions, tcp: .init())
+ params.includePeerToPeer = true
+
+ let conn = NWConnection(to: endpoint, using: params)
+
+ conn.stateUpdateHandler = { [weak self] nwState in
+ self?.handleStateUpdate(nwState)
+ }
+
+ conn.start(queue: .main)
+ self.connection = conn
+ updateState(.connecting)
+ }
+
+ /// Connect directly to a host:port (for manual connection).
+ func connect(host: String, port: UInt16, identity: SecIdentity) {
+ let endpoint = NWEndpoint.hostPort(
+ host: NWEndpoint.Host(host),
+ port: NWEndpoint.Port(rawValue: port)!
+ )
+ connect(to: endpoint, identity: identity)
+ }
+
+ /// Disconnect and tear down the connection.
+ func disconnect() {
+ connection?.cancel()
+ connection = nil
+ receiveBuffer = Data()
+ serverFingerprint = ""
+ updateState(.disconnected)
+ }
+
+ /// Send a protocol message to the daemon.
+ func send(_ message: TetherMessage) {
+ guard let conn = connection, state == .connected else { return }
+
+ do {
+ let data = try TetherProtocol.encode(message)
+ conn.send(content: data, completion: .contentProcessed { error in
+ if let error {
+ print("TetherConnection: Send error: \(error)")
+ }
+ })
+ } catch {
+ print("TetherConnection: Encode error: \(error)")
+ }
+ }
+
+ // MARK: - Private — State
+
+ private func updateState(_ newState: ConnectionState) {
+ state = newState
+ onStateChange?(newState)
+ }
+
+ private func handleStateUpdate(_ nwState: NWConnection.State) {
+ switch nwState {
+ case .ready:
+ updateState(.connected)
+ startReceiving()
+ case .waiting(let error):
+ print("TetherConnection: Waiting: \(error)")
+ case .failed(let error):
+ updateState(.failed(error.localizedDescription))
+ case .cancelled:
+ updateState(.disconnected)
+ case .preparing:
+ updateState(.connecting)
+ default:
+ break
+ }
+ }
+
+ // MARK: - Private — Receive Loop
+
+ private func startReceiving() {
+ guard let conn = connection else { return }
+
+ conn.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] content, _, isComplete, error in
+ guard let self else { return }
+
+ if let data = content, !data.isEmpty {
+ self.receiveBuffer.append(data)
+ let messages = TetherProtocol.decode(buffer: &self.receiveBuffer)
+ for msg in messages {
+ self.onMessage?(msg)
+ }
+ }
+
+ if let error {
+ print("TetherConnection: Receive error: \(error)")
+ self.updateState(.failed(error.localizedDescription))
+ return
+ }
+
+ if isComplete {
+ self.updateState(.disconnected)
+ return
+ }
+
+ // Continue the receive loop
+ self.startReceiving()
+ }
+ }
+
+ // MARK: - Private — TLS Fingerprint
+
+ /// Extract the server's certificate and compute its SHA-256 fingerprint.
+ private func captureServerFingerprint(trust: sec_trust_t) {
+ let secTrust = sec_trust_copy_ref(trust).takeRetainedValue()
+
+ if let certChain = SecTrustCopyCertificateChain(secTrust) as? [SecCertificate],
+ let serverCert = certChain.first
+ {
+ serverFingerprint = CertificateManager.fingerprint(ofCertificate: serverCert)
+ }
+ }
+}
diff --git a/apple/Tether/TetherApp.swift b/apple/Tether/TetherApp.swift
index a6c955e..29d9b24 100644
--- a/apple/Tether/TetherApp.swift
+++ b/apple/Tether/TetherApp.swift
@@ -9,9 +9,16 @@ import SwiftUI
@main
struct TetherApp: App {
+ @State private var viewModel = TetherViewModel()
+
var body: some Scene {
WindowGroup {
ContentView()
+ .environment(viewModel)
+ .preferredColorScheme(.dark)
+ .onAppear {
+ viewModel.initialize()
+ }
}
}
}
diff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swift
new file mode 100644
index 0000000..84ac953
--- /dev/null
+++ b/apple/Tether/ViewModels/TetherViewModel.swift
@@ -0,0 +1,366 @@
+//
+// TetherViewModel.swift
+// Tether
+//
+// Central observable driving the entire app: discovery, pairing,
+// clipboard sync, and file transfer.
+//
+
+import Foundation
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// High-level app state.
+enum AppConnectionState: Equatable {
+ case disconnected
+ case discovering
+ case connecting
+ case pairing
+ case connected
+}
+
+/// A clipboard history entry.
+struct ClipboardEntry: Identifiable {
+ let id = UUID()
+ let content: String
+ let timestamp: Date
+ let source: ClipboardSource
+
+ enum ClipboardSource: String {
+ case local = "iPhone"
+ case remote = "Desktop"
+ }
+}
+
+/// Tracks an active file transfer.
+struct FileTransfer: Identifiable {
+ let id: String // transfer_id
+ let filename: String
+ let totalSize: Int64
+ var bytesSent: Int64 = 0
+ var isComplete = false
+ var failed = false
+
+ var progress: Double {
+ guard totalSize > 0 else { return 0 }
+ return Double(bytesSent) / Double(totalSize)
+ }
+}
+
+/// Main app ViewModel — owns all services and coordinates their interactions.
+@Observable
+final class TetherViewModel {
+ // MARK: - Published State
+
+ /// Overall connection state.
+ private(set) var appState: AppConnectionState = .disconnected
+
+ /// Name of the connected device, if any.
+ private(set) var connectedDeviceName: String?
+
+ /// Clipboard history (most recent first).
+ private(set) var clipboardHistory: [ClipboardEntry] = []
+
+ /// Active file transfers.
+ private(set) var activeTransfers: [FileTransfer] = []
+
+ /// Completed file transfers.
+ private(set) var completedTransfers: [FileTransfer] = []
+
+ /// Whether the pairing sheet should be presented.
+ var showPairingSheet = false
+
+ /// Status message for the pairing flow.
+ private(set) var pairingStatus: String = ""
+
+ /// Error message to display, if any.
+ var errorMessage: String?
+
+ // MARK: - Services
+
+ let certificateManager = CertificateManager()
+ let discovery = BonjourDiscovery()
+ let connection = TetherConnection()
+
+ /// The chunk size for file transfers (48KB raw → 64KB base64).
+ private let fileChunkSize = 48 * 1024
+
+ // MARK: - Initialization
+
+ /// Call once at app startup.
+ func initialize() {
+ certificateManager.initialize()
+ setupConnectionHandlers()
+ startDiscovery()
+ }
+
+ // MARK: - Discovery
+
+ func startDiscovery() {
+ discovery.startScanning()
+ if appState == .disconnected {
+ appState = .discovering
+ }
+ }
+
+ func stopDiscovery() {
+ discovery.stopScanning()
+ }
+
+ // MARK: - Connection
+
+ /// Connect to a discovered host.
+ func connectTo(host: DiscoveredHost) {
+ guard let identity = certificateManager.getIdentity() else {
+ errorMessage = "TLS identity not available. Please restart the app."
+ return
+ }
+
+ appState = .connecting
+ connectedDeviceName = host.name
+ connection.connect(to: host.endpoint, identity: identity)
+ }
+
+ /// Connect by IP address and port.
+ func connectTo(host: String, port: UInt16) {
+ guard let identity = certificateManager.getIdentity() else {
+ errorMessage = "TLS identity not available. Please restart the app."
+ return
+ }
+
+ appState = .connecting
+ connectedDeviceName = host
+ connection.connect(host: host, port: port, identity: identity)
+ }
+
+ /// Disconnect from the daemon.
+ func disconnect() {
+ connection.disconnect()
+ appState = .disconnected
+ connectedDeviceName = nil
+ }
+
+ // MARK: - Clipboard
+
+ /// Send the current iOS clipboard content to the daemon.
+ func sendClipboard() {
+ #if canImport(UIKit)
+ guard let text = UIPasteboard.general.string, !text.isEmpty else {
+ errorMessage = "Clipboard is empty."
+ return
+ }
+ #else
+ guard let text = NSPasteboard.general.string(forType: .string), !text.isEmpty else {
+ errorMessage = "Clipboard is empty."
+ return
+ }
+ #endif
+
+ connection.send(.clipboardSet(text))
+
+ let entry = ClipboardEntry(content: text, timestamp: Date(), source: .local)
+ clipboardHistory.insert(entry, at: 0)
+
+ // Keep the history manageable
+ if clipboardHistory.count > 50 {
+ clipboardHistory = Array(clipboardHistory.prefix(50))
+ }
+ }
+
+ /// Request the current clipboard from the daemon.
+ func requestClipboard() {
+ connection.send(.clipboardGet())
+ }
+
+ /// Copy a clipboard entry to the iOS pasteboard.
+ func copyToLocalClipboard(_ text: String) {
+ #if canImport(UIKit)
+ UIPasteboard.general.string = text
+ #else
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ #endif
+ }
+
+ // MARK: - File Transfer
+
+ /// Send a file to the daemon.
+ func sendFile(url: URL) {
+ guard url.startAccessingSecurityScopedResource() else {
+ errorMessage = "Cannot access file."
+ return
+ }
+
+ let transferId = UUID().uuidString
+ let filename = url.lastPathComponent
+
+ Task.detached { [weak self] in
+ guard let self else { return }
+
+ do {
+ let fileData = try Data(contentsOf: url)
+ let totalSize = Int64(fileData.count)
+
+ await MainActor.run {
+ let transfer = FileTransfer(
+ id: transferId,
+ filename: filename,
+ totalSize: totalSize
+ )
+ self.activeTransfers.append(transfer)
+ }
+
+ // Send file_start
+ await MainActor.run {
+ self.connection.send(.fileStart(
+ filename: filename,
+ size: totalSize,
+ transferId: transferId
+ ))
+ }
+
+ // Send chunks
+ var offset = 0
+ var chunkIndex = 0
+ while offset < fileData.count {
+ let end = min(offset + self.fileChunkSize, fileData.count)
+ let chunk = fileData[offset..<end]
+ let base64 = chunk.base64EncodedString()
+
+ await MainActor.run {
+ self.connection.send(.fileChunk(
+ transferId: transferId,
+ chunkIndex: chunkIndex,
+ data: base64
+ ))
+
+ if let idx = self.activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ self.activeTransfers[idx].bytesSent = Int64(end)
+ }
+ }
+
+ offset = end
+ chunkIndex += 1
+
+ // Small delay to avoid overwhelming the connection
+ try await Task.sleep(for: .milliseconds(10))
+ }
+
+ // Send file_end
+ await MainActor.run {
+ self.connection.send(.fileEnd(transferId: transferId))
+ }
+ } catch {
+ await MainActor.run {
+ if let idx = self.activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ self.activeTransfers[idx].failed = true
+ }
+ self.errorMessage = "File transfer failed: \(error.localizedDescription)"
+ }
+ }
+
+ url.stopAccessingSecurityScopedResource()
+ }
+ }
+
+ // MARK: - Private — Connection Handlers
+
+ private func setupConnectionHandlers() {
+ connection.onStateChange = { [weak self] state in
+ guard let self else { return }
+ switch state {
+ case .connected:
+ self.handleConnected()
+ case .disconnected:
+ self.appState = .disconnected
+ case .failed(let msg):
+ self.appState = .disconnected
+ self.errorMessage = "Connection failed: \(msg)"
+ case .connecting:
+ self.appState = .connecting
+ }
+ }
+
+ connection.onMessage = { [weak self] message in
+ self?.handleMessage(message)
+ }
+ }
+
+ private func handleConnected() {
+ let serverFP = connection.serverFingerprint
+
+ if certificateManager.isHostKnown(serverFP) {
+ // Already paired — go straight to connected
+ appState = .connected
+ connectedDeviceName = certificateManager.knownHosts[serverFP] ?? connectedDeviceName
+ } else {
+ // Need to pair
+ appState = .pairing
+ showPairingSheet = true
+ pairingStatus = "Sending pairing request..."
+
+ let deviceName: String
+ #if canImport(UIKit)
+ deviceName = UIDevice.current.name
+ #else
+ deviceName = Host.current().localizedName ?? "Mac"
+ #endif
+
+ connection.send(.pairRequest(deviceName: deviceName))
+ }
+ }
+
+ private func handleMessage(_ message: TetherMessage) {
+ switch message.parsedCommand {
+ case .clipboardUpdated:
+ if let content = message.content {
+ let entry = ClipboardEntry(content: content, timestamp: Date(), source: .remote)
+ clipboardHistory.insert(entry, at: 0)
+ if clipboardHistory.count > 50 {
+ clipboardHistory = Array(clipboardHistory.prefix(50))
+ }
+ }
+
+ case .clipboardContent:
+ if let content = message.content {
+ let entry = ClipboardEntry(content: content, timestamp: Date(), source: .remote)
+ clipboardHistory.insert(entry, at: 0)
+ }
+
+ case .pairPending:
+ pairingStatus = "Waiting for approval on your desktop...\n\nRun: tether --accept \(certificateManager.myFingerprint)"
+
+ case .fileStatus:
+ if let transferId = message.transferId, message.status == "success" {
+ if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ var transfer = activeTransfers.remove(at: idx)
+ transfer.isComplete = true
+ completedTransfers.insert(transfer, at: 0)
+ }
+ }
+
+ case .error:
+ if message.message == "unauthorized" {
+ // The daemon rejected us — we're not paired yet.
+ // This can happen if the user hasn't accepted the pairing request.
+ pairingStatus = "Pairing request sent. Waiting for approval...\n\nRun: tether --accept \(certificateManager.myFingerprint)"
+ } else {
+ errorMessage = message.message ?? "Unknown error from daemon"
+ }
+
+ default:
+ break
+ }
+ }
+
+ /// Call after the daemon accepts the pairing request.
+ /// The daemon will start accepting our commands, so we just need to
+ /// save the server fingerprint and transition to connected state.
+ func confirmPairing() {
+ let serverFP = connection.serverFingerprint
+ let name = connectedDeviceName ?? "Desktop"
+ certificateManager.addKnownHost(fingerprint: serverFP, name: name)
+ showPairingSheet = false
+ appState = .connected
+ }
+}
diff --git a/apple/Tether/Views/ClipboardView.swift b/apple/Tether/Views/ClipboardView.swift
new file mode 100644
index 0000000..f83da9b
--- /dev/null
+++ b/apple/Tether/Views/ClipboardView.swift
@@ -0,0 +1,187 @@
+//
+// ClipboardView.swift
+// Tether
+//
+// Clipboard sync interface: send/receive buttons, clipboard history.
+//
+
+import SwiftUI
+
+struct ClipboardView: View {
+ @Environment(TetherViewModel.self) private var viewModel
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ if viewModel.appState != .connected {
+ notConnectedView
+ } else {
+ connectedView
+ }
+ }
+ .background(Color(.systemGroupedBackground))
+ .navigationTitle("Clipboard")
+ }
+ }
+
+ // MARK: - Not Connected
+
+ private var notConnectedView: some View {
+ VStack(spacing: 16) {
+ Spacer()
+
+ Image(systemName: "clipboard")
+ .font(.system(size: 48))
+ .foregroundStyle(.tertiary)
+
+ Text("Connect to a device to sync clipboard")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+ }
+ .frame(maxWidth: .infinity)
+ }
+
+ // MARK: - Connected
+
+ private var connectedView: some View {
+ ScrollView {
+ VStack(spacing: 20) {
+ // Action Buttons
+ HStack(spacing: 12) {
+ clipboardActionButton(
+ title: "Send to Desktop",
+ subtitle: "Copy iPhone clipboard",
+ icon: "arrow.up.circle.fill",
+ color: .teal
+ ) {
+ viewModel.sendClipboard()
+ }
+
+ clipboardActionButton(
+ title: "Get from Desktop",
+ subtitle: "Fetch desktop clipboard",
+ icon: "arrow.down.circle.fill",
+ color: .indigo
+ ) {
+ viewModel.requestClipboard()
+ }
+ }
+ .padding(.horizontal)
+ .padding(.top, 4)
+
+ // History
+ VStack(alignment: .leading, spacing: 12) {
+ Text("History")
+ .font(.headline)
+ .foregroundStyle(.secondary)
+ .padding(.horizontal)
+
+ if viewModel.clipboardHistory.isEmpty {
+ VStack(spacing: 12) {
+ Image(systemName: "clock.arrow.circlepath")
+ .font(.system(size: 32))
+ .foregroundStyle(.tertiary)
+
+ Text("No clipboard activity yet")
+ .font(.subheadline)
+ .foregroundStyle(.tertiary)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 40)
+ } else {
+ LazyVStack(spacing: 8) {
+ ForEach(viewModel.clipboardHistory) { entry in
+ clipboardEntryRow(entry)
+ }
+ }
+ .padding(.horizontal)
+ }
+ }
+ }
+ .padding(.vertical)
+ }
+ }
+
+ // MARK: - Components
+
+ private func clipboardActionButton(
+ title: String,
+ subtitle: String,
+ icon: String,
+ color: Color,
+ action: @escaping () -> Void
+ ) -> some View {
+ Button(action: action) {
+ VStack(alignment: .leading, spacing: 8) {
+ Image(systemName: icon)
+ .font(.title)
+ .foregroundStyle(color)
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title)
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(.primary)
+
+ Text(subtitle)
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 14))
+ }
+ .buttonStyle(.plain)
+ }
+
+ private func clipboardEntryRow(_ entry: ClipboardEntry) -> some View {
+ Button {
+ viewModel.copyToLocalClipboard(entry.content)
+ } label: {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: entry.source == .remote ? "desktopcomputer" : "iphone")
+ .font(.subheadline)
+ .foregroundStyle(entry.source == .remote ? .indigo : .teal)
+ .frame(width: 24)
+ .padding(.top, 2)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(entry.content)
+ .font(.subheadline)
+ .foregroundStyle(.primary)
+ .lineLimit(3)
+
+ HStack(spacing: 6) {
+ Text(entry.source.rawValue)
+ .font(.caption2.weight(.medium))
+ .foregroundStyle(entry.source == .remote ? .indigo : .teal)
+
+ Text("·")
+ .foregroundStyle(.quaternary)
+
+ Text(entry.timestamp, style: .relative)
+ .font(.caption2)
+ .foregroundStyle(.quaternary)
+ }
+ }
+
+ Spacer()
+
+ Image(systemName: "doc.on.doc")
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ }
+ .padding(14)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 12))
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+#Preview {
+ ClipboardView()
+ .environment(TetherViewModel())
+ .preferredColorScheme(.dark)
+}
diff --git a/apple/Tether/Views/Components/ConnectionStatusView.swift b/apple/Tether/Views/Components/ConnectionStatusView.swift
new file mode 100644
index 0000000..f306eee
--- /dev/null
+++ b/apple/Tether/Views/Components/ConnectionStatusView.swift
@@ -0,0 +1,74 @@
+//
+// ConnectionStatusView.swift
+// Tether
+//
+// Reusable animated connection status indicator.
+//
+
+import SwiftUI
+
+struct ConnectionStatusView: View {
+ let state: AppConnectionState
+
+ @State private var isPulsing = false
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Circle()
+ .fill(dotColor)
+ .frame(width: 10, height: 10)
+ .scaleEffect(isPulsing ? 1.3 : 1.0)
+ .opacity(isPulsing ? 0.6 : 1.0)
+ .animation(
+ isAnimating
+ ? .easeInOut(duration: 0.8).repeatForever(autoreverses: true)
+ : .default,
+ value: isPulsing
+ )
+
+ Text(statusText)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+ .onChange(of: state, initial: true) {
+ isPulsing = isAnimating
+ }
+ }
+
+ private var dotColor: Color {
+ switch state {
+ case .connected: .green
+ case .connecting, .pairing, .discovering: .orange
+ case .disconnected: .red
+ }
+ }
+
+ private var statusText: String {
+ switch state {
+ case .connected: "Connected"
+ case .connecting: "Connecting…"
+ case .pairing: "Pairing…"
+ case .discovering: "Searching…"
+ case .disconnected: "Disconnected"
+ }
+ }
+
+ private var isAnimating: Bool {
+ switch state {
+ case .connecting, .pairing, .discovering: true
+ default: false
+ }
+ }
+}
+
+#Preview {
+ VStack(spacing: 20) {
+ ConnectionStatusView(state: .connected)
+ ConnectionStatusView(state: .connecting)
+ ConnectionStatusView(state: .disconnected)
+ ConnectionStatusView(state: .discovering)
+ ConnectionStatusView(state: .pairing)
+ }
+ .padding()
+ .preferredColorScheme(.dark)
+}
diff --git a/apple/Tether/Views/DashboardView.swift b/apple/Tether/Views/DashboardView.swift
new file mode 100644
index 0000000..185474d
--- /dev/null
+++ b/apple/Tether/Views/DashboardView.swift
@@ -0,0 +1,322 @@
+//
+// DashboardView.swift
+// Tether
+//
+// Main dashboard: connection status, discovered hosts, quick actions.
+//
+
+import SwiftUI
+
+struct DashboardView: View {
+ @Environment(TetherViewModel.self) private var viewModel
+
+ @State private var manualHost = ""
+ @State private var manualPort = "5134"
+ @State private var showManualConnect = false
+
+ var body: some View {
+ NavigationStack {
+ ScrollView {
+ VStack(spacing: 20) {
+ // Status Card
+ statusCard
+
+ // Quick Actions (when connected)
+ if viewModel.appState == .connected {
+ quickActions
+ }
+
+ // Discovered Hosts (when not connected)
+ if viewModel.appState != .connected {
+ discoveredHostsSection
+ }
+ }
+ .padding()
+ }
+ .background(Color(.systemGroupedBackground))
+ .navigationTitle("Tether")
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ if viewModel.appState == .connected {
+ Button {
+ viewModel.disconnect()
+ } label: {
+ Image(systemName: "xmark.circle.fill")
+ .foregroundStyle(.secondary)
+ }
+ } else {
+ Button {
+ showManualConnect.toggle()
+ } label: {
+ Image(systemName: "network")
+ .foregroundStyle(.teal)
+ }
+ }
+ }
+ }
+ .sheet(isPresented: $showManualConnect) {
+ manualConnectSheet
+ }
+ }
+ }
+
+ // MARK: - Status Card
+
+ private var statusCard: some View {
+ VStack(spacing: 16) {
+ // Large icon
+ ZStack {
+ Circle()
+ .fill(statusGradient)
+ .frame(width: 80, height: 80)
+
+ Image(systemName: statusIcon)
+ .font(.system(size: 32, weight: .medium))
+ .foregroundStyle(.white)
+ }
+ .shadow(color: statusAccentColor.opacity(0.4), radius: 12, y: 4)
+
+ VStack(spacing: 6) {
+ if let deviceName = viewModel.connectedDeviceName,
+ viewModel.appState == .connected
+ {
+ Text(deviceName)
+ .font(.title2.weight(.semibold))
+
+ ConnectionStatusView(state: viewModel.appState)
+ } else {
+ Text("No Connection")
+ .font(.title2.weight(.semibold))
+
+ ConnectionStatusView(state: viewModel.appState)
+ }
+ }
+
+ // Fingerprint
+ if !viewModel.certificateManager.myFingerprint.isEmpty {
+ VStack(spacing: 4) {
+ Text("Your Fingerprint")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ .textCase(.uppercase)
+
+ Text(formatFingerprint(viewModel.certificateManager.myFingerprint))
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .textSelection(.enabled)
+ }
+ .padding(.top, 4)
+ }
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20))
+ }
+
+ private var statusIcon: String {
+ switch viewModel.appState {
+ case .connected: "link"
+ case .connecting, .pairing: "arrow.triangle.2.circlepath"
+ case .discovering: "magnifyingglass"
+ case .disconnected: "link.badge.plus"
+ }
+ }
+
+ private var statusAccentColor: Color {
+ switch viewModel.appState {
+ case .connected: .green
+ case .connecting, .pairing, .discovering: .orange
+ case .disconnected: .teal
+ }
+ }
+
+ private var statusGradient: LinearGradient {
+ LinearGradient(
+ colors: [statusAccentColor, statusAccentColor.opacity(0.7)],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ }
+
+ // MARK: - Quick Actions
+
+ private var quickActions: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("Quick Actions")
+ .font(.headline)
+ .foregroundStyle(.secondary)
+
+ HStack(spacing: 12) {
+ actionButton(
+ title: "Send Clipboard",
+ icon: "doc.on.clipboard.fill",
+ color: .teal
+ ) {
+ viewModel.sendClipboard()
+ }
+
+ actionButton(
+ title: "Get Clipboard",
+ icon: "arrow.down.doc.fill",
+ color: .indigo
+ ) {
+ viewModel.requestClipboard()
+ }
+ }
+ }
+ }
+
+ private func actionButton(
+ title: String,
+ icon: String,
+ color: Color,
+ action: @escaping () -> Void
+ ) -> some View {
+ Button(action: action) {
+ VStack(spacing: 10) {
+ Image(systemName: icon)
+ .font(.title2)
+ .foregroundStyle(color)
+
+ Text(title)
+ .font(.caption.weight(.medium))
+ .foregroundStyle(.primary)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 16)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 14))
+ }
+ .buttonStyle(.plain)
+ }
+
+ // MARK: - Discovered Hosts
+
+ private var discoveredHostsSection: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack {
+ Text("Discovered Devices")
+ .font(.headline)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+
+ if viewModel.discovery.isScanning {
+ ProgressView()
+ .controlSize(.small)
+ }
+ }
+
+ if viewModel.discovery.hosts.isEmpty {
+ VStack(spacing: 12) {
+ Image(systemName: "radar")
+ .font(.system(size: 36))
+ .foregroundStyle(.tertiary)
+
+ Text("Searching for tetherd on your network…")
+ .font(.subheadline)
+ .foregroundStyle(.tertiary)
+ .multilineTextAlignment(.center)
+
+ Text("Make sure tetherd is running on your Linux machine.")
+ .font(.caption)
+ .foregroundStyle(.quaternary)
+ .multilineTextAlignment(.center)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 32)
+ } else {
+ ForEach(viewModel.discovery.hosts) { host in
+ Button {
+ viewModel.connectTo(host: host)
+ } label: {
+ HStack(spacing: 14) {
+ Image(systemName: "desktopcomputer")
+ .font(.title3)
+ .foregroundStyle(.teal)
+ .frame(width: 36)
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(host.name)
+ .font(.body.weight(.medium))
+ .foregroundStyle(.primary)
+
+ if !host.fingerprint.isEmpty {
+ Text(formatFingerprint(String(host.fingerprint.prefix(16))) + "…")
+ .font(.system(.caption2, design: .monospaced))
+ .foregroundStyle(.tertiary)
+ }
+ }
+
+ Spacer()
+
+ if viewModel.certificateManager.isHostKnown(host.fingerprint) {
+ Image(systemName: "checkmark.shield.fill")
+ .foregroundStyle(.green)
+ .font(.subheadline)
+ }
+
+ Image(systemName: "chevron.right")
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ }
+ .padding(14)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 14))
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ }
+ }
+
+ // MARK: - Manual Connect Sheet
+
+ private var manualConnectSheet: some View {
+ NavigationStack {
+ Form {
+ Section("Host") {
+ TextField("IP Address", text: $manualHost)
+ .keyboardType(.decimalPad)
+ .autocorrectionDisabled()
+
+ TextField("Port", text: $manualPort)
+ .keyboardType(.numberPad)
+ }
+
+ Section {
+ Button("Connect") {
+ let port = UInt16(manualPort) ?? 5134
+ viewModel.connectTo(host: manualHost, port: port)
+ showManualConnect = false
+ }
+ .disabled(manualHost.isEmpty)
+ }
+ }
+ .navigationTitle("Manual Connection")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { showManualConnect = false }
+ }
+ }
+ }
+ .presentationDetents([.medium])
+ }
+
+ // MARK: - Helpers
+
+ private func formatFingerprint(_ fp: String) -> String {
+ var result = ""
+ for (i, char) in fp.enumerated() {
+ if i > 0 && i % 2 == 0 { result += ":" }
+ result.append(char)
+ }
+ return result
+ }
+}
+
+#Preview {
+ DashboardView()
+ .environment(TetherViewModel())
+ .preferredColorScheme(.dark)
+}
diff --git a/apple/Tether/Views/FilesView.swift b/apple/Tether/Views/FilesView.swift
new file mode 100644
index 0000000..c91990c
--- /dev/null
+++ b/apple/Tether/Views/FilesView.swift
@@ -0,0 +1,242 @@
+//
+// FilesView.swift
+// Tether
+//
+// File transfer interface: document picker, progress, transfer history.
+//
+
+import SwiftUI
+import UniformTypeIdentifiers
+
+struct FilesView: View {
+ @Environment(TetherViewModel.self) private var viewModel
+
+ @State private var showDocumentPicker = false
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ if viewModel.appState != .connected {
+ notConnectedView
+ } else {
+ connectedView
+ }
+ }
+ .background(Color(.systemGroupedBackground))
+ .navigationTitle("Files")
+ .toolbar {
+ if viewModel.appState == .connected {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button {
+ showDocumentPicker = true
+ } label: {
+ Image(systemName: "plus.circle.fill")
+ .foregroundStyle(.teal)
+ }
+ }
+ }
+ }
+ .fileImporter(
+ isPresented: $showDocumentPicker,
+ allowedContentTypes: [.data],
+ allowsMultipleSelection: false
+ ) { result in
+ switch result {
+ case .success(let urls):
+ if let url = urls.first {
+ viewModel.sendFile(url: url)
+ }
+ case .failure(let error):
+ viewModel.errorMessage = "File selection failed: \(error.localizedDescription)"
+ }
+ }
+ }
+ }
+
+ // MARK: - Not Connected
+
+ private var notConnectedView: some View {
+ VStack(spacing: 16) {
+ Spacer()
+
+ Image(systemName: "arrow.up.arrow.down")
+ .font(.system(size: 48))
+ .foregroundStyle(.tertiary)
+
+ Text("Connect to a device to transfer files")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+ }
+ .frame(maxWidth: .infinity)
+ }
+
+ // MARK: - Connected
+
+ private var connectedView: some View {
+ ScrollView {
+ VStack(spacing: 20) {
+ // Send File Button
+ Button {
+ showDocumentPicker = true
+ } label: {
+ HStack(spacing: 14) {
+ ZStack {
+ Circle()
+ .fill(
+ LinearGradient(
+ colors: [.teal, .teal.opacity(0.7)],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ .frame(width: 48, height: 48)
+
+ Image(systemName: "arrow.up.doc.fill")
+ .font(.title3)
+ .foregroundStyle(.white)
+ }
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Send a File")
+ .font(.body.weight(.semibold))
+ .foregroundStyle(.primary)
+
+ Text("Transfer to your Linux desktop")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Image(systemName: "chevron.right")
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ }
+ .padding(16)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))
+ }
+ .buttonStyle(.plain)
+
+ // Active Transfers
+ if !viewModel.activeTransfers.isEmpty {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("In Progress")
+ .font(.headline)
+ .foregroundStyle(.secondary)
+
+ ForEach(viewModel.activeTransfers) { transfer in
+ transferRow(transfer, isActive: true)
+ }
+ }
+ }
+
+ // Completed Transfers
+ if !viewModel.completedTransfers.isEmpty {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("Completed")
+ .font(.headline)
+ .foregroundStyle(.secondary)
+
+ ForEach(viewModel.completedTransfers) { transfer in
+ transferRow(transfer, isActive: false)
+ }
+ }
+ }
+
+ // Empty State
+ if viewModel.activeTransfers.isEmpty && viewModel.completedTransfers.isEmpty {
+ VStack(spacing: 12) {
+ Image(systemName: "tray")
+ .font(.system(size: 32))
+ .foregroundStyle(.tertiary)
+
+ Text("No transfers yet")
+ .font(.subheadline)
+ .foregroundStyle(.tertiary)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 40)
+ }
+ }
+ .padding()
+ }
+ }
+
+ // MARK: - Transfer Row
+
+ private func transferRow(_ transfer: FileTransfer, isActive: Bool) -> some View {
+ HStack(spacing: 14) {
+ Image(systemName: fileIcon(for: transfer.filename))
+ .font(.title3)
+ .foregroundStyle(isActive ? .teal : .secondary)
+ .frame(width: 32)
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text(transfer.filename)
+ .font(.subheadline.weight(.medium))
+ .lineLimit(1)
+
+ if isActive && !transfer.failed {
+ ProgressView(value: transfer.progress)
+ .tint(.teal)
+
+ Text(formatBytes(transfer.bytesSent) + " / " + formatBytes(transfer.totalSize))
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ } else if transfer.failed {
+ Text("Failed")
+ .font(.caption)
+ .foregroundStyle(.red)
+ } else {
+ HStack(spacing: 4) {
+ Image(systemName: "checkmark.circle.fill")
+ .font(.caption2)
+ .foregroundStyle(.green)
+
+ Text(formatBytes(transfer.totalSize))
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ }
+ }
+ .padding(14)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 12))
+ }
+
+ // MARK: - Helpers
+
+ private func fileIcon(for filename: String) -> String {
+ let ext = (filename as NSString).pathExtension.lowercased()
+ switch ext {
+ case "png", "jpg", "jpeg", "gif", "webp", "heic":
+ return "photo"
+ case "mp4", "mov", "avi", "mkv":
+ return "film"
+ case "mp3", "wav", "flac", "aac":
+ return "music.note"
+ case "pdf":
+ return "doc.richtext"
+ case "zip", "tar", "gz", "7z":
+ return "archivebox"
+ case "txt", "md", "log":
+ return "doc.text"
+ default:
+ return "doc"
+ }
+ }
+
+ private func formatBytes(_ bytes: Int64) -> String {
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .file
+ return formatter.string(fromByteCount: bytes)
+ }
+}
+
+#Preview {
+ FilesView()
+ .environment(TetherViewModel())
+ .preferredColorScheme(.dark)
+}
diff --git a/apple/Tether/Views/PairingView.swift b/apple/Tether/Views/PairingView.swift
new file mode 100644
index 0000000..ec56383
--- /dev/null
+++ b/apple/Tether/Views/PairingView.swift
@@ -0,0 +1,125 @@
+//
+// PairingView.swift
+// Tether
+//
+// Sheet presented during the device pairing flow.
+//
+
+import SwiftUI
+
+struct PairingView: View {
+ @Environment(TetherViewModel.self) private var viewModel
+
+ @State private var rotationAngle: Double = 0
+
+ var body: some View {
+ NavigationStack {
+ VStack(spacing: 32) {
+ Spacer()
+
+ // Animated pairing icon
+ ZStack {
+ // Outer rotating ring
+ Circle()
+ .strokeBorder(
+ AngularGradient(
+ colors: [.teal, .teal.opacity(0.2), .teal],
+ center: .center
+ ),
+ lineWidth: 3
+ )
+ .frame(width: 100, height: 100)
+ .rotationEffect(.degrees(rotationAngle))
+
+ // Inner icon
+ Image(systemName: "lock.shield")
+ .font(.system(size: 36, weight: .medium))
+ .foregroundStyle(.teal)
+ }
+ .onAppear {
+ withAnimation(.linear(duration: 3).repeatForever(autoreverses: false)) {
+ rotationAngle = 360
+ }
+ }
+
+ // Status Text
+ VStack(spacing: 12) {
+ Text("Device Pairing")
+ .font(.title2.weight(.bold))
+
+ Text(viewModel.pairingStatus.isEmpty
+ ? "Initiating secure pairing…"
+ : viewModel.pairingStatus)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 32)
+ }
+
+ // Fingerprint Display
+ VStack(spacing: 8) {
+ Text("Your Device Fingerprint")
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ .textCase(.uppercase)
+
+ Text(formatFingerprint(viewModel.certificateManager.myFingerprint))
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8))
+ .textSelection(.enabled)
+ }
+
+ Spacer()
+
+ // Actions
+ VStack(spacing: 12) {
+ Button {
+ viewModel.confirmPairing()
+ } label: {
+ Text("I've Approved on Desktop")
+ .font(.body.weight(.semibold))
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 14)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(.teal)
+
+ Button {
+ viewModel.disconnect()
+ viewModel.showPairingSheet = false
+ } label: {
+ Text("Cancel")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(.horizontal, 24)
+ .padding(.bottom, 16)
+ }
+ .padding()
+ .navigationBarTitleDisplayMode(.inline)
+ }
+ .presentationDetents([.large])
+ .presentationDragIndicator(.visible)
+ }
+
+ // MARK: - Helpers
+
+ private func formatFingerprint(_ fp: String) -> String {
+ var result = ""
+ for (i, char) in fp.enumerated() {
+ if i > 0 && i % 2 == 0 { result += ":" }
+ result.append(char)
+ }
+ return result
+ }
+}
+
+#Preview {
+ PairingView()
+ .environment(TetherViewModel())
+ .preferredColorScheme(.dark)
+}
diff --git a/apple/Tether/Views/SettingsView.swift b/apple/Tether/Views/SettingsView.swift
new file mode 100644
index 0000000..6c0ebb7
--- /dev/null
+++ b/apple/Tether/Views/SettingsView.swift
@@ -0,0 +1,219 @@
+//
+// SettingsView.swift
+// Tether
+//
+// Device identity, paired devices list, and app information.
+//
+
+import SwiftUI
+
+struct SettingsView: View {
+ @Environment(TetherViewModel.self) private var viewModel
+
+ @State private var showDeleteConfirm = false
+ @State private var fingerprintToDelete: String?
+
+ var body: some View {
+ NavigationStack {
+ List {
+ // This Device
+ Section {
+ HStack(spacing: 14) {
+ ZStack {
+ RoundedRectangle(cornerRadius: 10)
+ .fill(
+ LinearGradient(
+ colors: [.teal, .teal.opacity(0.7)],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ .frame(width: 40, height: 40)
+
+ Image(systemName: "iphone")
+ .font(.body.weight(.medium))
+ .foregroundStyle(.white)
+ }
+
+ VStack(alignment: .leading, spacing: 2) {
+ #if canImport(UIKit)
+ Text(UIDevice.current.name)
+ .font(.body.weight(.medium))
+ #else
+ Text(Host.current().localizedName ?? "This Mac")
+ .font(.body.weight(.medium))
+ #endif
+
+ Text("This device")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+
+ if !viewModel.certificateManager.myFingerprint.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("TLS Fingerprint")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+
+ Text(formatFingerprint(viewModel.certificateManager.myFingerprint))
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.primary)
+ .textSelection(.enabled)
+ }
+ }
+ } header: {
+ Text("This Device")
+ }
+
+ // Paired Devices
+ Section {
+ if viewModel.certificateManager.knownHosts.isEmpty {
+ HStack {
+ Spacer()
+ VStack(spacing: 8) {
+ Image(systemName: "shield.slash")
+ .font(.title3)
+ .foregroundStyle(.tertiary)
+
+ Text("No paired devices")
+ .font(.subheadline)
+ .foregroundStyle(.tertiary)
+ }
+ .padding(.vertical, 20)
+ Spacer()
+ }
+ } else {
+ ForEach(
+ Array(viewModel.certificateManager.knownHosts.sorted(by: { $0.value < $1.value })),
+ id: \.key
+ ) { fingerprint, name in
+ HStack(spacing: 14) {
+ Image(systemName: "desktopcomputer")
+ .font(.title3)
+ .foregroundStyle(.teal)
+ .frame(width: 32)
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name)
+ .font(.body.weight(.medium))
+
+ Text(formatFingerprint(String(fingerprint.prefix(16))) + "…")
+ .font(.system(.caption2, design: .monospaced))
+ .foregroundStyle(.tertiary)
+ }
+
+ Spacer()
+ }
+ .swipeActions(edge: .trailing, allowsFullSwipe: true) {
+ Button(role: .destructive) {
+ fingerprintToDelete = fingerprint
+ showDeleteConfirm = true
+ } label: {
+ Label("Unpair", systemImage: "trash")
+ }
+ }
+ }
+ }
+ } header: {
+ Text("Paired Devices")
+ } footer: {
+ if !viewModel.certificateManager.knownHosts.isEmpty {
+ Text("Swipe left on a device to unpair it.")
+ }
+ }
+
+ // Connection
+ Section {
+ HStack {
+ Text("Status")
+ Spacer()
+ ConnectionStatusView(state: viewModel.appState)
+ }
+
+ if !viewModel.connection.serverFingerprint.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Server Fingerprint")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+
+ Text(formatFingerprint(viewModel.connection.serverFingerprint))
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.primary)
+ .textSelection(.enabled)
+ }
+ }
+ } header: {
+ Text("Connection")
+ }
+
+ // About
+ Section {
+ HStack {
+ Text("Version")
+ Spacer()
+ Text("1.0")
+ .foregroundStyle(.secondary)
+ }
+
+ HStack {
+ Text("Protocol")
+ Spacer()
+ Text("TCP + mTLS")
+ .foregroundStyle(.secondary)
+ }
+
+ HStack {
+ Text("Service Type")
+ Spacer()
+ Text("_tether._tcp")
+ .font(.system(.body, design: .monospaced))
+ .foregroundStyle(.secondary)
+ }
+
+ HStack {
+ Text("Daemon Port")
+ Spacer()
+ Text("5134")
+ .font(.system(.body, design: .monospaced))
+ .foregroundStyle(.secondary)
+ }
+ } header: {
+ Text("About")
+ }
+ }
+ .navigationTitle("Settings")
+ .confirmationDialog(
+ "Unpair Device",
+ isPresented: $showDeleteConfirm,
+ titleVisibility: .visible
+ ) {
+ Button("Unpair", role: .destructive) {
+ if let fp = fingerprintToDelete {
+ viewModel.certificateManager.removeKnownHost(fingerprint: fp)
+ }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("This device will need to be paired again to connect.")
+ }
+ }
+ }
+
+ // MARK: - Helpers
+
+ private func formatFingerprint(_ fp: String) -> String {
+ var result = ""
+ for (i, char) in fp.enumerated() {
+ if i > 0 && i % 2 == 0 { result += ":" }
+ result.append(char)
+ }
+ return result
+ }
+}
+
+#Preview {
+ SettingsView()
+ .environment(TetherViewModel())
+ .preferredColorScheme(.dark)
+}