findfamily-ios: live relay WebSocket with reliable delivery (#ws)
- Commit
bcd641f63124fe2cfcf97934b19339beefb5cbad- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 23:00 UTC (22 days ago)
- Parents
b79ee0a
What changed - New RelaySocket: one long-lived binary WebSocket to wss://api.maproj.org/api/ws, the same protocol the Android client speaks (SUB/PUB/MSG/GETKEY/KEYRESP), plus the server's opt-in reliable mode: SUB_RELIABLE [0x0D][ver][u64 userid][PQC bundle], SUB_ACK [0x10][ver][u16 idleSecs][u16 inflightMax], MSG_SEQ [0x0E][flags][u64 seq][ciphertext], cumulative ACK [0x0F][u64 seq]. Each pushed message is decrypted and stored first, then ACKed, so the server keeps (and requeues) anything we never confirmed. - RelayDedup: at-least-once means a frame whose ACK was lost comes back; repeats are dropped by SHA-256 of the ciphertext (exact, since every PQC seal has a fresh encapsulation and random IV). 512 recent hashes, persisted in UserDefaults so a kill between "stored" and "ACKed" does not duplicate rows/notifications on relaunch. Also applied to the HTTP drains. - Publish (location + UWB) goes out as PUB on the socket when it is subscribed and fresh (inbound within one ping interval + 10 s, since PUB has no server ACK); otherwise the HTTP publish_pqc path, unchanged. Peer key lookup (RelayKeyLookup, getPqcBundle) asks GETKEY on the live socket first, then falls back to the old one-shot socket / HTTP lookup. - Receive: pushes are fed into the same pipeline the HTTP poll used (BackgroundTask.handleIncomingLocations / handleIncomingUwb, moved out of runTick unchanged). runTick still polls HTTP receive_pqc and uwb/receive_pqc every tick while the socket is not subscribed, and RelaySocket does one HTTP drain per wake as a safety net. - Lifecycle: connect at launch (foreground), on didBecomeActive, when tracking starts, and on every location update/heartbeat tick (no-op when already up; a socket quiet for 2 ping intervals after a wake is replaced at once). Reconnect with 1 s -> 15 s backoff (Android's). Close cleanly (normalClosure, so the server requeues immediately) when tracking stops while backgrounded or the app backgrounds without tracking. Ping every idleSecs/3 (25 s for the server's 75 s default); 3 intervals with no frame or pong = half-open, reconnect. - Old server: no SUB_ACK within 10 s -> plain SUB on the same socket, legacy MSG frames, no ACKs. - Heartbeat/publish cadence is unchanged (3 s ticks). Why: the owner wants iOS on the WebSocket like Android, but only with delivery that survives half-open sockets (phone suspended, network switch), which plain WS MSG frames do not. The server side of the reliable mode is location_share_server feat/ws-ack (a825718). Verified (no Xcode on the build box, so): - swiftc 6.0.3 -parse of every touched file. - Type-check of RelaySocket.swift + RelayKeyLookup.swift against Linux Foundation plus stub UIKit/CryptoKit/OSLog modules and stubs of the app types they call: clean in Swift 5 and Swift 6 (strict concurrency) modes. - End to end: the real RelaySocket.swift (only URL/Host patched, PQC and DB stubbed) compiled on Linux, run against a local server built from feat/ws-ack: subscribe + SUB_ACK, ordered pushes, de-dup of a byte-identical redelivery, every frame ACKed (nothing requeued on close), offline backlog on reconnect, GETKEY on the live socket, PUB (uwb) to another user's queue, UWB push routing, 22 s idle with a 15 s server idle timeout and no reconnect, recovery from a 25 s frozen server (half-open). Against a pre-change server binary the 10 s plain-SUB fallback passes the same checks. - Not verified here: the iOS SDK itself. Linux corelibs never calls sendPing's pong handler (pings do reach the server), so the pong path and the rest of the device behaviour need a first build and a device run.
Diff
apple/FindFamily/FindFamilyiOS/App/AppDelegate.swift
diff --git a/apple/FindFamily/FindFamilyiOS/App/AppDelegate.swift b/apple/FindFamily/FindFamilyiOS/App/AppDelegate.swiftindex af39166294..fa0461ffb7 100644--- a/apple/FindFamily/FindFamilyiOS/App/AppDelegate.swift+++ b/apple/FindFamily/FindFamilyiOS/App/AppDelegate.swift@@ -19,6 +19,9 @@ final class AppDelegate: NSObject, UIApplicationDelegate { Task { @MainActor in // Kick off the network / identity layer. await Networking.shared.start()+ // One long-lived relay socket: connects now if we're in the foreground and+ // whenever the app becomes active (tracking and location wakes also start it).+ RelaySocket.shared.beginLifecycle() // Subscribe to sharing-state changes first so a toggle that fires // before the DB finishes loading is still picked up, then start // location work only when we're actually sharing with someone —
apple/FindFamily/FindFamilyiOS/Location/Location.swift
diff --git a/apple/FindFamily/FindFamilyiOS/Location/Location.swift b/apple/FindFamily/FindFamilyiOS/Location/Location.swiftindex 4382e55ba4..96541db37a 100644--- a/apple/FindFamily/FindFamilyiOS/Location/Location.swift+++ b/apple/FindFamily/FindFamilyiOS/Location/Location.swift@@ -83,6 +83,7 @@ final class LocationsHandler: ObservableObject { manager.stopMonitoringVisits() manager.allowsBackgroundLocationUpdates = false BackgroundTask.shared.stopHeartbeat()+ RelaySocket.shared.trackingStopped() logger.info("Stopped location updates (not sharing with anyone)") } @@ -107,6 +108,7 @@ final class LocationsHandler: ObservableObject { func startLocationUpdatesIfSharing() { if isSharingWithAnyone() { BackgroundTask.shared.startHeartbeat()+ RelaySocket.shared.wake() startLocationUpdates() } else { stopLocationUpdates()@@ -197,7 +199,13 @@ final class BackgroundTask { lastKnownLocation = nil } + /// Whether location tracking (the heartbeat) is running.+ var isHeartbeatRunning: Bool { heartbeatTask != nil }+ func onLocationUpdate(_ loc: CLLocation, sleep: Bool) {+ // Every location update / heartbeat tick may be the app waking from suspension:+ // make sure the relay socket is up (no-op when it already is).+ RelaySocket.shared.wake() lastKnownLocation = loc let now = Date() if !sleep && now.timeIntervalSince(lastUpdateAt) < Self.shareIntervalSeconds { return }@@ -264,52 +272,67 @@ final class BackgroundTask { _ = await Networking.shared.publishLocation(me, toLink: link) } - // 5. Receive incoming peer locations. Any sender we don't already know about- // is added as AWAITING_REQUEST (Modern-Apps uses received locations — not a- // separate `/api/request_sharing` endpoint — to discover incoming requests).- if let incoming = await Networking.shared.receiveLocations() {- let knownIds = Set(users.map { $0.id } + [Networking.shared.userid])- let newSenderIds = Set(incoming.map { $0.userid }).subtracting(knownIds)- for id in newSenderIds {- let user = User(- id: id, name: "ID \(Base26.encode(id))", photo: nil,- locationName: "Unknown Location", sendingEnabled: true,- requestStatus: .awaitingRequest, lastLocationChangeTime: Date(),- encryptionKey: nil- )- Database.shared.upsertUser(user)- NotificationsUtil.send(- title: Strings.notifSharingRequestTitle,- body: Strings.notifSharingRequestBody(Base26.encode(id)),- category: "SHARING_REQUEST"- )- }- for loc in incoming {- Database.shared.insertLocationValue(loc)- await updateUserLocationName(loc)- await maybeNotifyBatteryDrop(loc)- }+ // 5. Receive incoming peer locations. The relay socket pushes them as they arrive+ // (RelaySocket -> handleIncomingLocations); poll HTTP only while it is not+ // subscribed, so a socket outage degrades to the old per-tick polling.+ let socketLive = RelaySocket.shared.isSubscribed+ if !socketLive, let incoming = await Networking.shared.receiveLocations() {+ await handleIncomingLocations(incoming) } // 6. Trim old locations (>7 days). let cutoff = Date().addingTimeInterval(-7 * 24 * 60 * 60) Database.shared.deleteLocationValuesOlderThan(cutoff) - // 7. Drain the UWB session-setup channel. Each envelope is published- // onto UwbInbox so an open Precision Finding view can react; if the- // envelope is a REQUEST and no view is open, post a notification.- if let envelopes = await Networking.shared.receiveUwbMessages() {- for env in envelopes {- UwbInbox.shared.emit(env)- if env.kind == UwbEnvelopeKind.request {- let senderId = Int64(bitPattern: env.sender)- let senderName = Database.shared.user(id: senderId)?.name ?? "Someone"- NotificationsUtil.send(- title: "Precision Finding request",- body: "\(senderName) wants to find you with Precision Finding. Tap to begin.",- category: "UWB_REQUEST"- )- }+ // 7. Drain the UWB session-setup channel (same rule: socket pushes, HTTP fallback).+ if !socketLive, let envelopes = await Networking.shared.receiveUwbMessages() {+ handleIncomingUwb(envelopes)+ }+ }++ /// Stores incoming peer fixes — from the relay socket or an HTTP drain. Any sender we+ /// don't already know about is added as AWAITING_REQUEST (Modern-Apps uses received+ /// locations — not a separate `/api/request_sharing` endpoint — to discover incoming+ /// requests).+ func handleIncomingLocations(_ incoming: [LocationValue]) async {+ guard !incoming.isEmpty else { return }+ let users = Database.shared.usersSubject.value+ let knownIds = Set(users.map { $0.id } + [Networking.shared.userid])+ let newSenderIds = Set(incoming.map { $0.userid }).subtracting(knownIds)+ for id in newSenderIds {+ let user = User(+ id: id, name: "ID \(Base26.encode(id))", photo: nil,+ locationName: "Unknown Location", sendingEnabled: true,+ requestStatus: .awaitingRequest, lastLocationChangeTime: Date(),+ encryptionKey: nil+ )+ Database.shared.upsertUser(user)+ NotificationsUtil.send(+ title: Strings.notifSharingRequestTitle,+ body: Strings.notifSharingRequestBody(Base26.encode(id)),+ category: "SHARING_REQUEST"+ )+ }+ for loc in incoming {+ Database.shared.insertLocationValue(loc)+ await updateUserLocationName(loc)+ await maybeNotifyBatteryDrop(loc)+ }+ }++ /// Hands incoming UWB envelopes (relay socket or HTTP drain) to UwbInbox so an open+ /// Precision Finding view can react; a REQUEST with no view open posts a notification.+ func handleIncomingUwb(_ envelopes: [UwbEnvelope]) {+ for env in envelopes {+ UwbInbox.shared.emit(env)+ if env.kind == UwbEnvelopeKind.request {+ let senderId = Int64(bitPattern: env.sender)+ let senderName = Database.shared.user(id: senderId)?.name ?? "Someone"+ NotificationsUtil.send(+ title: "Precision Finding request",+ body: "\(senderName) wants to find you with Precision Finding. Tap to begin.",+ category: "UWB_REQUEST"+ ) } } }
apple/FindFamily/FindFamilyiOS/Networking/Networking.swift
diff --git a/apple/FindFamily/FindFamilyiOS/Networking/Networking.swift b/apple/FindFamily/FindFamilyiOS/Networking/Networking.swiftindex 414153d111..62091906da 100644--- a/apple/FindFamily/FindFamilyiOS/Networking/Networking.swift+++ b/apple/FindFamily/FindFamilyiOS/Networking/Networking.swift@@ -41,9 +41,10 @@ final class NetworkClient { /// and sealed layout [4B encapLen][encap][aes] (aes = [12B iv][ct||tag]), KDF SHA256(BE32(1)||Z). /// - Server parallel endpoints `/api/pqc/*` store PQC bundles separately from RSA. ///-/// This app is **post-quantum only**: it publishes to and receives from the `_pqc` endpoints+/// This app is **post-quantum only**: it publishes to and receives from the `_pqc` queues /// exclusively and never touches the classic RSA location/UWB queues, and it registers only a-/// PQC bundle. Android keeps its classic fallback for other peers, but it always prefers PQC+/// PQC bundle. Publish, receive and peer key lookup ride the relay socket (`RelaySocket`)+/// when it is up; the HTTP `_pqc` endpoints here remain the fallback. Android keeps its classic fallback for other peers, but it always prefers PQC /// when the peer has a bundle registered — which this app does on every launch. @MainActor final class Networking: ObservableObject {@@ -55,6 +56,8 @@ final class Networking: ObservableObject { private var pqcPublicBundleB64: String = "" private var pqcIdentity: PQCIdentity? var pqcAvailable: Bool { pqcIdentity != nil }+ /// Our public PQC bundle, sent with every relay-socket SUB (which doubles as registration).+ var pqcPublicBundle: Data? { pqcIdentity?.publicBundle } private var networkIsDown = false @@ -240,7 +243,15 @@ final class Networking: ObservableObject { /// Fetches peer PQC bundle, caches to DB, returns Data. func getPqcBundle(forUserid id: Int64) async -> Data? { guard pqcAvailable else { return nil }- if let data = await getPqcKeyRaw(forUserid: id) {+ // GETKEY on the live relay socket when it is up (no extra connection); otherwise+ // the HTTP lookup as before.+ var fetched: Data? = nil+ if let live = await RelaySocket.shared.getKey(userId: id), live.status == .pqc,+ let bundle = live.bundle, !bundle.isEmpty {+ fetched = bundle+ }+ if fetched == nil { fetched = await getPqcKeyRaw(forUserid: id) }+ if let data = fetched { // Overwrite rather than fill-only-if-empty, matching Android: this is only // reached when there was no cached bundle to prefer, and a stale value here // would keep us encrypting to a key the peer has already replaced. Written on@@ -288,6 +299,11 @@ final class Networking: ObservableObject { let json = try JSONEncoder().encode(location.toCompatible(senderPlatform: Self.platformTag)) // Encrypt via PQC (ML-KEM encaps + AES-GCM), same as Kotlin Pqc.encryptTo let sealed = try PQCKeyManager.shared.encryptTo(bundle: bundle, plaintext: json)+ // Relay socket first (PUB); HTTP when the socket is down or not fresh.+ if await RelaySocket.shared.publish(recipient: recipientID, isUwb: false, sealed: sealed) {+ print("publishEncryptedPqc to \(UInt64(bitPattern: recipientID)) via ws encLen=\(sealed.count)")+ return true+ } let body = encodeJSON([ "recipientUserID": .uint64(UInt64(bitPattern: recipientID)), "encryptedLocation": .string(sealed.base64EncodedString()),@@ -328,19 +344,10 @@ final class Networking: ObservableObject { print("receiveLocationsPqc: skipped non-base64") continue }- do {- let plain = try PQCKeyManager.shared.decrypt(sealed: sealed)- let comp = try JSONDecoder().decode(LocationValueCompatible.self, from: plain)- let loc = comp.toLocationValue()- out.append(loc)- if let platform = comp.senderPlatform,- let u = Database.shared.user(id: loc.userid),- u.platform != platform {- Database.shared.setPlatform(id: loc.userid, platform: platform)- }- } catch {- print("receiveLocationsPqc: decrypt/parse failure: \(error.localizedDescription)")- }+ // Already taken from the relay socket (a requeued un-ACKed frame).+ if RelayDedup.shared.contains(sealed) { continue }+ RelayDedup.shared.insert(sealed)+ if let loc = decodeLocation(sealed: sealed) { out.append(loc) } } print("receiveLocationsPqc: \(out.count) location(s) for userid=\(UInt64(bitPattern: userid))") return out@@ -350,6 +357,31 @@ final class Networking: ObservableObject { } } + /// Decrypts one sealed location (HTTP drain or relay-socket push) and records the+ /// sender's platform tag. Nil on decrypt/parse failure.+ func decodeLocation(sealed: Data) -> LocationValue? {+ do {+ let plain = try PQCKeyManager.shared.decrypt(sealed: sealed)+ let comp = try JSONDecoder().decode(LocationValueCompatible.self, from: plain)+ let loc = comp.toLocationValue()+ if let platform = comp.senderPlatform,+ let u = Database.shared.user(id: loc.userid),+ u.platform != platform {+ Database.shared.setPlatform(id: loc.userid, platform: platform)+ }+ return loc+ } catch {+ print("decodeLocation: decrypt/parse failure: \(error.localizedDescription)")+ return nil+ }+ }++ /// Decrypts one sealed UWB envelope (HTTP drain or relay-socket push).+ func decodeUwb(sealed: Data) -> UwbEnvelope? {+ guard let plain = try? PQCKeyManager.shared.decrypt(sealed: sealed) else { return nil }+ return try? JSONDecoder().decode(UwbEnvelope.self, from: plain)+ }+ // MARK: - UWB session-setup channel (post-quantum only) /// Publishes [envelope] to [recipientID] via the peer's PQC bundle. Returns false if the peer@@ -376,6 +408,10 @@ final class Networking: ObservableObject { do { let json = try JSONEncoder().encode(envelope) let sealed = try PQCKeyManager.shared.encryptTo(bundle: bundle, plaintext: json)+ if await RelaySocket.shared.publish(recipient: recipientID, isUwb: true, sealed: sealed) {+ print("publishUwbMessagePqc to \(UInt64(bitPattern: recipientID)) via ws")+ return true+ } let body = encodeJSON([ "recipientUserID": .uint64(UInt64(bitPattern: recipientID)), "encryptedLocation": .string(sealed.base64EncodedString()),@@ -406,10 +442,9 @@ final class Networking: ObservableObject { var out: [UwbEnvelope] = [] for b64 in arr { guard let sealed = Data(base64Encoded: b64) else { continue }- if let plain = try? PQCKeyManager.shared.decrypt(sealed: sealed),- let env = try? JSONDecoder().decode(UwbEnvelope.self, from: plain) {- out.append(env)- }+ if RelayDedup.shared.contains(sealed) { continue }+ RelayDedup.shared.insert(sealed)+ if let env = decodeUwb(sealed: sealed) { out.append(env) } } return out } catch {
apple/FindFamily/FindFamilyiOS/Networking/RelayKeyLookup.swift
diff --git a/apple/FindFamily/FindFamilyiOS/Networking/RelayKeyLookup.swift b/apple/FindFamily/FindFamilyiOS/Networking/RelayKeyLookup.swiftindex 2f93248b17..58ecba8f1e 100644--- a/apple/FindFamily/FindFamilyiOS/Networking/RelayKeyLookup.swift+++ b/apple/FindFamily/FindFamilyiOS/Networking/RelayKeyLookup.swift@@ -9,11 +9,11 @@ import Foundation /// /// status: 0 = not registered, 1 = classic key only (outdated app), 2 = PQC bundle follows. ///-/// One request/response per connection, and deliberately **no SUB frame**. SUB is what-/// makes the relay treat a socket as a live subscriber and fan that user's locations out-/// to it instead of the queue that `/api/location/receive_pqc` drains — which this app-/// still polls. Without SUB the socket is inert apart from this exchange, so the HTTP-/// receive path is untouched.+/// Asked on the app's live relay socket (`RelaySocket`) when it is subscribed. Otherwise+/// one request/response on a throwaway connection, deliberately with **no SUB frame**:+/// SUB is what makes the relay treat a socket as a live subscriber and fan that user's+/// locations out to it instead of the queue, so a SUB here would steal pushes from the+/// real socket. Without SUB the throwaway socket is inert apart from this exchange. /// /// Replaces the two-request HTTP probe (`/api/pqc/getkey` then `/api/getkey`): one frame /// returns the status *and* the bundle together, so there is no window between deciding a@@ -43,6 +43,7 @@ enum RelayKeyLookup { /// Looks up `userId`'s key. Returns nil when the socket can't be established or the /// reply doesn't arrive in time; callers treat that as "unknown" rather than "absent". static func getKey(userId: Int64) async -> KeyResult? {+ if let live = await RelaySocket.shared.getKey(userId: userId) { return live } let session = URLSession(configuration: .ephemeral) let task = session.webSocketTask(with: url) task.resume()@@ -83,13 +84,19 @@ enum RelayKeyLookup { /// Parses `[0x05][status][u64 target][bundle…]`, or nil if this isn't the KEYRESP for /// `target`. private static func parse(_ frame: Data, target: Int64) -> KeyResult? {+ guard let reply = parseAny(frame), reply.target == target else { return nil }+ return reply.result+ }++ /// Parses any KEYRESP `[0x05][status][u64 target][bundle…]` into its target and result+ /// (shared with `RelaySocket`, which matches replies to its pending lookups).+ static func parseAny(_ frame: Data) -> (target: Int64, result: KeyResult)? { let bytes = [UInt8](frame) guard bytes.count >= 10, bytes[0] == opGetKeyResponse, let status = Status(rawValue: bytes[1]) else { return nil } var echoed: UInt64 = 0 for i in 0..<8 { echoed = (echoed << 8) | UInt64(bytes[2 + i]) }- guard Int64(bitPattern: echoed) == target else { return nil } let bundle = bytes.count > 10 ? Data(bytes[10...]) : nil- return KeyResult(status: status, bundle: bundle)+ return (Int64(bitPattern: echoed), KeyResult(status: status, bundle: bundle)) } }
apple/FindFamily/FindFamilyiOS/Networking/RelaySocket.swift
diff --git a/apple/FindFamily/FindFamilyiOS/Networking/RelaySocket.swift b/apple/FindFamily/FindFamilyiOS/Networking/RelaySocket.swiftnew file mode 100644index 0000000000..e9a741f035--- /dev/null+++ b/apple/FindFamily/FindFamilyiOS/Networking/RelaySocket.swift@@ -0,0 +1,458 @@+import Foundation+import CryptoKit+import OSLog+import UIKit++private let relayLog = Logger(subsystem: "cc.findfamily.ios.swift", category: "Relay")++/// The one long-lived relay socket (`wss://api.maproj.org/api/ws`), mirroring the Android+/// client (`Networking.kt` + `NetworkingLive.kt`) plus the server's reliable-delivery mode:+///+/// client→server SUB_RELIABLE : [0x0D][u8 version=1][u64 userid][PQC bundle…]+/// server→client SUB_ACK : [0x10][u8 version][u16 idleTimeoutSecs][u16 inflightMax]+/// server→client MSG_SEQ : [0x0E][flags][u64 seq][ciphertext…]+/// client→server ACK : [0x0F][u64 seq] (cumulative)+/// client→server PUB : [0x02][flags][u64 recipient][ciphertext…]+/// client→server GETKEY : [0x04][u64 target]+/// server→client KEYRESP : [0x05][status][u64 target][bundle…]+/// legacy fallback : SUB [0x01][u64 userid][bundle…] / MSG [0x03][flags][ciphertext…]+///+/// All integers big-endian; flags bit0 = UWB envelope (else location).+///+/// Reliability contract (server side in location_share_server `findfamily.rs`): every+/// MSG_SEQ stays on the server until we ACK it, and is requeued if the socket dies first.+/// So each frame is ACKed only after it has been decrypted and stored, and a frame can+/// arrive twice (ACK lost in a disconnect); `RelayDedup` drops repeats by ciphertext hash.+///+/// The HTTP `/api/location/receive_pqc` + `/api/uwb/receive_pqc` drain is kept as a safety+/// net: once per wake, and on every heartbeat tick while the socket is not subscribed.+@MainActor+final class RelaySocket {+ static let shared = RelaySocket()++ private static let url = URL(string: "wss://api.maproj.org/api/ws")!++ private static let opSub: UInt8 = 0x01+ private static let opPub: UInt8 = 0x02+ private static let opMsg: UInt8 = 0x03+ private static let opGetKeyRequest: UInt8 = 0x04+ private static let opGetKeyResponse: UInt8 = 0x05+ private static let opSubReliable: UInt8 = 0x0D+ private static let opMsgSeq: UInt8 = 0x0E+ private static let opAck: UInt8 = 0x0F+ private static let opSubAck: UInt8 = 0x10+ private static let reliableVersion: UInt8 = 1+ private static let flagUwb: UInt8 = 0x01++ /// No SUB_ACK within this window means an older server that ignores 0x0D: fall back+ /// to a plain SUB (no ACKs) on the same socket.+ private static let subAckTimeout: TimeInterval = 10+ /// Matches the Android client's GETKEY timeout.+ private static let keyTimeout: TimeInterval = 5+ /// Matches Android's reconnect backoff (1 s → 15 s).+ private static let backoffInitial: TimeInterval = 1+ private static let backoffMax: TimeInterval = 15+ /// Ping cadence until SUB_ACK says otherwise: the server's 75 s idle timeout / 3.+ private static let defaultPingInterval: TimeInterval = 25+ /// A wake this long after the previous one means the app was suspended in between.+ private static let wakeGap: TimeInterval = 30++ private let session: URLSession++ private var loopTask: Task<Void, Never>?+ private var loopID = 0+ private var wantRunning = false++ /// The connected socket, if any.+ private var task: URLSessionWebSocketTask?+ /// True once the server accepted our subscription (SUB_ACK, or the legacy fallback SUB).+ private(set) var isSubscribed = false+ /// True when the server confirmed reliable mode (MSG_SEQ + ACK).+ private var reliable = false+ private var legacyFallbackSent = false+ private var pingInterval: TimeInterval = RelaySocket.defaultPingInterval+ /// Last time anything (frame or pong) arrived on the current socket.+ private var lastInboundAt = Date.distantPast+ /// Keepalive for the current socket; started once subscribed, so it uses the interval+ /// the server advertised in SUB_ACK from the first ping.+ private var pingTask: Task<Void, Never>?++ private var lastWakeAt = Date.distantPast+ private var httpDrainInFlight = false+ private var lifecycleObservers: [NSObjectProtocol] = []++ /// Outstanding GETKEYs on the live socket, keyed by target userid.+ private var pendingKeys: [Int64: AsyncStream<RelayKeyLookup.KeyResult?>.Continuation] = [:]++ private init() {+ let cfg = URLSessionConfiguration.default+ // Surface "offline" as a failed connect (handled by backoff) instead of parking+ // the handshake until connectivity returns.+ cfg.waitsForConnectivity = false+ // Pongs every pingInterval keep traffic flowing well inside this.+ cfg.timeoutIntervalForRequest = 120+ self.session = URLSession(configuration: cfg)+ }++ // MARK: - Lifecycle++ /// Called once after `Networking.start()`: connect now if the app is in the+ /// foreground, connect whenever it becomes active, and close cleanly when it goes to+ /// the background without location tracking (iOS would suspend it anyway; a clean+ /// close lets the server requeue at once instead of after its idle timeout).+ func beginLifecycle() {+ guard lifecycleObservers.isEmpty else { return }+ let center = NotificationCenter.default+ lifecycleObservers.append(center.addObserver(+ forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main+ ) { _ in+ Task { @MainActor in RelaySocket.shared.wake() }+ })+ lifecycleObservers.append(center.addObserver(+ forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main+ ) { _ in+ Task { @MainActor in+ if !BackgroundTask.shared.isHeartbeatRunning { RelaySocket.shared.stop() }+ }+ })+ if UIApplication.shared.applicationState != .background {+ wake()+ }+ }++ /// Any sign of life: app became active, tracking started, a location update or+ /// heartbeat tick. Cheap when already connected. Starts the socket if needed, forces+ /// a reconnect if the current one has gone quiet (typical after suspension), and runs+ /// one HTTP drain per wake as a safety net.+ func wake() {+ guard Networking.shared.isReady, Networking.shared.pqcAvailable else { return }+ let now = Date()+ if now.timeIntervalSince(lastWakeAt) > Self.wakeGap {+ drainHttpOnce()+ }+ lastWakeAt = now+ if let task, isSubscribed, now.timeIntervalSince(lastInboundAt) > pingInterval * 2 {+ relayLog.notice("socket quiet for \(Int(now.timeIntervalSince(self.lastInboundAt)))s on wake; reconnecting")+ task.cancel(with: .goingAway, reason: nil)+ }+ start()+ }++ /// Location tracking stopped (not sharing with anyone). Keep the socket unless the app+ /// is in the background, so the map stays live on screen. Checks `.background` rather+ /// than `!= .active`: at a cold start the sharing gate runs while the app is still+ /// `.inactive`, possibly after `didBecomeActive` already fired.+ func trackingStopped() {+ guard UIApplication.shared.applicationState == .background else { return }+ stop()+ }++ func start() {+ guard Networking.shared.isReady, Networking.shared.pqcAvailable else { return }+ wantRunning = true+ guard loopTask == nil else { return }+ loopID += 1+ let id = loopID+ loopTask = Task { [weak self] in+ await self?.runLoop()+ if self?.loopID == id { self?.loopTask = nil }+ }+ }++ /// Closes the socket cleanly (the server then requeues anything we did not ACK).+ func stop() {+ wantRunning = false+ loopID += 1+ loopTask?.cancel()+ loopTask = nil+ if let task {+ task.cancel(with: .normalClosure, reason: nil)+ teardown(task)+ }+ }++ // MARK: - Connection loop++ private func runLoop() async {+ var backoff = Self.backoffInitial+ while wantRunning && !Task.isCancelled {+ let subscribed = await runOneConnection()+ if !wantRunning || Task.isCancelled { break }+ if subscribed { backoff = Self.backoffInitial }+ try? await Task.sleep(nanoseconds: UInt64(backoff * 1_000_000_000))+ backoff = min(backoff * 2, Self.backoffMax)+ }+ }++ /// One socket from connect to death. Returns whether it got subscribed.+ private func runOneConnection() async -> Bool {+ let task = session.webSocketTask(with: Self.url)+ self.task = task+ isSubscribed = false+ reliable = false+ legacyFallbackSent = false+ pingInterval = Self.defaultPingInterval+ lastInboundAt = Date()+ task.resume()++ var everSubscribed = false+ defer { teardown(task) }++ guard (try? await task.send(.data(subscribeFrame(op: Self.opSubReliable)))) != nil else {+ return false+ }+ let fallback = Task { [weak self] in+ guard let self else { return }+ await self.legacyFallbackIfNoSubAck(task)+ }+ defer { fallback.cancel() }++ do {+ while true {+ let message = try await task.receive()+ lastInboundAt = Date()+ guard case .data(let frame) = message else { continue }+ await handle(frame, on: task)+ if isSubscribed { everSubscribed = true }+ }+ } catch {+ relayLog.notice("relay socket ended: \(error.localizedDescription)")+ }+ return everSubscribed+ }++ /// Clears per-socket state, but only if `task` is still the current socket (a stop()+ /// followed by start() may already have replaced it).+ private func teardown(_ task: URLSessionWebSocketTask) {+ guard self.task === task else { return }+ task.cancel(with: .goingAway, reason: nil)+ self.task = nil+ pingTask?.cancel()+ pingTask = nil+ isSubscribed = false+ reliable = false+ for (_, waiter) in pendingKeys { waiter.finish() }+ pendingKeys.removeAll()+ }++ /// Pings every `pingInterval` (the server closes reliable sockets after 3 silent+ /// intervals) and, like Android's supervisor, treats 3 intervals without any inbound+ /// frame or pong as a half-open socket and forces a reconnect.+ private func pingLoop(_ task: URLSessionWebSocketTask) async {+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: UInt64(pingInterval * 1_000_000_000))+ if Task.isCancelled || self.task !== task { return }+ task.sendPing { error in+ guard error == nil else { return }+ Task { @MainActor in+ if RelaySocket.shared.task === task { RelaySocket.shared.lastInboundAt = Date() }+ }+ }+ let idle = Date().timeIntervalSince(lastInboundAt)+ if idle > pingInterval * 3 {+ relayLog.notice("no inbound for \(Int(idle))s; socket half-open, reconnecting")+ task.cancel(with: .goingAway, reason: nil)+ return+ }+ }+ }++ private func legacyFallbackIfNoSubAck(_ task: URLSessionWebSocketTask) async {+ try? await Task.sleep(nanoseconds: UInt64(Self.subAckTimeout * 1_000_000_000))+ guard !Task.isCancelled, self.task === task, !isSubscribed else { return }+ relayLog.notice("no SUB_ACK; server predates reliable mode, falling back to plain SUB")+ legacyFallbackSent = true+ guard (try? await task.send(.data(subscribeFrame(op: Self.opSub)))) != nil else { return }+ if self.task === task { markSubscribed(reliable: false, on: task) }+ }++ private func markSubscribed(reliable: Bool, on task: URLSessionWebSocketTask) {+ self.reliable = reliable+ isSubscribed = true+ lastInboundAt = Date()+ pingTask?.cancel()+ pingTask = Task { [weak self] in+ guard let self else { return }+ await self.pingLoop(task)+ }+ relayLog.info("relay subscribed reliable=\(reliable) ping=\(Int(self.pingInterval))s")+ }++ // MARK: - Frames++ /// `[op][(version)][u64 userid][PQC bundle…]` — SUB doubles as registration.+ private func subscribeFrame(op: UInt8) -> Data {+ var frame = Data([op])+ if op == Self.opSubReliable { frame.append(Self.reliableVersion) }+ Self.appendU64(&frame, UInt64(bitPattern: Networking.shared.userid))+ if let bundle = Networking.shared.pqcPublicBundle { frame.append(bundle) }+ return frame+ }++ private func handle(_ frame: Data, on task: URLSessionWebSocketTask) async {+ let bytes = [UInt8](frame)+ guard let op = bytes.first else { return }+ switch op {+ case Self.opSubAck:+ // [0x10][version][u16 idleSecs][u16 inflightMax]+ guard bytes.count >= 6, !legacyFallbackSent else { return }+ let idle = TimeInterval(Self.readU16(bytes, 2))+ if idle > 0 { pingInterval = min(max(idle / 3, 5), 60) }+ markSubscribed(reliable: true, on: task)+ case Self.opMsgSeq:+ // [0x0E][flags][u64 seq][ciphertext…]+ guard bytes.count >= 10 else { return }+ let seq = Self.readU64(bytes, 2)+ await deliver(Data(bytes[10...]), isUwb: bytes[1] & Self.flagUwb != 0)+ // ACK only after the payload is processed and stored: an ACK is the server's+ // licence to forget the frame.+ var ack = Data([Self.opAck])+ Self.appendU64(&ack, seq)+ try? await task.send(.data(ack))+ case Self.opMsg:+ // Legacy fallback: [0x03][flags][ciphertext…], no ACK.+ guard bytes.count >= 2 else { return }+ await deliver(Data(bytes[2...]), isUwb: bytes[1] & Self.flagUwb != 0)+ case Self.opGetKeyResponse:+ guard let reply = RelayKeyLookup.parseAny(frame) else { return }+ pendingKeys.removeValue(forKey: reply.target)?.yield(reply.result)+ default:+ break+ }+ }++ /// Decrypts and hands one pushed payload to the same pipeline the HTTP drain feeds.+ /// A repeat (redelivered after a lost ACK) is skipped but still ACKed by the caller.+ private func deliver(_ sealed: Data, isUwb: Bool) async {+ if RelayDedup.shared.contains(sealed) { return }+ if isUwb {+ if let env = Networking.shared.decodeUwb(sealed: sealed) {+ BackgroundTask.shared.handleIncomingUwb([env])+ }+ } else if let loc = Networking.shared.decodeLocation(sealed: sealed) {+ await BackgroundTask.shared.handleIncomingLocations([loc])+ }+ // Recorded even when decryption failed: a byte-identical retry fails the same way.+ RelayDedup.shared.insert(sealed)+ }++ // MARK: - Requests++ /// Sends an already-sealed payload as PUB. False when there is no fresh subscribed+ /// socket — the caller then publishes over HTTP. PUB has no server acknowledgement, so+ /// a socket that has been quiet longer than one ping interval (+10 s) is not trusted.+ func publish(recipient: Int64, isUwb: Bool, sealed: Data) async -> Bool {+ guard let task, isSubscribed,+ Date().timeIntervalSince(lastInboundAt) < pingInterval + 10 else { return false }+ var frame = Data([Self.opPub, isUwb ? Self.flagUwb : 0])+ Self.appendU64(&frame, UInt64(bitPattern: recipient))+ frame.append(sealed)+ do {+ try await task.send(.data(frame))+ return true+ } catch {+ return false+ }+ }++ /// GETKEY over the live socket. Nil when there is no subscribed socket, another+ /// lookup for the same target is in flight, or no reply within the timeout.+ func getKey(userId: Int64) async -> RelayKeyLookup.KeyResult? {+ guard let task, isSubscribed, pendingKeys[userId] == nil else { return nil }+ let (stream, continuation) = AsyncStream<RelayKeyLookup.KeyResult?>.makeStream()+ pendingKeys[userId] = continuation+ defer {+ pendingKeys.removeValue(forKey: userId)?.finish()+ }+ var request = Data([Self.opGetKeyRequest])+ Self.appendU64(&request, UInt64(bitPattern: userId))+ guard (try? await task.send(.data(request))) != nil else { return nil }+ let timeout = Self.keyTimeout+ return await withTaskGroup(of: RelayKeyLookup.KeyResult?.self) { group in+ group.addTask {+ for await result in stream { return result }+ return nil+ }+ group.addTask {+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))+ return nil+ }+ let first = await group.next() ?? nil+ group.cancelAll()+ return first+ }+ }++ // MARK: - HTTP safety net++ /// One HTTP drain of both PQC queues, fed into the same pipeline as socket pushes.+ private func drainHttpOnce() {+ guard !httpDrainInFlight else { return }+ httpDrainInFlight = true+ Task {+ if let locations = await Networking.shared.receiveLocations(), !locations.isEmpty {+ await BackgroundTask.shared.handleIncomingLocations(locations)+ }+ if let envelopes = await Networking.shared.receiveUwbMessages(), !envelopes.isEmpty {+ BackgroundTask.shared.handleIncomingUwb(envelopes)+ }+ self.httpDrainInFlight = false+ }+ }++ // MARK: - Byte helpers++ private static func appendU64(_ data: inout Data, _ value: UInt64) {+ withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) }+ }++ private static func readU64(_ bytes: [UInt8], _ offset: Int) -> UInt64 {+ var value: UInt64 = 0+ for i in 0..<8 { value = (value << 8) | UInt64(bytes[offset + i]) }+ return value+ }++ private static func readU16(_ bytes: [UInt8], _ offset: Int) -> UInt16 {+ (UInt16(bytes[offset]) << 8) | UInt16(bytes[offset + 1])+ }+}++/// Recently processed relay payloads, by ciphertext hash, so a frame redelivered after a+/// lost ACK (or also drained over HTTP) is not stored or notified twice. Exact: every PQC+/// seal has a fresh ML-KEM encapsulation and random IV, so equal bytes == same message.+/// Persisted so a kill between "stored" and "ACKed" does not duplicate on relaunch.+@MainActor+final class RelayDedup {+ static let shared = RelayDedup()++ private static let defaultsKey = "relaySeenPayloads_v1"+ private static let capacity = 512++ private var order: [String]+ private var seen: Set<String>++ private init() {+ order = UserDefaults.standard.stringArray(forKey: Self.defaultsKey) ?? []+ seen = Set(order)+ }++ private static func digest(_ payload: Data) -> String {+ Data(Array(SHA256.hash(data: payload)).prefix(16)).base64EncodedString()+ }++ func contains(_ payload: Data) -> Bool {+ seen.contains(Self.digest(payload))+ }++ func insert(_ payload: Data) {+ let d = Self.digest(payload)+ guard seen.insert(d).inserted else { return }+ order.append(d)+ if order.count > Self.capacity {+ let overflow = order.count - Self.capacity+ for old in order.prefix(overflow) { seen.remove(old) }+ order.removeFirst(overflow)+ }+ UserDefaults.standard.set(order, forKey: Self.defaultsKey)+ }+}
apple/FindFamily/FindFamilyiOS/UWB/UwbInbox.swift
diff --git a/apple/FindFamily/FindFamilyiOS/UWB/UwbInbox.swift b/apple/FindFamily/FindFamilyiOS/UWB/UwbInbox.swiftindex afadac2a9f..778ecba6ff 100644--- a/apple/FindFamily/FindFamilyiOS/UWB/UwbInbox.swift+++ b/apple/FindFamily/FindFamilyiOS/UWB/UwbInbox.swift@@ -3,8 +3,9 @@ import Combine /// Process-global UWB envelope inbox. ///-/// Producer: [BackgroundTask] drains `/api/uwb/receive` once per heartbeat-/// tick (every ~3 s when foregrounded) and forwards each envelope here.+/// Producer: [BackgroundTask.handleIncomingUwb], fed by relay-socket pushes+/// ([RelaySocket]) and by the HTTP `/api/uwb/receive_pqc` drain (once per wake,+/// and every heartbeat tick while the socket is down). /// /// Consumer: [RangingSession] subscribes while the Precision Finding screen /// is open to drive the WaitingForPeer handshake. When the view isn't alive