Modern Apps git

← Modern-Apps.git

various fixes

Commit
083b976482355a78c8992c411d27b1e6ca622aa2
Author
Vayun Mathur <[email protected]>
When
2026-08-25 17:56 UTC (3 months ago)
Parents
898a90d

Diff

FindFamilyiOS/Crypto/Crypto.swift
diff --git a/FindFamilyiOS/Crypto/Crypto.swift b/FindFamilyiOS/Crypto/Crypto.swiftindex e60eea816a..5255c22f31 100644--- a/FindFamilyiOS/Crypto/Crypto.swift+++ b/FindFamilyiOS/Crypto/Crypto.swift@@ -129,3 +129,70 @@ extension Int64 {     /// Convenience: `myId.base26`.     var base26: String { Base26.encode(self) } }++// MARK: - Invite fingerprint++/// Short fingerprint of a public bundle, small enough to ride in an invite link.+/// Byte-identical to Kotlin `InviteFingerprint`.+///+/// A PQC bundle is ~3.1 kB, so the key itself cannot travel in a URL. An invite carries+/// this truncated digest instead; the recipient still fetches the full bundle from the+/// relay and checks that it hashes to what the link said, which removes the relay's+/// ability to substitute a key of its own. The user id is hashed in so a fingerprint+/// lifted from one invite cannot be presented as another user's.+///+/// Cross-platform test vectors, asserted on the Android side in `InviteFingerprintTest`+/// (`matches_the_cross_platform_test_vector`). With `publicBundle` = 3184 bytes where+/// byte *i* is `i % 256`:+///+///     userId  12345  ->  "iXVzYL2J4imtjXPgh-dmtw"+///     userId     -2  ->  "rjnCvl7blekCiZv2q9QJOA"+///+/// A link minted on one platform has to verify on the other, so changing the domain+/// string, the id width, or `length` here breaks live invites in both directions.+enum InviteFingerprint {+    /// Truncated digest length. 16 bytes encodes to 22 unpadded base64url characters.+    static let length = 16++    private static let domain = "ff-invite-v1"++    /// `SHA-256(domain || u64be(userId) || publicBundle)`, truncated to `length`.+    static func compute(userId: Int64, publicBundle: Data) -> Data {+        var input = Data(domain.utf8)+        // Big-endian over the *bit pattern*, so a negative id hashes to the same bytes+        // the Kotlin side produces for the matching ULong.+        withUnsafeBytes(of: UInt64(bitPattern: userId).bigEndian) { input.append(contentsOf: $0) }+        input.append(publicBundle)+        return Data(SecurityCodeFormat.sha256(input).prefix(length))+    }++    /// The `k=` value of a share link: unpadded base64url.+    static func encode(userId: Int64, publicBundle: Data) -> String {+        base64urlEncode(compute(userId: userId, publicBundle: publicBundle))+    }++    /// Whether `publicBundle` is the one `expected` (unpadded base64url) names. A+    /// malformed or truncated value fails rather than being skipped, so a mangled link+    /// counts as unverified instead of silently trusting whatever the relay returned.+    static func matches(userId: Int64, publicBundle: Data, expected: String) -> Bool {+        guard let want = base64urlDecode(expected), want.count == length else { return false }+        return want == compute(userId: userId, publicBundle: publicBundle)+    }++    static func base64urlEncode(_ data: Data) -> String {+        data.base64EncodedString()+            .replacingOccurrences(of: "+", with: "-")+            .replacingOccurrences(of: "/", with: "_")+            .replacingOccurrences(of: "=", with: "")+    }++    static func base64urlDecode(_ s: String) -> Data? {+        var b64 = s+            .replacingOccurrences(of: "-", with: "+")+            .replacingOccurrences(of: "_", with: "/")+        // Data(base64Encoded:) rejects unpadded input, and links carry it unpadded.+        let remainder = b64.count % 4+        if remainder != 0 { b64 += String(repeating: "=", count: 4 - remainder) }+        return Data(base64Encoded: b64)+    }+}
FindFamilyiOS/Networking/Networking.swift
diff --git a/FindFamilyiOS/Networking/Networking.swift b/FindFamilyiOS/Networking/Networking.swiftindex a8e70ee9cc..63351b37a4 100644--- a/FindFamilyiOS/Networking/Networking.swift+++ b/FindFamilyiOS/Networking/Networking.swift@@ -140,46 +140,65 @@ final class Networking: ObservableObject {         return await registerPqc()     } -    /// Whether the server holds a *classic* (RSA) key for [id]. Used only to detect peers on an-    /// outdated, pre-quantum app — FindFamily never encrypts with RSA anymore.-    func hasClassicKey(forUserid id: Int64) async -> Bool {-        let body = Data(#"{"userid": \#(UInt64(bitPattern: id))}"#.utf8)-        do {-            let (data, http) = try await client.postJSON(path: "/api/getkey", jsonBody: body)-            networkIsDown = false-            return http.statusCode == 200 && !data.isEmpty-        } catch {-            checkNetworkDown(error)-            return false-        }-    }--    /// Whether the server holds a *PQC* bundle for [id] (independent of this device's PQC-    /// availability, unlike [getPqcKeyRaw]). Used for peer-capability detection.-    private func serverHasPqcKey(forUserid id: Int64) async -> Bool {-        let body = Data(#"{"userid": \#(UInt64(bitPattern: id))}"#.utf8)-        do {-            let (data, http) = try await client.postJSON(path: "/api/pqc/getkey", jsonBody: body)-            networkIsDown = false-            return http.statusCode == 200 && !data.isEmpty-        } catch {-            checkNetworkDown(error)-            return false-        }-    }-     /// Post-quantum capability of a peer, used to gate connecting/sharing.     enum PeerCrypto {         case pqc          // peer has a PQC bundle — sharing works         case needsUpdate  // peer has only a classic key — outdated app, must update         case unknown      // not registered, or the lookup failed (offline)+        case keyMismatch  // the relay's bundle doesn't match the invite link's fingerprint+    }++    /// Outcome of the connect-time key check. `verifiedBundleB64` is set only when an+    /// invite fingerprint was supplied and matched, and is meant to go straight onto the+    /// `User` row being created — pinning the key that was checked, so `resolvedPqcBundle`+    /// prefers it and a later lookup can't swap in one the fingerprint never covered.+    struct PeerKeyCheck {+        let status: PeerCrypto+        let verifiedBundleB64: String?+    }++    /// Checks a peer's PQC capability "when connecting", over the relay socket. A PQC+    /// bundle → `.pqc`; only a classic key → `.needsUpdate` (show the update prompt);+    /// neither, or the lookup failed → `.unknown`.+    ///+    /// `expectedFingerprint` is the `k=` value of the invite link this came from, when+    /// there was one. The relay's bundle has to hash to it, or the result is+    /// `.keyMismatch` — this is what stops the relay handing out a key it controls+    /// instead of the sender's.+    func peerCryptoStatus(forUserid id: Int64, expectedFingerprint: String? = nil) async -> PeerKeyCheck {+        guard let res = await RelayKeyLookup.getKey(userId: id) else {+            return PeerKeyCheck(status: .unknown, verifiedBundleB64: nil)+        }+        switch res.status {+        case .pqc:+            guard let expected = expectedFingerprint else {+                return PeerKeyCheck(status: .pqc, verifiedBundleB64: nil)+            }+            guard let bundle = res.bundle, !bundle.isEmpty else {+                return PeerKeyCheck(status: .unknown, verifiedBundleB64: nil)+            }+            guard InviteFingerprint.matches(userId: id, publicBundle: bundle, expected: expected) else {+                print("Networking: invite fingerprint mismatch for \(UInt64(bitPattern: id))")+                return PeerKeyCheck(status: .keyMismatch, verifiedBundleB64: nil)+            }+            return PeerKeyCheck(status: .pqc, verifiedBundleB64: bundle.base64EncodedString())+        case .classic:+            return PeerKeyCheck(status: .needsUpdate, verifiedBundleB64: nil)+        case .noKey:+            return PeerKeyCheck(status: .unknown, verifiedBundleB64: nil)+        }     } -    /// Checks a peer's PQC capability "when connecting": a PQC bundle present → `.pqc`; only a-    /// classic key → `.needsUpdate` (show the update prompt); neither → `.unknown`.-    func peerCryptoStatus(forUserid id: Int64) async -> PeerCrypto {-        if await serverHasPqcKey(forUserid: id) { return .pqc }-        return await hasClassicKey(forUserid: id) ? .needsUpdate : .unknown+    /// The invite link to share: the https bounce page, which many messaging apps will+    /// linkify where a bare `findfamily://` URI is left as plain text. Both values ride in+    /// the fragment, which browsers never send, so the server sees only that some share+    /// page was opened. `k` is a 22-character hash of our public bundle, not the bundle+    /// itself (~4 kB base64) — the recipient fetches the key from the relay and checks it+    /// against this. Omitted when PQC is unavailable, leaving the id-only link.+    func inviteLink() -> String {+        let base = "https://ma.vayunmathur.com/ff/share#id=\(Base26.encode(userid))"+        guard let bundle = pqcIdentity?.publicBundle else { return base }+        return base + "&k=" + InviteFingerprint.encode(userId: userid, publicBundle: bundle)     }      /// Computes the quantum-safe verification "security code" (safety number) for a connection:@@ -219,8 +238,11 @@ final class Networking: ObservableObject {     func getPqcBundle(forUserid id: Int64) async -> Data? {         guard pqcAvailable else { return nil }         if let data = await getPqcKeyRaw(forUserid: id) {-            // Cache atomically so we don't clobber other columns (sharingAutoToggleAt etc.).-            if let u = Database.shared.user(id: id), u.pqcEncryptionKey == nil {+            // 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+            // its own so the other columns (sharingAutoToggleAt etc.) aren't clobbered.+            if Database.shared.user(id: id) != nil {                 Database.shared.setPqcEncryptionKey(id: id, pqcEncryptionKey: data.base64EncodedString())             }             return data
FindFamilyiOS/Networking/RelayKeyLookup.swift
diff --git a/FindFamilyiOS/Networking/RelayKeyLookup.swift b/FindFamilyiOS/Networking/RelayKeyLookup.swiftnew file mode 100644index 0000000000..9f09dc3c1d--- /dev/null+++ b/FindFamilyiOS/Networking/RelayKeyLookup.swift@@ -0,0 +1,95 @@+import Foundation++/// Peer key lookup over the live relay's binary socket — the same GETKEY exchange the+/// Android client uses, so both platforms read a peer's key capability through one code+/// path and one set of status codes:+///+///     client→server  [0x04][u64 target]+///     server→client  [0x05][status][u64 target][bundle…]+///+/// 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.+///+/// 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+/// peer has a PQC key and fetching the key that gets verified.+enum RelayKeyLookup {+    /// Key capability of a peer, as reported by the relay.+    enum Status: UInt8 {+        case noKey = 0+        case classic = 1+        case pqc = 2+    }++    struct KeyResult {+        let status: Status+        /// The peer's public bundle — present only for `.pqc`.+        let bundle: Data?+    }++    private static let url = URL(string: "wss://findfamily.cc/api/ws")!++    /// Matches the Android client's GETKEY timeout.+    private static let timeout: TimeInterval = 5++    private static let opGetKeyRequest: UInt8 = 0x04+    private static let opGetKeyResponse: UInt8 = 0x05++    /// 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? {+        let session = URLSession(configuration: .ephemeral)+        let task = session.webSocketTask(with: url)+        task.resume()+        defer {+            task.cancel(with: .goingAway, reason: nil)+            session.invalidateAndCancel()+        }++        var request = Data([opGetKeyRequest])+        withUnsafeBytes(of: UInt64(bitPattern: userId).bigEndian) { request.append(contentsOf: $0) }+        guard (try? await task.send(.data(request))) != nil else { return nil }++        return await firstKeyResponse(task, target: userId)+    }++    /// Reads frames until the KEYRESP for `target` arrives, or the timeout wins. The relay+    /// only ever answers a GETKEY on an unsubscribed socket, but skipping non-matching+    /// frames keeps this from being desynced by anything else it might send.+    private static func firstKeyResponse(_ task: URLSessionWebSocketTask, target: Int64) async -> KeyResult? {+        await withTaskGroup(of: KeyResult?.self) { group in+            group.addTask {+                while true {+                    guard let message = try? await task.receive() else { return nil }+                    guard case .data(let frame) = message else { continue }+                    if let result = parse(frame, target: target) { return result }+                }+            }+            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+        }+    }++    /// 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? {+        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)+    }+}
FindFamilyiOS/UI/Dialogs.swift
diff --git a/FindFamilyiOS/UI/Dialogs.swift b/FindFamilyiOS/UI/Dialogs.swiftindex a00acf07d9..aca96815df 100644--- a/FindFamilyiOS/UI/Dialogs.swift+++ b/FindFamilyiOS/UI/Dialogs.swift@@ -4,6 +4,8 @@ import SwiftUI  struct AddPersonDialog: View {     let presetID: Int64?+    /// The `k=` fingerprint from the invite link that prefilled `presetID`, if any.+    let fingerprint: String?     @Binding var isPresented: Bool      @State private var theirIDStr: String = ""@@ -11,6 +13,7 @@ struct AddPersonDialog: View {     @State private var contactPhoto: String?     @State private var justCopied = false     @State private var showNeedsUpdate = false+    @State private var showKeyMismatch = false      private var myIDStr: String { Base26.encode(Networking.shared.userid) } @@ -71,11 +74,12 @@ struct AddPersonDialog: View {                         .contentShape(Rectangle())                     }                     .buttonStyle(.plain)-                    // Share sheet instead of copy/paste: sends findfamily://add/<myId>,-                    // which prefills the recipient's Add Person dialog. The link carries-                    // only a public id — never a key — so it's safe to share anywhere.+                    // Share sheet instead of copy/paste: sends an https link that bounces+                    // to findfamily://add/<myId>?k=<fingerprint>, which prefills the+                    // recipient's Add Person dialog. See Networking.inviteLink() for why+                    // the web hop exists and what `k` is.                     Button {-                        Platform.share("findfamily://add/\(myIDStr)")+                        Platform.share(Networking.shared.inviteLink())                     } label: {                         HStack {                             Image(systemName: "square.and.arrow.up")@@ -129,6 +133,11 @@ struct AddPersonDialog: View {             } message: {                 Text(Strings.outdatedPeerMessage)             }+            .alert(Strings.keyMismatchTitle, isPresented: $showKeyMismatch) {+                Button(Strings.okButton, role: .cancel) {}+            } message: {+                Text(Strings.keyMismatchMessage)+            }         }     } @@ -138,12 +147,23 @@ struct AddPersonDialog: View {         // peer who registered only a classic key is on an outdated app: prompt them to update         // instead of adding them. Unknown (not-yet-registered) peers are allowed through — they may         // register with PQC once they install the app.+        //+        // The fingerprint only vouches for the id that arrived in the link, and the field is+        // read-only whenever there is a preset, so it applies exactly when one is present.+        let inviteFingerprint = presetID != nil ? fingerprint : nil         Task { @MainActor in-            let peerStatus = await Networking.shared.peerCryptoStatus(forUserid: id)-            if peerStatus == .needsUpdate {+            let check = await Networking.shared.peerCryptoStatus(+                forUserid: id,+                expectedFingerprint: inviteFingerprint+            )+            if check.status == .needsUpdate {                 showNeedsUpdate = true                 return             }+            if check.status == .keyMismatch {+                showKeyMismatch = true+                return+            }             let isAccepting = (status == .awaitingRequest)             let newStatus: RequestStatus = isAccepting ? .mutualConnection : .awaitingResponse             let user = User(@@ -155,7 +175,9 @@ struct AddPersonDialog: View {                 requestStatus: newStatus,                 lastLocationChangeTime: Date(),                 encryptionKey: nil,-                pqcEncryptionKey: nil+                // Store the fingerprint-checked key with the row itself, so the key that+                // was verified is the one used from here on rather than a fresh lookup.+                pqcEncryptionKey: check.verifiedBundleB64             )             Database.shared.upsertUser(user)             isPresented = false
FindFamilyiOS/UI/MainView.swift
diff --git a/FindFamilyiOS/UI/MainView.swift b/FindFamilyiOS/UI/MainView.swiftindex d36c7650e7..bfb7cdfff1 100644--- a/FindFamilyiOS/UI/MainView.swift+++ b/FindFamilyiOS/UI/MainView.swift@@ -51,6 +51,8 @@ struct MainView: View {     // Dialogs     @State private var showAddPersonDialog = false     @State private var addPersonId: Int64?+    /// Fingerprint from the invite link that set `addPersonId`, when it came from one.+    @State private var addPersonFingerprint: String?     @State private var showAddLinkDialog = false     @State private var showMissingFeaturesDialog = false     @State private var showSecurityCode = false@@ -111,8 +113,15 @@ struct MainView: View {             .navigationTitle(Text(headerTitle))             .navigationBarTitleDisplayMode(.inline)             .toolbar { topBarToolbar }-            .sheet(isPresented: $showAddPersonDialog, onDismiss: { addPersonId = nil }) {-                AddPersonDialog(presetID: addPersonId, isPresented: $showAddPersonDialog)+            .sheet(isPresented: $showAddPersonDialog, onDismiss: {+                addPersonId = nil+                addPersonFingerprint = nil+            }) {+                AddPersonDialog(+                    presetID: addPersonId,+                    fingerprint: addPersonFingerprint,+                    isPresented: $showAddPersonDialog+                )             }             .sheet(isPresented: $showAddLinkDialog) {                 AddLinkDialog(isPresented: $showAddLinkDialog)@@ -145,10 +154,11 @@ struct MainView: View {         }         // A tapped findfamily://add/<id> invite prefills the Add Person dialog. @Published         // replays its current value on subscribe, so this catches cold-start links too.-        .onReceive(deepLink.$pendingAddId.compactMap { $0 }) { id in-            addPersonId = id+        .onReceive(deepLink.$pendingAddInvite.compactMap { $0 }) { invite in+            addPersonId = invite.id+            addPersonFingerprint = invite.fingerprint             showAddPersonDialog = true-            deepLink.pendingAddId = nil+            deepLink.pendingAddInvite = nil         }     } @@ -199,6 +209,7 @@ struct MainView: View {             AddMenu(                 onAddPerson: {                     addPersonId = nil+                    addPersonFingerprint = nil                     showAddPersonDialog = true                 },                 onAddWaypoint: {@@ -287,7 +298,10 @@ struct MainView: View {                             waypointCoord = wp.coord                         },                         onTapRequest: { id in+                            // An inbound sharing request, not an invite link, so there is+                            // no fingerprint to check against.                             addPersonId = id+                            addPersonFingerprint = nil                             showAddPersonDialog = true                         }                     )
FindFamilyiOS/Util/Util.swift
diff --git a/FindFamilyiOS/Util/Util.swift b/FindFamilyiOS/Util/Util.swiftindex 6ea2b4b543..3f41afdd03 100644--- a/FindFamilyiOS/Util/Util.swift+++ b/FindFamilyiOS/Util/Util.swift@@ -134,6 +134,10 @@ enum Strings {     // Shown when connecting to a peer whose app is too old for post-quantum encryption.     static let outdatedPeerTitle = "Update needed"     static let outdatedPeerMessage = "This person is using an older version of FindFamily that doesn't support quantum-safe encryption. Ask them to update their app, then try connecting again."++    // Shown when a peer's key doesn't match the fingerprint their invite link vouched for.+    static let keyMismatchTitle = "Couldn't verify this person"+    static let keyMismatchMessage = "The encryption key for this person doesn't match the one their invite link listed, so they weren't added. Check that you opened the whole link, and ask them to send a new one." }  // MARK: - Time formatting@@ -202,15 +206,23 @@ enum NotificationsUtil {  // MARK: - Deep links -/// Routes incoming `findfamily://add/<base26>` invites to the UI. The link carries-/// only the sender's public id — never a key — so prefilling the Add Person dialog-/// from it is safe; the user still explicitly accepts.+/// A tapped invite link: the sender's id, plus the bundle fingerprint it vouched for.+struct AddInvite: Equatable {+    let id: Int64+    /// The `k=` value, or nil for links from builds before it existed.+    let fingerprint: String?+}++/// Routes incoming `findfamily://add/<base26>[?k=<fingerprint>]` invites to the UI. The+/// link carries the sender's public id and a hash of their public key — never a key and+/// never a secret — so prefilling the Add Person dialog from it is safe; the user still+/// explicitly accepts, and the fingerprint is checked against the relay's key on connect. final class DeepLinkRouter: ObservableObject {     static let shared = DeepLinkRouter()     private init() {} -    /// Decoded invite user id awaiting presentation, or nil once consumed.-    @Published var pendingAddId: Int64?+    /// Decoded invite awaiting presentation, or nil once consumed.+    @Published var pendingAddInvite: AddInvite?      func handle(_ url: URL) {         guard url.scheme == "findfamily", url.host == "add" else { return }@@ -220,7 +232,19 @@ final class DeepLinkRouter: ObservableObject {         guard !segment.isEmpty,               segment.allSatisfy({ $0.isASCII && $0.isLetter }),               let id = Base26.decode(segment) else { return }-        pendingAddId = id+        pendingAddInvite = AddInvite(id: id, fingerprint: Self.fingerprint(from: url))+    }++    /// The `k` query value, accepted only if it looks like base64url. Anything else is+    /// dropped, which leaves the invite unverified rather than failing the whole link.+    private static func fingerprint(from url: URL) -> String? {+        guard let value = URLComponents(url: url, resolvingAgainstBaseURL: false)?+            .queryItems?.first(where: { $0.name == "k" })?.value?+            .trimmingCharacters(in: .whitespaces), !value.isEmpty else { return nil }+        let isBase64url = value.allSatisfy {+            $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_")+        }+        return isBase64url ? value : nil     } }