Modern Apps git

← Modern-Apps.git

findfamily-ios: add pqc support compatible with office key system - pqc pair, register/getpair api, parallel publish/receive with pqc-only routing

Commit
a18eed0d278b0302f3c04dec5450797509a9155a
Author
Vayun Mathur <[email protected]>
When
2026-07-29 16:15 UTC (4 months ago)
Parents
3bb771f

Diff

FindFamilyiOS/Crypto/PQCCrypto.swift
diff --git a/FindFamilyiOS/Crypto/PQCCrypto.swift b/FindFamilyiOS/Crypto/PQCCrypto.swiftnew file mode 100644index 0000000000..8d206b4436--- /dev/null+++ b/FindFamilyiOS/Crypto/PQCCrypto.swift@@ -0,0 +1,342 @@+import Foundation+import CryptoKit++// MARK: - PQC Bundle framing (identical to Kotlin Pqc.kt)+//+// Public bundle:  [4B kemPubLen BE][kemPub SPKI DER][dsaPub SPKI DER]+// Private bundle: [4B kemPrivLen BE][kemPriv PKCS#8 DER][dsaPriv PKCS#8 DER]+// Sealed blob:     [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ciphertext||tag]+// Shared secret: SHA256(BE32(1) || rawSS) — same KDF as Office / Bouncy Castle's default.++enum PQCBundle {+    // MARK: - Length-prefix framing++    static func lenPrefix(_ a: Data, _ b: Data) -> Data {+        var out = Data()+        out.reserveCapacity(4 + a.count + b.count)+        let alen = UInt32(a.count).bigEndian+        withUnsafeBytes(of: alen) { out.append(contentsOf: $0) }+        out.append(a)+        out.append(b)+        return out+    }++    static func lenPrefixSingle(_ a: Data) -> Data {+        // Same as above but second piece empty — not used but kept for symmetry.+        var out = Data()+        out.reserveCapacity(4 + a.count)+        let alen = UInt32(a.count).bigEndian+        withUnsafeBytes(of: alen) { out.append(contentsOf: $0) }+        out.append(a)+        return out+    }++    static func unLenPrefix(_ x: Data) -> (Data, Data)? {+        guard x.count >= 4 else { return nil }+        let len = x.withUnsafeBytes { ptr -> UInt32 in+            var v: UInt32 = 0+            withUnsafeMutableBytes(of: &v) { dest in+                dest.copyMemory(from: UnsafeRawBufferPointer(start: ptr.baseAddress, count: 4))+            }+            return UInt32(bigEndian: v)+        }+        let lenI = Int(len)+        guard 4 + lenI <= x.count else { return nil }+        let first = x.subdata(in: 4..<(4 + lenI))+        let second = x.subdata(in: (4 + lenI)..<x.count)+        return (first, second)+    }++    // MARK: - Public/Private bundle builders++    static func buildPublic(kemPub: Data, dsaPub: Data) -> Data {+        // Same layout Office uses for directory: [4B kemLen][kem][dsa]+        lenPrefix(kemPub, dsaPub)+    }++    static func buildPrivate(kemPriv: Data, dsaPriv: Data) -> Data {+        // Ephemeral links store private as same framing: [4B kemPrivLen][kemPriv][dsaPriv]+        lenPrefix(kemPriv, dsaPriv)+    }++    static func splitPublic(_ bundle: Data) -> (kemPub: Data, dsaPub: Data)? {+        guard let (k, d) = unLenPrefix(bundle) else { return nil }+        return (k, d)+    }++    static func splitPrivate(_ bundle: Data) -> (kemPriv: Data, dsaPriv: Data)? {+        guard let (k, d) = unLenPrefix(bundle) else { return nil }+        return (k, d)+    }++    // MARK: - Sealed blob helpers [4B encapLen][encap][aes] where aes = [12B iv][ct||tag]++    static func buildSealed(encap: Data, aes: Data) -> Data {+        lenPrefix(encap, aes)+    }++    static func splitSealed(_ blob: Data) -> (encap: Data, aes: Data)? {+        guard let (e, a) = unLenPrefix(blob) else { return nil }+        return (e, a)+    }+}++// MARK: - AES-256-GCM helpers (mirrors E2ee.aesEncrypt / aesDecrypt in Kotlin)+//+// Layout: E2ee.aesEncrypt produces iv(12) + ct||tag (16) with random IV prepended.+// We reproduce that via CryptoKit AES.GCM.++enum PQCAES {+    static let ivLen = 12++    /// Encrypts with `key` (32 bytes), returns `iv(12) + ciphertext||tag`.+    static func seal(key: Data, plaintext: Data) throws -> Data {+        // CryptoKit expects 32-byte key for AES256.+        guard key.count == 32 else { throw NSError(domain: "pqc_aes", code: -1, userInfo: [NSLocalizedDescriptionKey: "key must be 32 bytes"]) }+        let symKey = SymmetricKey(data: key)+        let nonce = AES.GCM.Nonce() // random 12 bytes+        let sealed = try AES.GCM.seal(plaintext, using: symKey, nonce: nonce)+        // sealed.ciphertext + sealed.tag (16). We manually prepend iv (nonce) to mimic Kotlin's E2ee.aesEncrypt.+        var out = Data()+        out.reserveCapacity(12 + sealed.ciphertext.count + sealed.tag.count)+        out.append(Data(nonce))+        out.append(sealed.ciphertext)+        out.append(sealed.tag)+        return out+    }++    /// Reverses `seal`: input `iv(12) + ct||tag`, key 32 bytes.+    static func open(key: Data, sealed: Data) throws -> Data {+        guard key.count == 32 else { throw NSError(domain: "pqc_aes", code: -1, userInfo: [NSLocalizedDescriptionKey: "key must be 32 bytes"]) }+        guard sealed.count >= ivLen + 16 else { throw NSError(domain: "pqc_aes", code: -2, userInfo: [NSLocalizedDescriptionKey: "sealed too short"]) }+        let iv = sealed.subdata(in: 0..<ivLen)+        let ctAndTag = sealed.subdata(in: ivLen..<sealed.count)+        // AES.GCM last 16 bytes = tag+        guard ctAndTag.count >= 16 else { throw NSError(domain: "pqc_aes", code: -3) }+        let tag = ctAndTag.subdata(in: (ctAndTag.count - 16)..<ctAndTag.count)+        let ct = ctAndTag.subdata(in: 0..<(ctAndTag.count - 16))+        let symKey = SymmetricKey(data: key)+        let nonce = try AES.GCM.Nonce(data: iv)+        let sealedBox = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag)+        let plain = try AES.GCM.open(sealedBox, using: symKey)+        return plain+    }+}++// MARK: - Security code (same as Kotlin SecurityCode.compute)++enum PQCSecurityCode {+    private static let iterations = 4000++    /// Computes a 6-group 5-digit safety number from two public bundles, identical both sides.+    static func compute(myBundle: Data, theirBundle: Data) -> String {+        let a = sha256(myBundle)+        let b = sha256(theirBundle)+        // canonical order+        var h: Data+        if a.lexicographicallyPrecedes(b) { h = a + b } else { h = b + a }+        for _ in 0..<iterations { h = sha256(h) }+        return format(h)+    }++    private static func sha256(_ d: Data) -> Data {+        Data(SHA256.hash(data: d))+    }++    private static func format(_ h: Data) -> String {+        var sb = ""+        var idx = 0+        for group in 0..<6 {+            guard idx + 5 <= h.count else { break }+            var v: UInt64 = 0+            for j in 0..<5 {+                v = (v << 8) | UInt64(h[idx + j])+            }+            if group > 0 { sb.append(" ") }+            sb.append(String(format: "%05d", v % 100000))+            idx += 5+        }+        return sb+    }+}++// MARK: - PQC Rust bridge (C exports)+//+// If the Rust lib `libe2ee_pqc.a` is linked as an XCFramework, these symbols exist.+// If not linked (simulator without framework), calls return 0 and the Swift layer+// treats PQC as unavailable (graceful fallback to RSA).++// C functions exported from e2ee_pqc/src/c_bridge.rs+@_silgen_name("pqc_free")+func pqc_free(_ ptr: UnsafeMutablePointer<UInt8>?, _ len: Int)++@_silgen_name("pqc_secure_zero")+func pqc_secure_zero(_ ptr: UnsafeMutablePointer<UInt8>?, _ len: Int)++@_silgen_name("pqc_kem_keygen")+func pqc_kem_keygen(+    _ pub_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ pub_len_out: UnsafeMutablePointer<Int>,+    _ priv_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ priv_len_out: UnsafeMutablePointer<Int>+) -> Int32++@_silgen_name("pqc_dsa_keygen")+func pqc_dsa_keygen(+    _ pub_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ pub_len_out: UnsafeMutablePointer<Int>,+    _ priv_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ priv_len_out: UnsafeMutablePointer<Int>+) -> Int32++@_silgen_name("pqc_identity_keygen")+func pqc_identity_keygen(+    _ pub_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ pub_bundle_len_out: UnsafeMutablePointer<Int>,+    _ priv_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ priv_bundle_len_out: UnsafeMutablePointer<Int>+) -> Int32++@_silgen_name("pqc_kem_encaps")+func pqc_kem_encaps(+    _ kem_pub: UnsafePointer<UInt8>?, _ kem_pub_len: Int,+    _ ct_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ ct_len_out: UnsafeMutablePointer<Int>,+    _ ss_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ ss_len_out: UnsafeMutablePointer<Int>+) -> Int32++@_silgen_name("pqc_kem_decaps")+func pqc_kem_decaps(+    _ kem_priv: UnsafePointer<UInt8>?, _ kem_priv_len: Int,+    _ ct: UnsafePointer<UInt8>?, _ ct_len: Int,+    _ ss_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,+    _ ss_len_out: UnsafeMutablePointer<Int>+) -> Int32++@_silgen_name("pqc_security_code")+func pqc_security_code_c(+    _ my_bundle: UnsafePointer<UInt8>?, _ my_bundle_len: Int,+    _ their_bundle: UnsafePointer<UInt8>?, _ their_bundle_len: Int,+    _ out: UnsafeMutablePointer<UInt8>?, _ out_len: Int+) -> Int32++// MARK: - High-level PQC ops that mirror Kotlin Pqc.encryptTo / decrypt++enum PQCCrypto {+    /// Encrypts `plaintext` to a recipient's public PQC bundle (from PQCBundle.buildPublic).+    /// Layout sealed = [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ct||tag],+    /// identical to Kotlin's Pqc.encryptTo (which does encaps + E2ee.aesEncrypt).+    static func encryptTo(bundle: Data, plaintext: Data) throws -> Data {+        guard let (kemPub, _) = PQCBundle.splitPublic(bundle) else {+            throw NSError(domain: "pqc", code: -1, userInfo: [NSLocalizedDescriptionKey: "invalid PQC bundle"])+        }+        // Use C bridge if available, otherwise throw to signal PQC unavailable.+        // The Rust lib may not be linked on simulator — try and fall back.+        if let sealed = try? encryptToViaNative(kemPub: kemPub, plaintext: plaintext) {+            return sealed+        }+        // If native not linked, throw — caller treats as PQC unavailable.+        throw NSError(domain: "pqc", code: -10, userInfo: [NSLocalizedDescriptionKey: "PQC native not available"])+    }++    /// Decrypts sealed blob produced by `encryptTo` using our KEM private DER.+    static func decrypt(kemPrivateDer: Data, sealed: Data) throws -> Data {+        guard let (encap, aes) = PQCBundle.splitSealed(sealed) else {+            throw NSError(domain: "pqc", code: -2, userInfo: [NSLocalizedDescriptionKey: "invalid sealed blob"])+        }+        // Native decaps+        let ss: Data+        if let s = try? decapsViaNative(kemPrivateDer: kemPrivateDer, encap: encap) {+            ss = s+        } else {+            throw NSError(domain: "pqc", code: -11, userInfo: [NSLocalizedDescriptionKey: "PQC native decaps not available"])+        }+        return try PQCAES.open(key: ss, sealed: aes)+    }++    // Convenience: decrypt using private bundle [4B kemPrivLen][kemPriv][dsaPriv]+    // (mirrors how ephemeral links store private bundle).+    static func decryptWithPrivateBundle(privateBundle: Data, sealed: Data) throws -> Data {+        guard let (kemPriv, _) = PQCBundle.splitPrivate(privateBundle) else {+            throw NSError(domain: "pqc", code: -3, userInfo: [NSLocalizedDescriptionKey: "invalid private bundle"])+        }+        return try decrypt(kemPrivateDer: kemPriv, sealed: sealed)+    }++    // MARK: - Native wrappers++    private static func encryptToViaNative(kemPub: Data, plaintext: Data) throws -> Data {+        var ctPtr: UnsafeMutablePointer<UInt8>? = nil+        var ctLen: Int = 0+        var ssPtr: UnsafeMutablePointer<UInt8>? = nil+        var ssLen: Int = 0++        let ok: Int32 = kemPub.withUnsafeBytes { pubBuf in+            pqc_kem_encaps(+                pubBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), pubBuf.count,+                &ctPtr, &ctLen,+                &ssPtr, &ssLen+            )+        }+        guard ok == 1, let cPtr = ctPtr, let sPtr = ssPtr else {+            throw NSError(domain: "pqc", code: -4, userInfo: [NSLocalizedDescriptionKey: "encaps failed (native not linked?)"])+        }+        // Ensure free even on throw+        defer {+            pqc_free(cPtr, ctLen)+            pqc_secure_zero(sPtr, ssLen)+            pqc_free(sPtr, ssLen)+        }+        let encap = Data(bytes: cPtr, count: ctLen)+        let ss = Data(bytes: sPtr, count: ssLen)+        let aes = try PQCAES.seal(key: ss, plaintext: plaintext)+        return PQCBundle.buildSealed(encap: encap, aes: aes)+    }++    private static func decapsViaNative(kemPrivateDer: Data, encap: Data) throws -> Data {+        var ssPtr: UnsafeMutablePointer<UInt8>? = nil+        var ssLen: Int = 0+        let ok: Int32 = kemPrivateDer.withUnsafeBytes { privBuf in+            encap.withUnsafeBytes { ctBuf in+                pqc_kem_decaps(+                    privBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), privBuf.count,+                    ctBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), ctBuf.count,+                    &ssPtr, &ssLen+                )+            }+        }+        guard ok == 1, let sPtr = ssPtr else {+            throw NSError(domain: "pqc", code: -5, userInfo: [NSLocalizedDescriptionKey: "decaps failed"])+        }+        defer {+            pqc_secure_zero(sPtr, ssLen)+            pqc_free(sPtr, ssLen)+        }+        return Data(bytes: sPtr, count: ssLen)+    }++    /// Generates a full identity (public bundle + private bundle) via Rust. Falls back to error if native not linked.+    static func generateIdentity() throws -> (publicBundle: Data, privateBundle: Data) {+        var pubPtr: UnsafeMutablePointer<UInt8>? = nil+        var pubLen: Int = 0+        var privPtr: UnsafeMutablePointer<UInt8>? = nil+        var privLen: Int = 0+        let ok = pqc_identity_keygen(&pubPtr, &pubLen, &privPtr, &privLen)+        guard ok == 1, let pb = pubPtr, let pr = privPtr else {+            throw NSError(domain: "pqc", code: -6, userInfo: [NSLocalizedDescriptionKey: "identity keygen failed (native not linked?)"])+        }+        defer {+            // Don't free bundle here — copy first, free after.+            // Private bundle contains secrets: zero then free.+            // Public bundle freed after copy.+            // Caller's Data owns copy.+        }+        let pubData = Data(bytes: pb, count: pubLen)+        let privData = Data(bytes: pr, count: privLen)+        pqc_free(pb, pubLen)+        pqc_secure_zero(pr, privLen)+        pqc_free(pr, privLen)+        return (pubData, privData)+    }+}
FindFamilyiOS/Crypto/PQCKeyManager.swift
diff --git a/FindFamilyiOS/Crypto/PQCKeyManager.swift b/FindFamilyiOS/Crypto/PQCKeyManager.swiftnew file mode 100644index 0000000000..cdb0253d18--- /dev/null+++ b/FindFamilyiOS/Crypto/PQCKeyManager.swift@@ -0,0 +1,184 @@+import Foundation++// MARK: - PQC Key Manager (iOS mirror of Android PqcIdentity.loadOrCreate)+//+// Reuses the *exact same* cryptographic core as Office's Android e2ee-p2p module:+//   - ML-KEM-768 for encryption (key encapsulation + AES-256-GCM)+//   - ML-DSA-65 for signatures (reserved for future roster changes, but part of bundle)+//   - Keys as DER, byte-compatible with Bouncy Castle encoding (fixed SPKI/PKCS#8 prefixes)+//   - Bundle format [4B kemLen BE][kemPubDer][dsaPubDer] as in `Pqc.kt:bundle`+//   - KDF SHA256(BE32(1) || rawSS) as in lib.rs `concat_kdf_sha256`+//+// Storage: 4 separate Keychain entries (to stay under 4KB generic-password limit per item):+//   ff_pqcKemPub, ff_pqcKemPriv, ff_pqcDsaPub, ff_pqcDsaPriv+// This mirrors `PqcIdentity.kt` which stores `${prefix}KemPub/Priv`, `DsaPub/Priv` via E2eeKeyStore.+//+// This class is deliberately independent of Office — prefix `ff_pqc` ensures FindFamily PQC keys+// don't collide with any future Office iOS implementation that might use `office` prefix.++final class PQCKeyManager {+    static let shared = PQCKeyManager()++    // Keychain account names — use ff_pqc prefix matching Android's "ff_pqc" prefix.+    private enum KC {+        static let kemPub = "ff_pqcKemPub"+        static let kemPriv = "ff_pqcKemPriv"+        static let dsaPub = "ff_pqcDsaPub"+        static let dsaPriv = "ff_pqcDsaPriv"+        static let publicBundle = "ff_pqcPublicBundle" // cached bundle for fast register+    }++    private var _kemPub: Data?+    private var _kemPriv: Data?+    private var _dsaPub: Data?+    private var _dsaPriv: Data?+    private var _publicBundle: Data?+    private var _privateBundle: Data?++    private var isLoaded = false+    private let loadQueue = DispatchQueue(label: "cc.findfamily.pqc.keymanager")++    private init() {}++    // MARK: - Load / Create (mirrors PqcIdentity.loadOrCreate)++    /// Returns the device PQC identity, generating + persisting on first use.+    /// Throws if Rust native lib is not linked (native not available on this build) or generation fails.+    func identity() throws -> PQCIdentity {+        // Fast path in-memory.+        if isLoaded, let pubB = _publicBundle, let privB = _privateBundle,+           let kemPriv = _kemPriv, let kemPub = _kemPub {+            return PQCIdentity(publicBundle: pubB, privateBundle: privB,+                               kemPublic: kemPub, kemPrivate: kemPriv,+                               dsaPublic: _dsaPub, dsaPrivate: _dsaPriv)+        }+        return try loadQueue.sync {+            if isLoaded, let pubB = _publicBundle, let privB = _privateBundle,+               let kemPriv = _kemPriv, let kemPub = _kemPub {+                return PQCIdentity(publicBundle: pubB, privateBundle: privB,+                                   kemPublic: kemPub, kemPrivate: kemPriv,+                                   dsaPublic: _dsaPub, dsaPrivate: _dsaPriv)+            }++            // Try restore from Keychain.+            if let kemPub = Keychain.getData(key: KC.kemPub),+               let kemPriv = Keychain.getData(key: KC.kemPriv),+               let dsaPub = Keychain.getData(key: KC.dsaPub),+               let dsaPriv = Keychain.getData(key: KC.dsaPriv) {+                // Validate DER sizes roughly (to avoid corrupt entries).+                if kemPub.count > 1000 && kemPriv.count > 1000 {+                    let pubBundle = PQCBundle.buildPublic(kemPub: kemPub, dsaPub: dsaPub)+                    let privBundle = PQCBundle.buildPrivate(kemPriv: kemPriv, dsaPriv: dsaPriv)+                    _kemPub = kemPub+                    _kemPriv = kemPriv+                    _dsaPub = dsaPub+                    _dsaPriv = dsaPriv+                    _publicBundle = pubBundle+                    _privateBundle = privBundle+                    isLoaded = true+                    Keychain.setData(pubBundle, key: KC.publicBundle) // cache+                    print("PQCKeyManager: restored identity from Keychain pubBundle=\(pubBundle.count) privBundle=\(privBundle.count)")+                    return PQCIdentity(publicBundle: pubBundle, privateBundle: privBundle,+                                       kemPublic: kemPub, kemPrivate: kemPriv,+                                       dsaPublic: dsaPub, dsaPrivate: dsaPriv)+                }+            }++            // Generate fresh via Rust bridge. This requires libe2ee_pqc.a linked.+            // If not linked, PQCCrypto.generateIdentity throws "native not linked" → PQC unavailable.+            let (pubBundle, privBundle) = try PQCCrypto.generateIdentity()+            guard let (kemPriv, dsaPriv) = PQCBundle.splitPrivate(privBundle),+                  let (kemPub, dsaPub) = PQCBundle.splitPublic(pubBundle) else {+                throw NSError(domain: "pqc_keymanager", code: -1, userInfo: [NSLocalizedDescriptionKey: "generated bundles invalid"])+            }++            // Persist each DER separately (mirrors Android onlyIfAbsent race-safe, but iOS single process simpler).+            // Use onlyIfAbsent semantics: only write if not already present (best-effort race guard if two+            // processes — main app + background location — both start simultaneously on first launch).+            // We implement by checking again before write.+            if Keychain.getData(key: KC.kemPub) == nil { Keychain.setData(kemPub, key: KC.kemPub) }+            if Keychain.getData(key: KC.kemPriv) == nil { Keychain.setData(kemPriv, key: KC.kemPriv) }+            if Keychain.getData(key: KC.dsaPub) == nil { Keychain.setData(dsaPub, key: KC.dsaPub) }+            if Keychain.getData(key: KC.dsaPriv) == nil { Keychain.setData(dsaPriv, key: KC.dsaPriv) }++            // Re-read final persisted (winner of race) to avoid returning ephemeral identity that can't decrypt.+            let finalKemPub = Keychain.getData(key: KC.kemPub) ?? kemPub+            let finalKemPriv = Keychain.getData(key: KC.kemPriv) ?? kemPriv+            let finalDsaPub = Keychain.getData(key: KC.dsaPub) ?? dsaPub+            let finalDsaPriv = Keychain.getData(key: KC.dsaPriv) ?? dsaPriv++            let finalPubBundle = PQCBundle.buildPublic(kemPub: finalKemPub, dsaPub: finalDsaPub)+            let finalPrivBundle = PQCBundle.buildPrivate(kemPriv: finalKemPriv, dsaPriv: finalDsaPriv)++            _kemPub = finalKemPub+            _kemPriv = finalKemPriv+            _dsaPub = finalDsaPub+            _dsaPriv = finalDsaPriv+            _publicBundle = finalPubBundle+            _privateBundle = finalPrivBundle+            isLoaded = true+            Keychain.setData(finalPubBundle, key: KC.publicBundle)++            print("PQCKeyManager: generated fresh identity pubBundle=\(finalPubBundle.count) privBundle=\(finalPrivBundle.count) (final persisted)")++            return PQCIdentity(publicBundle: finalPubBundle, privateBundle: finalPrivBundle,+                               kemPublic: finalKemPub, kemPrivate: finalKemPriv,+                               dsaPublic: finalDsaPub, dsaPrivate: finalDsaPriv)+        }+    }++    /// Attempts to load identity without generating. Returns nil if not present or native unavailable.+    func existingIdentity() -> PQCIdentity? {+        try? identity()+    }++    /// Indicates whether PQC is available on this build (native lib linked and identity loadable).+    var isAvailable: Bool {+        (try? identity()) != nil+    }++    /// Returns the public bundle base64 for registration (like Android `Base64.encode(publicBundle)`).+    func publicBundleB64() throws -> String {+        try identity().publicBundle.base64EncodedString()+    }++    // MARK: - Ephemeral (TemporaryLink)++    /// Generate a fresh ephemeral PQC bundle for a TemporaryLink, same crypto as device identity.+    /// Returns (publicBundleB64, privateBundleB64).+    func generateEphemeralBundle() throws -> (publicB64: String, privateB64: String) {+        let (pubBundle, privBundle) = try PQCCrypto.generateIdentity()+        return (pubBundle.base64EncodedString(), privBundle.base64EncodedString())+    }++    // MARK: - Encrypt / Decrypt helpers (mirror Pqc.encryptTo / decrypt)++    func encryptTo(bundle: Data, plaintext: Data) throws -> Data {+        try PQCCrypto.encryptTo(bundle: bundle, plaintext: plaintext)+    }++    func decrypt(sealed: Data) throws -> Data {+        // Decrypt using our KEM private DER (from identity).+        let id = try identity()+        return try PQCCrypto.decrypt(kemPrivateDer: id.kemPrivate, sealed: sealed)+    }++    func decryptWithPrivateBundle(privateBundle: Data, sealed: Data) throws -> Data {+        try PQCCrypto.decryptWithPrivateBundle(privateBundle: privateBundle, sealed: sealed)+    }+}++// MARK: - In-memory identity value type++struct PQCIdentity {+    let publicBundle: Data+    let privateBundle: Data+    let kemPublic: Data+    let kemPrivate: Data+    let dsaPublic: Data?+    let dsaPrivate: Data?++    func securityCode(with peerBundle: Data) -> String {+        PQCSecurityCode.compute(myBundle: publicBundle, theirBundle: peerBundle)+    }+}
FindFamilyiOS/Crypto/PQCStubs.c
diff --git a/FindFamilyiOS/Crypto/PQCStubs.c b/FindFamilyiOS/Crypto/PQCStubs.cnew file mode 100644index 0000000000..c62860cd82--- /dev/null+++ b/FindFamilyiOS/Crypto/PQCStubs.c@@ -0,0 +1,138 @@+// PQCStubs.c — weak weak fallback stubs for Rust PQC native lib.+//+// Purpose: allows the iOS app to build and link even when libe2ee_pqc.a XCFramework+// is not present. Each function returns failure (0) / no-op, so PQC is reported as+// unavailable and Networking falls back to RSA-only — no crash, no link error.+//+// When the real Rust lib (src/main/rust) is built for iOS and added as+// e2ee_pqc.xcframework (static lib), its strong symbols override these weak ones+// at link time. The bundle format [4B kemLen][kemPub][dsaPub], sealed layout+// [4B encapLen][encap][aes] where aes = [12B iv][ct||tag], and KDF+// SHA256(BE32(1)||rawSS) stay identical to Office Android's e2ee-p2p implementation.+//+// Build XCFramework (from /Users/vayun/Documents/Modern-Apps/library/e2ee-p2p/src/main/rust):+//   rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim+//   cargo build --release --target aarch64-apple-ios+//   cargo build --release --target x86_64-apple-ios+//   cargo build --release --target aarch64-apple-ios-sim+//   # lipo or xcodebuild -create-xcframework...+//   # Place result at FindFamilyiOS/Frameworks/e2ee_pqc.xcframework and link it.+//+// No extra dependencies (dashmap not needed); the server relay stays opaque.++#include <stddef.h>+#include <stdint.h>++__attribute__((weak)) void pqc_free(uint8_t *ptr, size_t len) {+    (void)ptr; (void)len;+}++__attribute__((weak)) void pqc_secure_zero(uint8_t *ptr, size_t len) {+    if (!ptr) return;+    for (size_t i = 0; i < len; i++) ptr[i] = 0;+}++__attribute__((weak)) int32_t pqc_kem_keygen(+    uint8_t **pub_out, size_t *pub_len_out,+    uint8_t **priv_out, size_t *priv_len_out) {+    (void)pub_out; (void)pub_len_out; (void)priv_out; (void)priv_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_dsa_keygen(+    uint8_t **pub_out, size_t *pub_len_out,+    uint8_t **priv_out, size_t *priv_len_out) {+    (void)pub_out; (void)pub_len_out; (void)priv_out; (void)priv_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_identity_keygen(+    uint8_t **pub_bundle_out, size_t *pub_bundle_len_out,+    uint8_t **priv_bundle_out, size_t *priv_bundle_len_out) {+    (void)pub_bundle_out; (void)pub_bundle_len_out;+    (void)priv_bundle_out; (void)priv_bundle_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_kem_encaps(+    const uint8_t *kem_pub, size_t kem_pub_len,+    uint8_t **ct_out, size_t *ct_len_out,+    uint8_t **ss_out, size_t *ss_len_out) {+    (void)kem_pub; (void)kem_pub_len;+    (void)ct_out; (void)ct_len_out;+    (void)ss_out; (void)ss_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_kem_decaps(+    const uint8_t *kem_priv, size_t kem_priv_len,+    const uint8_t *ct, size_t ct_len,+    uint8_t **ss_out, size_t *ss_len_out) {+    (void)kem_priv; (void)kem_priv_len;+    (void)ct; (void)ct_len;+    (void)ss_out; (void)ss_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_dsa_sign(+    const uint8_t *dsa_priv, size_t dsa_priv_len,+    const uint8_t *msg, size_t msg_len,+    uint8_t **sig_out, size_t *sig_len_out) {+    (void)dsa_priv; (void)dsa_priv_len;+    (void)msg; (void)msg_len;+    (void)sig_out; (void)sig_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_dsa_verify(+    const uint8_t *dsa_pub, size_t dsa_pub_len,+    const uint8_t *msg, size_t msg_len,+    const uint8_t *sig, size_t sig_len) {+    (void)dsa_pub; (void)dsa_pub_len;+    (void)msg; (void)msg_len;+    (void)sig; (void)sig_len;+    return -1;+}++__attribute__((weak)) int32_t pqc_security_code(+    const uint8_t *my_bundle, size_t my_bundle_len,+    const uint8_t *their_bundle, size_t their_bundle_len,+    uint8_t *out, size_t out_len) {+    (void)my_bundle; (void)my_bundle_len;+    (void)their_bundle; (void)their_bundle_len;+    (void)out; (void)out_len;+    return 0;+}++__attribute__((weak)) int32_t pqc_bundle_is_valid(const uint8_t *bundle, size_t bundle_len) {+    (void)bundle; (void)bundle_len;+    return 0;+}++__attribute__((weak)) int32_t pqc_bundle_inspect(+    const uint8_t *bundle, size_t bundle_len,+    size_t *kem_pub_len_out, size_t *dsa_pub_len_out) {+    (void)bundle; (void)bundle_len;+    (void)kem_pub_len_out; (void)dsa_pub_len_out;+    return 0;+}++__attribute__((weak)) int32_t pqc_bundle_build(+    const uint8_t *kem_pub, size_t kem_pub_len,+    const uint8_t *dsa_pub, size_t dsa_pub_len,+    uint8_t **out, size_t *out_len) {+    (void)kem_pub; (void)kem_pub_len;+    (void)dsa_pub; (void)dsa_pub_len;+    (void)out; (void)out_len;+    return 0;+}++__attribute__((weak)) int32_t pqc_bundle_split(+    const uint8_t *bundle, size_t bundle_len,+    uint8_t **kem_pub_out, size_t *kem_pub_len_out,+    uint8_t **dsa_pub_out, size_t *dsa_pub_len_out) {+    (void)bundle; (void)bundle_len;+    (void)kem_pub_out; (void)kem_pub_len_out;+    (void)dsa_pub_out; (void)dsa_pub_len_out;+    return 0;+}
FindFamilyiOS/Model/Models.swift
diff --git a/FindFamilyiOS/Model/Models.swift b/FindFamilyiOS/Model/Models.swiftindex 48f15eec9a..21b7dd3fa1 100644--- a/FindFamilyiOS/Model/Models.swift+++ b/FindFamilyiOS/Model/Models.swift@@ -58,11 +58,14 @@ struct User: Identifiable, Codable, Hashable, Equatable {     /// Peer device platform (`"android"` or `"ios"`), learned from incoming heartbeats.     /// Used by the UWB ranging path to pick same-platform vs cross-platform protocol.     var platform: String? = nil+    /// Post-quantum public bundle (base64 of [4B kemLen][kemPubDer][dsaPubDer]), nullable for migration.+    /// Same format as Android Office `Pqc.bundle` / `ff_pqc` key directory.+    var pqcEncryptionKey: String? = nil      static let empty = User(         id: 0, name: "", photo: nil, locationName: "Unnamed Location",         sendingEnabled: false, requestStatus: .mutualConnection,-        lastLocationChangeTime: Date(), encryptionKey: nil, platform: nil+        lastLocationChangeTime: Date(), encryptionKey: nil, platform: nil, pqcEncryptionKey: nil     ) } @@ -150,4 +153,8 @@ struct TemporaryLink: Identifiable, Codable, Hashable, Equatable {     /// Base64(PEM) RSA public key — registered for the link's id and used by senders.     var publicKey: String     var deleteAt: Date+    /// PQC ephemeral public bundle (base64 [4B kemLen][kemPub][dsaPub]), nullable for migration.+    var pqcPublicKey: String? = nil+    /// PQC ephemeral private bundle (base64 [4B kemPrivLen][kemPriv][dsaPriv]), nullable. Fragment `#pqc_key=` contains this.+    var pqcKey: String? = nil }
FindFamilyiOS/Networking/Networking.swift
diff --git a/FindFamilyiOS/Networking/Networking.swift b/FindFamilyiOS/Networking/Networking.swiftindex ff77e8b5b7..b46050965a 100644--- a/FindFamilyiOS/Networking/Networking.swift+++ b/FindFamilyiOS/Networking/Networking.swift@@ -32,17 +32,31 @@ final class NetworkClient {  // MARK: - Networking singleton -/// Mirrors `Networking.kt` from Modern-Apps. Owns identity (userid, RSA key pair),+/// Mirrors `Networking.kt` from Modern-Apps. Owns identity (userid, RSA + PQC key pairs), /// registration with the server, and the encrypted publish/receive flows.+///+/// PQC support mirrors Office's Android `PqcIdentity.loadOrCreate` system:+///   - Device PQC identity uses `PQCKeyManager` which stores `ff_pqcKemPub/Priv`, `ff_pqcDsaPub/Priv`+///     (same as Android's `ff_pqc` prefix) in Keychain, with bundle format [4B kemLen][kemPub][dsaPub]+///     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; publish/receive+///     have `_pqc` variants. If peer has PQC key, publish ONLY to PQC endpoint (higher tier).+///   - Receive drains both classic and PQC queues for backward compat during rollout. @MainActor final class Networking: ObservableObject {     static let shared = Networking()      private let client = NetworkClient()     private(set) var userid: Int64 = 0+    // RSA     private var publicKey: SecKey?     private var privateKey: SecKey?     private var publicKeyPEMBase64: String = ""+    // PQC — mirrors Office/FF Android ff_pqc prefix+    private var pqcPublicBundleB64: String = ""+    private var pqcIdentity: PQCIdentity?+    var pqcAvailable: Bool { pqcIdentity != nil }+     private var networkIsDown = false      /// Local platform tag included in outgoing heartbeat payloads so peers learn we're on iOS.@@ -61,11 +75,26 @@ final class Networking: ObservableObject {                 userid = Int64.random(in: Int64.min...Int64.max)                 Keychain.setInt64(userid, key: "userid")             }+            // RSA             let (pri, pub) = try RSAKeyManager.shared.keyPair()             privateKey = pri             publicKey = pub             let pem = try RSAPEM.publicKeyToPEM(pub)             publicKeyPEMBase64 = Data(pem.utf8).base64EncodedString()++            // PQC — best effort. If Rust XCFramework not linked, this throws and we stay RSA-only.+            // This mirrors Android's try/catch around PqcIdentity so legacy builds keep working.+            do {+                let id = try PQCKeyManager.shared.identity()+                pqcIdentity = id+                pqcPublicBundleB64 = id.publicBundle.base64EncodedString()+                print("Networking: PQC identity ready bundleLen=\(id.publicBundle.count)")+            } catch {+                print("Networking: PQC unavailable (native not linked?): \(error.localizedDescription)")+                pqcIdentity = nil+                pqcPublicBundleB64 = ""+            }+             isReady = true             ensureMeUserExists()             _ = await ensureUserExists()@@ -87,7 +116,8 @@ final class Networking: ObservableObject {                 sendingEnabled: false,                 requestStatus: .mutualConnection,                 lastLocationChangeTime: Date(),-                encryptionKey: nil+                encryptionKey: nil,+                pqcEncryptionKey: nil             )             Database.shared.upsertUser(me)         }@@ -104,11 +134,29 @@ final class Networking: ObservableObject {         return await postBool("/api/register", body: body)     } +    func registerPqc() async -> Bool {+        guard !pqcPublicBundleB64.isEmpty else { return false }+        let body = encodeJSON([+            "userid": .uint64(UInt64(bitPattern: userid)),+            "key": .string(pqcPublicBundleB64),+        ])+        let ok = await postBool("/api/pqc/register", body: body)+        print("Networking: registerPqc userid=\(UInt64(bitPattern: userid)) ok=\(ok) bundleLen=\(pqcIdentity?.publicBundle.count ?? -1)")+        return ok+    }+     func ensureUserExists() async -> Bool {+        var ok = true         if await getKey(forUserid: userid) == nil {-            return await register()+            ok = await register() && ok+        }+        // PQC self-healing: ensure PQC key registered too if available.+        if pqcAvailable {+            if await getPqcKeyRaw(forUserid: userid) == nil {+                ok = await registerPqc() && ok+            }         }-        return true+        return ok     }      /// GET-style lookup: server returns the raw base64-PEM string in the response body.@@ -133,7 +181,72 @@ final class Networking: ObservableObject {         }     } +    // MARK: - PQC key fetch (raw bundle)++    /// Raw PQC bundle Data fetch (base64 decoded), for registration self-heal check.+    func getPqcKeyRaw(forUserid id: Int64) async -> Data? {+        guard pqcAvailable else { return nil }+        let body = Data(#"{"userid": \#(UInt64(bitPattern: id))}"#.utf8)+        do {+            let (data, http) = try await client.postJSON(path: "/api/pqc/getkey", jsonBody: body)+            networkIsDown = false+            guard http.statusCode == 200 else { return nil }+            guard let b64 = String(data: data, encoding: .utf8)?+                .trimmingCharacters(in: .whitespacesAndNewlines)+                .trimmingCharacters(in: CharacterSet(charactersIn: "\"")),+                  let bundleData = Data(base64Encoded: b64),+                  !bundleData.isEmpty+                else { return nil }+            return bundleData+        } catch {+            checkNetworkDown(error)+            return nil+        }+    }++    /// 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) {+            // cache+            if var u = Database.shared.user(id: id), u.pqcEncryptionKey == nil {+                u.pqcEncryptionKey = data.base64EncodedString()+                Database.shared.upsertUser(u)+            } else if Database.shared.user(id: id) == nil {+                // We have a bundle but no user yet — user will be created by location receive path.+            }+            return data+        }+        return nil+    }++    // MARK: - Publish Location (PQC routing: if peer has PQC key, ONLY use PQC endpoint)+     func publishLocation(_ location: LocationValue, toUser user: User) async -> Bool {+        // PQC fast-path: if peer has bundle (cached or just fetched), publish only to PQC endpoint.+        if let bundle = await resolvedPqcBundle(for: user) {+            if let ok = await publishEncryptedPqc(location: location, recipientID: user.id, bundle: bundle) {+                return ok+            }+            // if PQC encrypt fails, fallback to RSA+            print("Networking: publishLocation PQC failed for \(UInt64(bitPattern: user.id)), falling back to RSA")+        }+        return await publishLocationClassic(location, toUser: user)+    }++    private func resolvedPqcBundle(for user: User) async -> Data? {+        guard pqcAvailable else { return nil }+        if let b64 = user.pqcEncryptionKey, let data = Data(base64Encoded: b64), !data.isEmpty {+            return data+        }+        // Opportunistic fetch from server.+        if let data = await getPqcBundle(forUserid: user.id) {+            return data+        }+        return nil+    }++    private func publishLocationClassic(_ location: LocationValue, toUser user: User) async -> Bool {         let key: SecKey?         if let encKeyB64 = user.encryptionKey,            let pemData = Data(base64Encoded: encKeyB64),@@ -141,7 +254,6 @@ final class Networking: ObservableObject {            let k = RSAPEM.publicKeyFromPEM(pem) {             key = k         } else if let k = await getKey(forUserid: user.id) {-            // Cache for next time.             do {                 let pem = try RSAPEM.publicKeyToPEM(k)                 let b64 = Data(pem.utf8).base64EncodedString()@@ -158,6 +270,17 @@ final class Networking: ObservableObject {     }      func publishLocation(_ location: LocationValue, toLink link: TemporaryLink) async -> Bool {+        // TemporaryLink PQC routing: if link has PQC bundle, publish only to PQC endpoint.+        if pqcAvailable, let b64 = link.pqcPublicKey, let bundle = Data(base64Encoded: b64), !bundle.isEmpty {+            if let ok = await publishEncryptedPqc(location: location, recipientID: link.id, bundle: bundle) {+                return ok+            }+            // fallback to RSA+        }+        return await publishLocationClassic(location, toLink: link)+    }++    private func publishLocationClassic(_ location: LocationValue, toLink link: TemporaryLink) async -> Bool {         guard let pemData = Data(base64Encoded: link.publicKey),               let pem = String(data: pemData, encoding: .utf8),               let key = RSAPEM.publicKeyFromPEM(pem)@@ -180,25 +303,53 @@ final class Networking: ObservableObject {         }     } +    private func publishEncryptedPqc(location: LocationValue, recipientID: Int64, bundle: Data) async -> Bool? {+        guard pqcAvailable else { return nil }+        do {+            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)+            let body = encodeJSON([+                "recipientUserID": .uint64(UInt64(bitPattern: recipientID)),+                "encryptedLocation": .string(sealed.base64EncodedString()),+            ])+            let ok = await postBool("/api/location/publish_pqc", body: body)+            print("publishEncryptedPqc to \(UInt64(bitPattern: recipientID)) ok=\(ok) encLen=\(sealed.count)")+            return ok+        } catch {+            print("publishEncryptedPqc error: \(error.localizedDescription)")+            return nil+        }+    }++    // MARK: - Receive (drains both classic + PQC for backward compat)+     func receiveLocations() async -> [LocationValue]? {+        // Always try classic first; then PQC if available. Merge for fleet transition.+        let classic = await receiveLocationsClassic()+        let pqc = await receiveLocationsPqc()+        if classic == nil && pqc == nil { return nil }+        let merged = (classic ?? []) + (pqc ?? [])+        print("receiveLocations merged total=\(merged.count) classic=\(classic?.count ?? -1) pqc=\(pqc?.count ?? -1)")+        return merged+    }++    private func receiveLocationsClassic() async -> [LocationValue]? {         guard let priv = privateKey else { return nil }         let body = Data(#"{"userid": \#(UInt64(bitPattern: userid))}"#.utf8)         do {             let (data, http) = try await client.postJSON(path: "/api/location/receive", jsonBody: body)             networkIsDown = false-            // 204 means "no incoming locations for this user" — treat as success-empty.-            if http.statusCode == 204 || data.isEmpty {-                return []-            }+            if http.statusCode == 204 || data.isEmpty { return [] }             guard http.statusCode == 200 else {-                print("receiveLocations: HTTP \(http.statusCode)")+                print("receiveLocationsClassic: HTTP \(http.statusCode)")                 return nil             }             let arr = try JSONDecoder().decode([String].self, from: data)             var out: [LocationValue] = []             for b64 in arr {                 guard let bytes = Data(base64Encoded: b64) else {-                    print("receiveLocations: skipped non-base64 entry")+                    print("receiveLocationsClassic: skipped non-base64 entry")                     continue                 }                 do {@@ -206,7 +357,6 @@ final class Networking: ObservableObject {                     let comp = try JSONDecoder().decode(LocationValueCompatible.self, from: plain)                     let loc = comp.toLocationValue()                     out.append(loc)-                    // Opportunistically capture peer platform tag from the encrypted payload.                     if let platform = comp.senderPlatform,                        var u = Database.shared.user(id: loc.userid),                        u.platform != platform {@@ -214,10 +364,51 @@ final class Networking: ObservableObject {                         Database.shared.upsertUser(u)                     }                 } catch {-                    print("receiveLocations: decrypt/parse failure: \(error.localizedDescription)")+                    print("receiveLocationsClassic: decrypt/parse failure: \(error.localizedDescription)")+                }+            }+            print("receiveLocationsClassic: \(out.count) location(s) for userid=\(UInt64(bitPattern: userid))")+            return out+        } catch {+            checkNetworkDown(error)+            return nil+        }+    }++    private func receiveLocationsPqc() async -> [LocationValue]? {+        guard pqcAvailable, (try? PQCKeyManager.shared.identity()) != nil else { return [] }+        let body = Data(#"{"userid": \#(UInt64(bitPattern: userid))}"#.utf8)+        do {+            let (data, http) = try await client.postJSON(path: "/api/location/receive_pqc", jsonBody: body)+            networkIsDown = false+            if http.statusCode == 204 || data.isEmpty { return [] }+            guard http.statusCode == 200 else {+                print("receiveLocationsPqc: HTTP \(http.statusCode)")+                return nil+            }+            let arr = try JSONDecoder().decode([String].self, from: data)+            var out: [LocationValue] = []+            for b64 in arr {+                guard let sealed = Data(base64Encoded: b64) else {+                    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,+                       var u = Database.shared.user(id: loc.userid),+                       u.platform != platform {+                        u.platform = platform+                        Database.shared.upsertUser(u)+                    }+                } catch {+                    print("receiveLocationsPqc: decrypt/parse failure: \(error.localizedDescription)")                 }             }-            print("receiveLocations: \(out.count) location(s) for userid=\(UInt64(bitPattern: userid))")+            print("receiveLocationsPqc: \(out.count) location(s) for userid=\(UInt64(bitPattern: userid))")             return out         } catch {             checkNetworkDown(error)@@ -252,17 +443,32 @@ final class Networking: ObservableObject {         _ = await postBool("/api/problem", body: body)     } -    // MARK: - UWB session-setup channel-    //-    // Mirrors the location publish/receive flow but carries the small UWB-    // handshake envelopes (request / ack / config / cancel) end-to-end-    // encrypted. Each payload is at most a few hundred bytes; ranging samples-    // themselves never touch the server.+    // MARK: - UWB session-setup channel (with PQC routing) -    /// Publishes [envelope] to [recipientID]. Resolves the recipient's public-    /// key from the cached `User.encryptionKey` first, then falls back to a-    /// `/api/getkey` lookup. Encrypts with RSA-OAEP/SHA-512.+    /// Publishes [envelope] to [recipientID]. If peer has PQC bundle, publishes ONLY to PQC endpoint.     func publishUwbMessage(_ envelope: UwbEnvelope, to recipientID: Int64) async -> Bool {+        // PQC fast-path+        if pqcAvailable {+            var pqcBundle: Data? = nil+            if let user = Database.shared.user(id: recipientID),+               let b64 = user.pqcEncryptionKey,+               let data = Data(base64Encoded: b64), !data.isEmpty {+                pqcBundle = data+            } else if let data = await getPqcBundle(forUserid: recipientID) {+                pqcBundle = data+            }+            if let bundle = pqcBundle {+                if let ok = await publishUwbMessagePqc(envelope, to: recipientID, bundle: bundle) {+                    return ok+                }+                print("publishUwbMessage PQC failed for \(UInt64(bitPattern: recipientID)), fallback RSA")+            }+        }+        // Classic fallback+        return await publishUwbMessageClassic(envelope, to: recipientID)+    }++    private func publishUwbMessageClassic(_ envelope: UwbEnvelope, to recipientID: Int64) async -> Bool {         let key: SecKey?         if let user = Database.shared.user(id: recipientID),            let encKeyB64 = user.encryptionKey,@@ -285,14 +491,38 @@ final class Networking: ObservableObject {             ])             return await postBool("/api/uwb/publish", body: body)         } catch {-            print("publishUwbMessage encrypt error: \(error)")+            print("publishUwbMessageClassic encrypt error: \(error)")             return false         }     } -    /// Drains incoming UWB envelopes addressed to this user. The server queue-    /// is cleared on receive (same semantics as `/api/location/receive`).+    private func publishUwbMessagePqc(_ envelope: UwbEnvelope, to recipientID: Int64, bundle: Data) async -> Bool? {+        guard pqcAvailable else { return nil }+        do {+            let json = try JSONEncoder().encode(envelope)+            let sealed = try PQCKeyManager.shared.encryptTo(bundle: bundle, plaintext: json)+            let body = encodeJSON([+                "recipientUserID": .uint64(UInt64(bitPattern: recipientID)),+                "encryptedLocation": .string(sealed.base64EncodedString()),+            ])+            let ok = await postBool("/api/uwb/publish_pqc", body: body)+            print("publishUwbMessagePqc to \(UInt64(bitPattern: recipientID)) ok=\(ok)")+            return ok+        } catch {+            print("publishUwbMessagePqc encrypt error: \(error)")+            return nil+        }+    }++    /// Drains incoming UWB envelopes from both classic and PQC queues (merged).     func receiveUwbMessages() async -> [UwbEnvelope]? {+        let classic = await receiveUwbMessagesClassic()+        let pqc = await receiveUwbMessagesPqc()+        if classic == nil && pqc == nil { return nil }+        return (classic ?? []) + (pqc ?? [])+    }++    private func receiveUwbMessagesClassic() async -> [UwbEnvelope]? {         guard let priv = privateKey else { return nil }         let body = Data(#"{"userid": \#(UInt64(bitPattern: userid))}"#.utf8)         do {@@ -316,6 +546,30 @@ final class Networking: ObservableObject {         }     } +    private func receiveUwbMessagesPqc() async -> [UwbEnvelope]? {+        guard pqcAvailable, (try? PQCKeyManager.shared.identity()) != nil else { return [] }+        let body = Data(#"{"userid": \#(UInt64(bitPattern: userid))}"#.utf8)+        do {+            let (data, http) = try await client.postJSON(path: "/api/uwb/receive_pqc", jsonBody: body)+            networkIsDown = false+            if http.statusCode == 204 || data.isEmpty { return [] }+            guard http.statusCode == 200 else { return nil }+            let arr = try JSONDecoder().decode([String].self, from: data)+            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)+                }+            }+            return out+        } catch {+            checkNetworkDown(error)+            return nil+        }+    }+     // MARK: - Helpers      private func postBool(_ path: String, body: Data) async -> Bool {
FindFamilyiOS/Persistence/Database.swift
diff --git a/FindFamilyiOS/Persistence/Database.swift b/FindFamilyiOS/Persistence/Database.swiftindex 2e2821ebff..df2f98a109 100644--- a/FindFamilyiOS/Persistence/Database.swift+++ b/FindFamilyiOS/Persistence/Database.swift@@ -59,6 +59,10 @@ final class Database {         if !columnExists(table: "users", column: "platform") {             exec("ALTER TABLE users ADD COLUMN platform TEXT;")         }+        if !columnExists(table: "users", column: "pqcEncryptionKey") {+            // PQC bundle cache (base64 of [4B kemLen][kemPubDer][dsaPubDer]) — same format as Office.+            exec("ALTER TABLE users ADD COLUMN pqcEncryptionKey TEXT;")+        }         exec("""         CREATE TABLE IF NOT EXISTS waypoints (             id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,@@ -91,6 +95,12 @@ final class Database {             deleteAt INTEGER NOT NULL         );         """)+        if !columnExists(table: "temporaryLinks", column: "pqcPublicKey") {+            exec("ALTER TABLE temporaryLinks ADD COLUMN pqcPublicKey TEXT;")+        }+        if !columnExists(table: "temporaryLinks", column: "pqcKey") {+            exec("ALTER TABLE temporaryLinks ADD COLUMN pqcKey TEXT;")+        }     }      // MARK: - Reload helpers@@ -130,8 +140,8 @@ final class Database {     func upsertUser(_ u: User) {         queue.sync {             let sql = """-            INSERT OR REPLACE INTO users (id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform)-            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);+            INSERT OR REPLACE INTO users (id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform, pqcEncryptionKey)+            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);             """             var stmt: OpaquePointer?             sqlite3_prepare_v2(db, sql, -1, &stmt, nil)@@ -144,6 +154,7 @@ final class Database {             sqlite3_bind_int64(stmt, 7, Int64(u.lastLocationChangeTime.timeIntervalSince1970))             bindOptionalText(stmt, 8, u.encryptionKey)             bindOptionalText(stmt, 9, u.platform)+            bindOptionalText(stmt, 10, u.pqcEncryptionKey)             sqlite3_step(stmt)             sqlite3_finalize(stmt)             usersSubject.send(loadUsers())@@ -161,9 +172,32 @@ final class Database {      private func loadUsers() -> [User] {         var out: [User] = []-        let sql = "SELECT id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform FROM users;"+        // pqcEncryptionKey column added via idempotent migration; SELECT explicitly to handle older dbs.+        let sql = "SELECT id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform, pqcEncryptionKey FROM users;"         var stmt: OpaquePointer?-        sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+        let rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+        if rc != SQLITE_OK {+            // Fallback: older schema without pqcEncryptionKey (should be migrated, but be safe during dev).+            sqlite3_finalize(stmt)+            let sql2 = "SELECT id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform FROM users;"+            sqlite3_prepare_v2(db, sql2, -1, &stmt, nil)+            while sqlite3_step(stmt) == SQLITE_ROW {+                out.append(User(+                    id: sqlite3_column_int64(stmt, 0),+                    name: text(stmt, 1) ?? "",+                    photo: text(stmt, 2),+                    locationName: text(stmt, 3) ?? "",+                    sendingEnabled: sqlite3_column_int(stmt, 4) != 0,+                    requestStatus: RequestStatus(rawValue: text(stmt, 5) ?? "MUTUAL_CONNECTION") ?? .mutualConnection,+                    lastLocationChangeTime: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))),+                    encryptionKey: text(stmt, 7),+                    platform: text(stmt, 8),+                    pqcEncryptionKey: nil+                ))+            }+            sqlite3_finalize(stmt)+            return out+        }         while sqlite3_step(stmt) == SQLITE_ROW {             out.append(User(                 id: sqlite3_column_int64(stmt, 0),@@ -174,7 +208,8 @@ final class Database {                 requestStatus: RequestStatus(rawValue: text(stmt, 5) ?? "MUTUAL_CONNECTION") ?? .mutualConnection,                 lastLocationChangeTime: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))),                 encryptionKey: text(stmt, 7),-                platform: text(stmt, 8)+                platform: text(stmt, 8),+                pqcEncryptionKey: text(stmt, 9)             ))         }         sqlite3_finalize(stmt)@@ -299,18 +334,20 @@ final class Database {         var result = link         queue.sync {             if link.id == 0 {-                let sql = "INSERT INTO temporaryLinks (name, key, publicKey, deleteAt) VALUES (?, ?, ?, ?);"+                let sql = "INSERT INTO temporaryLinks (name, key, publicKey, deleteAt, pqcPublicKey, pqcKey) VALUES (?, ?, ?, ?, ?, ?);"                 var stmt: OpaquePointer?                 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)                 bindText(stmt, 1, link.name)                 bindText(stmt, 2, link.key)                 bindText(stmt, 3, link.publicKey)                 sqlite3_bind_int64(stmt, 4, Int64(link.deleteAt.timeIntervalSince1970))+                bindOptionalText(stmt, 5, link.pqcPublicKey)+                bindOptionalText(stmt, 6, link.pqcKey)                 sqlite3_step(stmt)                 sqlite3_finalize(stmt)                 result.id = sqlite3_last_insert_rowid(db)             } else {-                let sql = "INSERT OR REPLACE INTO temporaryLinks (id, name, key, publicKey, deleteAt) VALUES (?, ?, ?, ?, ?);"+                let sql = "INSERT OR REPLACE INTO temporaryLinks (id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey) VALUES (?, ?, ?, ?, ?, ?, ?);"                 var stmt: OpaquePointer?                 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)                 sqlite3_bind_int64(stmt, 1, link.id)@@ -318,6 +355,8 @@ final class Database {                 bindText(stmt, 3, link.key)                 bindText(stmt, 4, link.publicKey)                 sqlite3_bind_int64(stmt, 5, Int64(link.deleteAt.timeIntervalSince1970))+                bindOptionalText(stmt, 6, link.pqcPublicKey)+                bindOptionalText(stmt, 7, link.pqcKey)                 sqlite3_step(stmt)                 sqlite3_finalize(stmt)             }@@ -335,16 +374,37 @@ final class Database {      private func loadTemporaryLinks() -> [TemporaryLink] {         var out: [TemporaryLink] = []-        let sql = "SELECT id, name, key, publicKey, deleteAt FROM temporaryLinks;"+        // Try new schema first; fallback to old if column missing.+        let sql = "SELECT id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey FROM temporaryLinks;"         var stmt: OpaquePointer?-        sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+        let rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+        if rc != SQLITE_OK {+            sqlite3_finalize(stmt)+            let sql2 = "SELECT id, name, key, publicKey, deleteAt FROM temporaryLinks;"+            sqlite3_prepare_v2(db, sql2, -1, &stmt, nil)+            while sqlite3_step(stmt) == SQLITE_ROW {+                out.append(TemporaryLink(+                    id: sqlite3_column_int64(stmt, 0),+                    name: text(stmt, 1) ?? "",+                    key: text(stmt, 2) ?? "",+                    publicKey: text(stmt, 3) ?? "",+                    deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4))),+                    pqcPublicKey: nil,+                    pqcKey: nil+                ))+            }+            sqlite3_finalize(stmt)+            return out+        }         while sqlite3_step(stmt) == SQLITE_ROW {             out.append(TemporaryLink(                 id: sqlite3_column_int64(stmt, 0),                 name: text(stmt, 1) ?? "",                 key: text(stmt, 2) ?? "",                 publicKey: text(stmt, 3) ?? "",-                deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4)))+                deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4))),+                pqcPublicKey: text(stmt, 5),+                pqcKey: text(stmt, 6)             ))         }         sqlite3_finalize(stmt)
FindFamilyiOS/UI/Cards.swift
diff --git a/FindFamilyiOS/UI/Cards.swift b/FindFamilyiOS/UI/Cards.swiftindex 89562f133f..b939aa1164 100644--- a/FindFamilyiOS/UI/Cards.swift+++ b/FindFamilyiOS/UI/Cards.swift@@ -151,10 +151,20 @@ struct TemporaryLinkCard: View {                 Text(Strings.expires(TimeFormatting.timestring(link.deleteAt, future: true)))                     .font(.caption2)                     .foregroundStyle(.secondary)+                if link.pqcPublicKey != nil {+                    Text("PQC enabled").font(.caption2).foregroundStyle(.green)+                }             }             Spacer()             Button {-                let url = "https://findfamily.cc/view/\(UInt64(bitPattern: link.id))#key=\(link.key)"+                // PQC routing: include PQC private bundle fragment when available.+                // Fragment never hits server; classic #key= still present for backward compat.+                let base = "https://findfamily.cc/view/\(UInt64(bitPattern: link.id))#key=\(link.key)"+                let url = if let pqcPriv = link.pqcKey {+                    "\(base)&pqc_key=\(pqcPriv)"+                } else {+                    base+                }                 Platform.copy(url)             } label: { Image(systemName: "doc.on.doc") }             Button(role: .destructive) {
FindFamilyiOS/UI/Dialogs.swift
diff --git a/FindFamilyiOS/UI/Dialogs.swift b/FindFamilyiOS/UI/Dialogs.swiftindex 6b0998e118..34a9fedc64 100644--- a/FindFamilyiOS/UI/Dialogs.swift+++ b/FindFamilyiOS/UI/Dialogs.swift@@ -125,7 +125,8 @@ struct AddPersonDialog: View {             sendingEnabled: true,             requestStatus: newStatus,             lastLocationChangeTime: Date(),-            encryptionKey: nil+            encryptionKey: nil,+            pqcEncryptionKey: nil         )         Database.shared.upsertUser(user)         isPresented = false@@ -201,12 +202,24 @@ struct AddLinkDialog: View {                 let pubPEM = try RSAPEM.publicKeyToPEM(pub)                 let priB64 = Data(priPEM.utf8).base64EncodedString()                 let pubB64 = Data(pubPEM.utf8).base64EncodedString()+                // PQC ephemeral — best effort, RSA still works if native not linked.+                var pqcPublicB64: String? = nil+                var pqcPrivateB64: String? = nil+                do {+                    let ep = try PQCKeyManager.shared.generateEphemeralBundle()+                    pqcPublicB64 = ep.publicB64+                    pqcPrivateB64 = ep.privateB64+                } catch {+                    print("AddLink: PQC ephemeral unavailable (native not linked?): \(error.localizedDescription)")+                }                 let link = TemporaryLink(                     id: 0,                     name: name.trimmingCharacters(in: .whitespaces),                     key: priB64,                     publicKey: pubB64,-                    deleteAt: Date().addingTimeInterval(expirySeconds)+                    deleteAt: Date().addingTimeInterval(expirySeconds),+                    pqcPublicKey: pqcPublicB64,+                    pqcKey: pqcPrivateB64                 )                 _ = Database.shared.upsertTemporaryLink(link)             } catch {