findfamily: post-quantum only networking with peer-needs-update alert
- Commit
638fd153efe7b15cc8d2c8e5d7016b2cefb54791- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 16:24 UTC (3 months ago)
- Parents
5ea4d53
Diff
FindFamilyiOS/Crypto/Crypto.swift
diff --git a/FindFamilyiOS/Crypto/Crypto.swift b/FindFamilyiOS/Crypto/Crypto.swiftindex 5f044112db..e60eea816a 100644--- a/FindFamilyiOS/Crypto/Crypto.swift+++ b/FindFamilyiOS/Crypto/Crypto.swift@@ -61,303 +61,11 @@ enum Keychain { } } -// MARK: - RSA Key Manager--/// Manages a single device-wide RSA-OAEP-SHA512 key pair. 4096-bit keys to match the-/// Android implementation's effective payload limits (LocationValue JSON > 126 bytes).-final class RSAKeyManager {- static let shared = RSAKeyManager()-- private let keySize = 4096- private var _privateKey: SecKey?- private var _publicKey: SecKey?-- private init() {}-- /// Returns the device key pair, generating + persisting it on first use.- func keyPair() throws -> (privateKey: SecKey, publicKey: SecKey) {- if let pri = _privateKey, let pub = _publicKey {- return (pri, pub)- }- // Try to restore from keychain.- if let priDER = Keychain.getData(key: "rsaPrivateDER"),- let pri = importPrivateKey(der: priDER),- let pub = SecKeyCopyPublicKey(pri) {- _privateKey = pri- _publicKey = pub- return (pri, pub)- }- // Generate new.- let attrs: [String: Any] = [- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,- kSecAttrKeySizeInBits as String: keySize,- ]- var error: Unmanaged<CFError>?- guard let pri = SecKeyCreateRandomKey(attrs as CFDictionary, &error),- let pub = SecKeyCopyPublicKey(pri) else {- throw error?.takeRetainedValue() as Error? ?? NSError(domain: "rsa", code: -1)- }- // Persist private key DER (PKCS#1 RSAPrivateKey format that SecKey returns natively).- var error2: Unmanaged<CFError>?- guard let priData = SecKeyCopyExternalRepresentation(pri, &error2) as Data? else {- throw error2?.takeRetainedValue() as Error? ?? NSError(domain: "rsa", code: -2)- }- Keychain.setData(priData, key: "rsaPrivateDER")- _privateKey = pri- _publicKey = pub- return (pri, pub)- }-- /// Generate a fresh, ephemeral key pair (used for TemporaryLink share URLs).- func generateEphemeralKeyPair() throws -> (privateKey: SecKey, publicKey: SecKey) {- let attrs: [String: Any] = [- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,- kSecAttrKeySizeInBits as String: keySize,- ]- var error: Unmanaged<CFError>?- guard let pri = SecKeyCreateRandomKey(attrs as CFDictionary, &error),- let pub = SecKeyCopyPublicKey(pri) else {- throw error?.takeRetainedValue() as Error? ?? NSError(domain: "rsa", code: -1)- }- return (pri, pub)- }-- private func importPrivateKey(der: Data) -> SecKey? {- let attrs: [String: Any] = [- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,- kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,- kSecAttrKeySizeInBits as String: keySize,- ]- var err: Unmanaged<CFError>?- return SecKeyCreateWithData(der as CFData, attrs as CFDictionary, &err)- }-- func importPublicKey(der: Data) -> SecKey? {- // Parse the modulus length from PKCS#1 so we don't have to assume the size- // matches our own key — peers (e.g. Android) may use a different bit length.- let bits = RSAPEM.rsaModulusBits(pkcs1DER: der) ?? 2048- let attrs: [String: Any] = [- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,- kSecAttrKeyClass as String: kSecAttrKeyClassPublic,- kSecAttrKeySizeInBits as String: bits,- ]- var err: Unmanaged<CFError>?- return SecKeyCreateWithData(der as CFData, attrs as CFDictionary, &err)- }-- func encryptOAEPSHA512(_ data: Data, publicKey: SecKey) throws -> Data {- var err: Unmanaged<CFError>?- guard let out = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionOAEPSHA512, data as CFData, &err) as Data? else {- throw err?.takeRetainedValue() as Error? ?? NSError(domain: "rsa", code: -3)- }- return out- }-- func decryptOAEPSHA512(_ data: Data, privateKey: SecKey) throws -> Data {- var err: Unmanaged<CFError>?- guard let out = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionOAEPSHA512, data as CFData, &err) as Data? else {- throw err?.takeRetainedValue() as Error? ?? NSError(domain: "rsa", code: -4)- }- return out- }-}--// MARK: - PEM ↔ DER ↔ SecKey conversions--/// SecKey for RSA returns/accepts PKCS#1 DER. Most PEM PUBLIC KEY blocks use X.509-/// SubjectPublicKeyInfo, and PEM PRIVATE KEY blocks use PKCS#8. We wrap/unwrap here.-enum RSAPEM {-- static let rsaOID: [UInt8] = [- 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 // 1.2.840.113549.1.1.1- ]-- // MARK: - Public key-- /// Wrap PKCS#1 RSAPublicKey into X.509 SubjectPublicKeyInfo PEM.- static func publicKeyToPEM(_ key: SecKey) throws -> String {- var err: Unmanaged<CFError>?- guard let pkcs1 = SecKeyCopyExternalRepresentation(key, &err) as Data? else {- throw err?.takeRetainedValue() as Error? ?? NSError(domain: "pem", code: -1)- }- let der = wrapX509SPKI(pkcs1: pkcs1)- return wrapPEM(label: "PUBLIC KEY", der: der)- }-- /// Parse a PEM PUBLIC KEY (X.509 SPKI or PKCS#1) into SecKey.- static func publicKeyFromPEM(_ pem: String) -> SecKey? {- guard let der = unwrapPEM(pem) else { return nil }- let pkcs1 = stripX509SPKI(der: der) ?? der- return RSAKeyManager.shared.importPublicKey(der: pkcs1)- }-- // MARK: - Private key-- /// Wrap PKCS#1 RSAPrivateKey into PKCS#8 PrivateKeyInfo PEM.- static func privateKeyToPEM(_ key: SecKey) throws -> String {- var err: Unmanaged<CFError>?- guard let pkcs1 = SecKeyCopyExternalRepresentation(key, &err) as Data? else {- throw err?.takeRetainedValue() as Error? ?? NSError(domain: "pem", code: -1)- }- let der = wrapPKCS8(pkcs1: pkcs1)- return wrapPEM(label: "PRIVATE KEY", der: der)- }-- // MARK: - PEM framing helpers-- static func wrapPEM(label: String, der: Data) -> String {- let b64 = der.base64EncodedString()- // 64-char lines per RFC 7468.- var lines: [String] = []- var idx = b64.startIndex- while idx < b64.endIndex {- let end = b64.index(idx, offsetBy: 64, limitedBy: b64.endIndex) ?? b64.endIndex- lines.append(String(b64[idx..<end]))- idx = end- }- return "-----BEGIN \(label)-----\n" + lines.joined(separator: "\n") + "\n-----END \(label)-----\n"- }-- static func unwrapPEM(_ pem: String) -> Data? {- let lines = pem.split(separator: "\n").map(String.init)- let body = lines- .filter { !$0.hasPrefix("-----") }- .joined()- .filter { !$0.isWhitespace }- return Data(base64Encoded: body)- }-- // MARK: - ASN.1 helpers-- /// Wrap a PKCS#1 RSAPublicKey into X.509 SubjectPublicKeyInfo.- static func wrapX509SPKI(pkcs1: Data) -> Data {- // AlgorithmIdentifier ::= SEQUENCE { OID rsaEncryption, NULL }- let alg = asn1Sequence(asn1OID(rsaOID) + asn1Null())- // BIT STRING with 0 unused bits + PKCS#1 RSAPublicKey- let bitString = asn1BitString(content: pkcs1)- return asn1Sequence(alg + bitString)- }-- /// Strip the X.509 wrapping (if present) and return the inner PKCS#1 bytes. Best-effort.- static func stripX509SPKI(der: Data) -> Data? {- var p = ASN1Parser(data: der)- guard let outerSeq = p.readSequence() else { return nil }- var inner = ASN1Parser(data: outerSeq)- guard inner.skipSequence() else { return nil } // AlgorithmIdentifier- guard let bits = inner.readBitString() else { return nil }- return bits- }-- /// Parse the modulus bit length from a PKCS#1 RSAPublicKey or RSAPrivateKey DER.- /// PKCS#1: SEQUENCE { INTEGER modulus, INTEGER exponent, ... }- /// For PKCS#1 private keys: SEQUENCE { INTEGER version=0, INTEGER modulus, INTEGER exponent, ... }- static func rsaModulusBits(pkcs1DER: Data) -> Int? {- var parser = ASN1Parser(data: pkcs1DER)- guard let seq = parser.readSequence() else { return nil }- var inner = ASN1Parser(data: seq)- // First INTEGER might be a version (private keys) or the modulus (public keys).- guard var firstInt = inner.readTag(0x02) else { return nil }- // Heuristic: if it's a single byte (version), the next INTEGER is the modulus.- if firstInt.count <= 4 {- guard let modulus = inner.readTag(0x02) else { return nil }- firstInt = modulus- }- // Strip leading 0x00 if present (DER INTEGER sign byte).- var bytes = firstInt- if let f = bytes.first, f == 0 { bytes = bytes.dropFirst() }- return bytes.count * 8- }-- /// Wrap a PKCS#1 RSAPrivateKey into PKCS#8 PrivateKeyInfo.- static func wrapPKCS8(pkcs1: Data) -> Data {- let version = asn1Integer(value: 0)- let alg = asn1Sequence(asn1OID(rsaOID) + asn1Null())- let octet = asn1OctetString(content: pkcs1)- return asn1Sequence(version + alg + octet)- }-- static func asn1Sequence(_ content: Data) -> Data {- Data([0x30]) + asn1Length(content.count) + content- }- static func asn1OctetString(content: Data) -> Data {- Data([0x04]) + asn1Length(content.count) + content- }- static func asn1BitString(content: Data) -> Data {- // 0 unused bits.- Data([0x03]) + asn1Length(content.count + 1) + Data([0x00]) + content- }- static func asn1Null() -> Data { Data([0x05, 0x00]) }- static func asn1OID(_ bytes: [UInt8]) -> Data {- Data([0x06]) + asn1Length(bytes.count) + Data(bytes)- }- static func asn1Integer(value: UInt8) -> Data {- Data([0x02, 0x01, value])- }-- static func asn1Length(_ length: Int) -> Data {- if length < 0x80 { return Data([UInt8(length)]) }- var len = length- var bytes: [UInt8] = []- while len > 0 {- bytes.insert(UInt8(len & 0xFF), at: 0)- len >>= 8- }- return Data([0x80 | UInt8(bytes.count)]) + Data(bytes)- }-}--/// Minimal ASN.1 parser sufficient for unwrapping X.509 SPKI.-private struct ASN1Parser {- let data: Data- var offset: Int = 0-- init(data: Data) { self.data = data }-- mutating func readByte() -> UInt8? {- guard offset < data.count else { return nil }- let b = data[data.startIndex + offset]- offset += 1- return b- }-- mutating func readLength() -> Int? {- guard let first = readByte() else { return nil }- if first < 0x80 { return Int(first) }- let count = Int(first & 0x7F)- guard count > 0, count <= 8 else { return nil }- var len = 0- for _ in 0..<count {- guard let b = readByte() else { return nil }- len = (len << 8) | Int(b)- }- return len- }-- mutating func readTag(_ tag: UInt8) -> Data? {- guard let t = readByte(), t == tag else { return nil }- guard let len = readLength() else { return nil }- let start = data.startIndex + offset- guard offset + len <= data.count else { return nil }- let bytes = data.subdata(in: start..<(start + len))- offset += len- return bytes- }-- mutating func readSequence() -> Data? { readTag(0x30) }-- mutating func skipSequence() -> Bool { readSequence() != nil }-- mutating func readBitString() -> Data? {- guard let bs = readTag(0x03) else { return nil }- guard let first = bs.first, first == 0 else { return nil }- return bs.dropFirst()- }-}--// MARK: - Security code formatting (shared by PQC + RSA safety numbers)+// MARK: - Security code formatting (safety numbers) /// Formats an iterated hash into a 6-group, 5-digit safety number, and runs the shared /// canonical-order iterated-SHA256 computation. Identical to Kotlin `SecurityCode`.+/// Used by the post-quantum safety number (`PQCSecurityCode`). enum SecurityCodeFormat { static let iterations = 4000 @@ -389,21 +97,6 @@ enum SecurityCodeFormat { } } -// MARK: - RSA security code (safety number over canonical X.509 SPKI DER)--/// Computes the RSA safety number matching Android's `E2ee.securityCode`, which hashes the-/// **canonical DER** (X.509 SubjectPublicKeyInfo) of each RSA public key. iOS `SecKey` gives-/// PKCS#1, so we wrap to SPKI first to match the Android encoding byte-for-byte. Callers pass-/// the two canonical DERs to `SecurityCodeFormat.compute` (run off the main actor).-enum RSASecurityCode {- /// Canonical X.509 SPKI DER for an RSA public SecKey (PKCS#1 → SPKI), matching Android.- static func canonicalDER(_ key: SecKey) -> Data? {- var err: Unmanaged<CFError>?- guard let pkcs1 = SecKeyCopyExternalRepresentation(key, &err) as Data? else { return nil }- return RSAPEM.wrapX509SPKI(pkcs1: pkcs1)- }-}- // MARK: - Base26 /// Encodes a Long id using uppercase A..Z digits. Mirrors `encodeBase26` in the Modern-Apps library.
FindFamilyiOS/Networking/Networking.swift
diff --git a/FindFamilyiOS/Networking/Networking.swift b/FindFamilyiOS/Networking/Networking.swiftindex 278cb04712..a8e70ee9cc 100644--- a/FindFamilyiOS/Networking/Networking.swift+++ b/FindFamilyiOS/Networking/Networking.swift@@ -48,11 +48,7 @@ final class Networking: ObservableObject { 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+ // PQC identity — mirrors Office/FF Android ff_pqc prefix. FindFamily is post-quantum only. private var pqcPublicBundleB64: String = "" private var pqcIdentity: PQCIdentity? var pqcAvailable: Bool { pqcIdentity != nil }@@ -67,43 +63,34 @@ final class Networking: ObservableObject { private init() {} func start() async {- do {- // Stable identity: only generate userid on first launch.- if let stored = Keychain.getInt64(key: "userid"), stored != 0 {- userid = stored- } else {- 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 = ""- }+ // Stable identity: only generate userid on first launch.+ if let stored = Keychain.getInt64(key: "userid"), stored != 0 {+ userid = stored+ } else {+ userid = Int64.random(in: Int64.min...Int64.max)+ Keychain.setInt64(userid, key: "userid")+ } - isReady = true- ensureMeUserExists()- // Apply any auto-toggle timers that fell due while the app was not running- // (mirrors Android's cold-start applyDueAutoToggles in the ViewModel init).- Database.shared.applyDueAutoToggles(now: Date())- _ = await ensureUserExists()+ // PQC identity — post-quantum only. If the Rust XCFramework isn't linked this throws and+ // pqcAvailable stays false; the app cannot share until the native lib is present. There is+ // deliberately no RSA fallback.+ 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.start error: \(error)")+ print("Networking: PQC unavailable (native not linked?): \(error.localizedDescription)")+ pqcIdentity = nil+ pqcPublicBundleB64 = "" }++ isReady = true+ ensureMeUserExists()+ // Apply any auto-toggle timers that fell due while the app was not running+ // (mirrors Android's cold-start applyDueAutoToggles in the ViewModel init).+ Database.shared.applyDueAutoToggles(now: Date())+ _ = await ensureUserExists() } /// Ensure there's a "Me" entry in the users table representing the device owner.@@ -128,15 +115,6 @@ final class Networking: ObservableObject { // MARK: - Endpoints - func register() async -> Bool {- guard !publicKeyPEMBase64.isEmpty else { return false }- let body = encodeJSON([- "userid": .uint64(UInt64(bitPattern: userid)),- "key": .string(publicKeyPEMBase64),- ])- return await postBool("/api/register", body: body)- }- func registerPqc() async -> Bool { guard !pqcPublicBundleB64.isEmpty else { return false } let body = encodeJSON([@@ -149,96 +127,70 @@ final class Networking: ObservableObject { } func ensureUserExists() async -> Bool {- var ok = true- // RSA self-heal: re-register if the server has no key OR a key that differs from ours.- // A DataStore/Keychain race on first launch could have registered an ephemeral key, so- // peers would encrypt to the wrong pubkey. Detect the mismatch by comparing the base64- // of the server's returned public key against our own PEM.- if let serverKey = await getKey(forUserid: userid) {- if let serverPem = try? RSAPEM.publicKeyToPEM(serverKey) {- let serverB64 = Data(serverPem.utf8).base64EncodedString()- if serverB64 != publicKeyPEMBase64 {- print("Networking: server RSA key mismatch for self, re-registering")- ok = await register() && ok- }- }- } else {- ok = await register() && ok- }- // PQC self-healing: same missing-or-mismatched detection for the PQC bundle.- if pqcAvailable {- if let serverBundle = await getPqcKeyRaw(forUserid: userid) {- if serverBundle.base64EncodedString() != pqcPublicBundleB64 {- print("Networking: server PQC bundle mismatch for self, re-registering")- ok = await registerPqc() && ok- }- } else {- ok = await registerPqc() && ok+ // PQC-only: register/self-heal the post-quantum bundle. Without PQC there is nothing to+ // register and the app cannot share until the native lib is present.+ guard pqcAvailable else { return false }+ if let serverBundle = await getPqcKeyRaw(forUserid: userid) {+ if serverBundle.base64EncodedString() != pqcPublicBundleB64 {+ print("Networking: server PQC bundle mismatch for self, re-registering")+ return await registerPqc() }+ return true }- return ok+ return await registerPqc() } - /// GET-style lookup: server returns the raw base64-PEM string in the response body.- func getKey(forUserid id: Int64) async -> SecKey? {+ /// 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- guard http.statusCode == 200 else { return nil }- // The response body is a raw base64(PEM) string (no JSON wrapping).- guard let pemB64 = String(data: data, encoding: .utf8)?- .trimmingCharacters(in: .whitespacesAndNewlines)- .trimmingCharacters(in: CharacterSet(charactersIn: "\""))- else { return nil }- guard let pemData = Data(base64Encoded: pemB64),- let pem = String(data: pemData, encoding: .utf8)- else { return nil }- return RSAPEM.publicKeyFromPEM(pem)+ return http.statusCode == 200 && !data.isEmpty } catch { checkNetworkDown(error)- return nil+ return false } } - /// Computes the RSA verification "security code" (safety number) for a connection: a- /// fingerprint of both this device's and [user]'s public keys, identical on both peers.- /// Comparing them out-of-band confirms no key was substituted. Returns nil if the peer's- /// key isn't known yet.- ///- /// Prefers the PQC (quantum-safe) code when both sides support PQC, falling back to the RSA- /// code otherwise. The choice is symmetric: PQC is used iff this device is PQC-capable AND the- /// peer has a PQC bundle available, so if either side lacks PQC both compute the RSA code.- /// The heavy SHA-256 ×4000 runs off the main actor (`Networking` is @MainActor); only `Data`- /// (Sendable) crosses the boundary.- func securityCode(for user: User) async -> String? {- // Prefer PQC when both sides support it.- if pqcAvailable, let myBundle = pqcIdentity?.publicBundle,- let peerBundle = await resolvedPqcBundle(for: user) {- return await Task.detached(priority: .userInitiated) {- PQCSecurityCode.compute(myBundle: myBundle, theirBundle: peerBundle)- }.value- }- // RSA fallback.- guard let selfPub = publicKey else { return nil }- // Prefer the cached peer key; otherwise fetch and cache it atomically.- var peerKey: SecKey?- if let encKeyB64 = user.encryptionKey,- let pemData = Data(base64Encoded: encKeyB64),- let pem = String(data: pemData, encoding: .utf8) {- peerKey = RSAPEM.publicKeyFromPEM(pem)- }- if peerKey == nil, let k = await getKey(forUserid: user.id) {- if let pem = try? RSAPEM.publicKeyToPEM(k) {- Database.shared.setEncryptionKey(id: user.id, encryptionKey: Data(pem.utf8).base64EncodedString())- }- peerKey = k+ /// 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 }- guard let peer = peerKey else { return nil }- guard let myDer = RSASecurityCode.canonicalDER(selfPub),- let theirDer = RSASecurityCode.canonicalDER(peer) else { return nil }+ }++ /// 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)+ }++ /// 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+ }++ /// Computes the quantum-safe verification "security code" (safety number) for a connection:+ /// a fingerprint of both this device's and [user]'s PQC bundles, identical on both peers.+ /// Returns nil if PQC is unavailable locally or the peer has no PQC bundle. The heavy+ /// SHA-256 ×4000 runs off the main actor.+ func securityCode(for user: User) async -> String? {+ guard pqcAvailable, let myBundle = pqcIdentity?.publicBundle,+ let peerBundle = await resolvedPqcBundle(for: user) else { return nil } return await Task.detached(priority: .userInitiated) {- SecurityCodeFormat.compute(myDer, theirDer)+ PQCSecurityCode.compute(myBundle: myBundle, theirBundle: peerBundle) }.value } @@ -276,18 +228,14 @@ final class Networking: ObservableObject { return nil } - // MARK: - Publish Location (PQC routing: if peer has PQC key, ONLY use PQC endpoint)+ // MARK: - Publish Location (post-quantum only) 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")+ guard let bundle = await resolvedPqcBundle(for: user) else {+ print("Networking: publishLocation no PQC bundle for \(UInt64(bitPattern: user.id)); peer must update")+ return false }- return await publishLocationClassic(location, toUser: user)+ return await publishEncryptedPqc(location: location, recipientID: user.id, bundle: bundle) ?? false } private func resolvedPqcBundle(for user: User) async -> Data? {@@ -302,58 +250,11 @@ final class Networking: ObservableObject { 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),- let pem = String(data: pemData, encoding: .utf8),- let k = RSAPEM.publicKeyFromPEM(pem) {- key = k- } else if let k = await getKey(forUserid: user.id) {- if let pem = try? RSAPEM.publicKeyToPEM(k) {- let b64 = Data(pem.utf8).base64EncodedString()- Database.shared.setEncryptionKey(id: user.id, encryptionKey: b64)- }- key = k- } else {- key = nil- }- guard let k = key else { return false }- return await publishEncrypted(location: location, recipientID: user.id, key: k)- }- 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)- else { return false }- return await publishEncrypted(location: location, recipientID: link.id, key: key)- }-- private func publishEncrypted(location: LocationValue, recipientID: Int64, key: SecKey) async -> Bool {- do {- let json = try JSONEncoder().encode(location.toCompatible(senderPlatform: Self.platformTag))- let cipher = try RSAKeyManager.shared.encryptOAEPSHA512(json, publicKey: key)- let body = encodeJSON([- "recipientUserID": .uint64(UInt64(bitPattern: recipientID)),- "encryptedLocation": .string(cipher.base64EncodedString()),- ])- return await postBool("/api/location/publish", body: body)- } catch {- print("publishEncrypted error: \(error)")+ guard pqcAvailable, let b64 = link.pqcPublicKey, let bundle = Data(base64Encoded: b64), !bundle.isEmpty else { return false }+ return await publishEncryptedPqc(location: location, recipientID: link.id, bundle: bundle) ?? false } private func publishEncryptedPqc(location: LocationValue, recipientID: Int64, bundle: Data) async -> Bool? {@@ -375,56 +276,10 @@ final class Networking: ObservableObject { } } - // MARK: - Receive (drains both classic + PQC for backward compat)+ // MARK: - Receive (post-quantum only) 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- if http.statusCode == 204 || data.isEmpty { return [] }- guard http.statusCode == 200 else {- 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("receiveLocationsClassic: skipped non-base64 entry")- continue- }- do {- let plain = try RSAKeyManager.shared.decryptOAEPSHA512(bytes, privateKey: priv)- 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("receiveLocationsClassic: decrypt/parse failure: \(error.localizedDescription)")- }- }- print("receiveLocationsClassic: \(out.count) location(s) for userid=\(UInt64(bitPattern: userid))")- return out- } catch {- checkNetworkDown(error)- return nil- }+ return await receiveLocationsPqc() } private func receiveLocationsPqc() async -> [LocationValue]? {@@ -494,57 +349,25 @@ final class Networking: ObservableObject { _ = await postBool("/api/problem", body: body) } - // MARK: - UWB session-setup channel (with PQC routing)+ // MARK: - UWB session-setup channel (post-quantum only) - /// Publishes [envelope] to [recipientID]. If peer has PQC bundle, publishes ONLY to PQC endpoint.+ /// Publishes [envelope] to [recipientID] via the peer's PQC bundle. Returns false if the peer+ /// has no PQC bundle (they are on an outdated app). 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?+ guard pqcAvailable else { return false }+ var pqcBundle: Data? = nil if let user = Database.shared.user(id: recipientID),- let encKeyB64 = user.encryptionKey,- let pemData = Data(base64Encoded: encKeyB64),- let pem = String(data: pemData, encoding: .utf8),- let k = RSAPEM.publicKeyFromPEM(pem) {- key = k- } else if let k = await getKey(forUserid: recipientID) {- key = k- } else {- key = nil+ let b64 = user.pqcEncryptionKey,+ let data = Data(base64Encoded: b64), !data.isEmpty {+ pqcBundle = data+ } else if let data = await getPqcBundle(forUserid: recipientID) {+ pqcBundle = data }- guard let k = key else { return false }- do {- let json = try JSONEncoder().encode(envelope)- let cipher = try RSAKeyManager.shared.encryptOAEPSHA512(json, publicKey: k)- let body = encodeJSON([- "recipientUserID": .uint64(UInt64(bitPattern: recipientID)),- "encryptedLocation": .string(cipher.base64EncodedString()),- ])- return await postBool("/api/uwb/publish", body: body)- } catch {- print("publishUwbMessageClassic encrypt error: \(error)")+ guard let bundle = pqcBundle else {+ print("publishUwbMessage: no PQC bundle for \(UInt64(bitPattern: recipientID)); peer must update") return false }+ return await publishUwbMessagePqc(envelope, to: recipientID, bundle: bundle) ?? false } private func publishUwbMessagePqc(_ envelope: UwbEnvelope, to recipientID: Int64, bundle: Data) async -> Bool? {@@ -565,36 +388,9 @@ final class Networking: ObservableObject { } } - /// Drains incoming UWB envelopes from both classic and PQC queues (merged).+ /// Drains incoming UWB envelopes from the PQC queue (post-quantum only). 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 {- let (data, http) = try await client.postJSON(path: "/api/uwb/receive", 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 bytes = Data(base64Encoded: b64) else { continue }- if let plain = try? RSAKeyManager.shared.decryptOAEPSHA512(bytes, privateKey: priv),- let env = try? JSONDecoder().decode(UwbEnvelope.self, from: plain) {- out.append(env)- }- }- return out- } catch {- checkNetworkDown(error)- return nil- }+ return await receiveUwbMessagesPqc() } private func receiveUwbMessagesPqc() async -> [UwbEnvelope]? {
FindFamilyiOS/UI/Dialogs.swift
diff --git a/FindFamilyiOS/UI/Dialogs.swift b/FindFamilyiOS/UI/Dialogs.swiftindex 12c576d678..5f12d800c6 100644--- a/FindFamilyiOS/UI/Dialogs.swift+++ b/FindFamilyiOS/UI/Dialogs.swift@@ -10,6 +10,7 @@ struct AddPersonDialog: View { @State private var contactName: String? @State private var contactPhoto: String? @State private var justCopied = false+ @State private var showNeedsUpdate = false private var myIDStr: String { Base26.encode(Networking.shared.userid) } @@ -123,26 +124,42 @@ struct AddPersonDialog: View { Button(Strings.cancelButton) { isPresented = false } } }+ .alert(Strings.outdatedPeerTitle, isPresented: $showNeedsUpdate) {+ Button(Strings.okButton, role: .cancel) {}+ } message: {+ Text(Strings.outdatedPeerMessage)+ } } } private func submit() { guard let id = theirID, let name = contactName else { return }- let isAccepting = (status == .awaitingRequest)- let newStatus: RequestStatus = isAccepting ? .mutualConnection : .awaitingResponse- let user = User(- id: id,- name: name,- photo: contactPhoto,- locationName: "Unknown Location",- sendingEnabled: true,- requestStatus: newStatus,- lastLocationChangeTime: Date(),- encryptionKey: nil,- pqcEncryptionKey: nil- )- Database.shared.upsertUser(user)- isPresented = false+ // Check the peer's post-quantum capability "when connecting". FindFamily is PQC-only, so a+ // 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.+ Task { @MainActor in+ let peerStatus = await Networking.shared.peerCryptoStatus(forUserid: id)+ if peerStatus == .needsUpdate {+ showNeedsUpdate = true+ return+ }+ let isAccepting = (status == .awaitingRequest)+ let newStatus: RequestStatus = isAccepting ? .mutualConnection : .awaitingResponse+ let user = User(+ id: id,+ name: name,+ photo: contactPhoto,+ locationName: "Unknown Location",+ sendingEnabled: true,+ requestStatus: newStatus,+ lastLocationChangeTime: Date(),+ encryptionKey: nil,+ pqcEncryptionKey: nil+ )+ Database.shared.upsertUser(user)+ isPresented = false+ } } private func copyMyID() {@@ -263,21 +280,9 @@ struct AddLinkDialog: View { working = true Task { do {- let (priv, pub) = try RSAKeyManager.shared.generateEphemeralKeyPair()- let priPEM = try RSAPEM.privateKeyToPEM(priv)- 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)")- }+ // Links are post-quantum only: generate a PQC ephemeral bundle. There is no RSA+ // fallback, so this fails the creation rather than downgrading to classic crypto.+ let ep = try PQCKeyManager.shared.generateEphemeralBundle() let link = TemporaryLink( // A link id is the server-side recipient id (what `/view/<id>` resolves to) // and shares the random 64-bit namespace of userids. Room-style autoincrement@@ -286,15 +291,15 @@ struct AddLinkDialog: View { // newTemporaryLinkId()); this routes through the explicit-id INSERT OR REPLACE. id: Int64.random(in: 1...Int64.max), name: name.trimmingCharacters(in: .whitespaces),- key: priB64,- publicKey: pubB64,+ key: "",+ publicKey: "", deleteAt: Date().addingTimeInterval(expirySeconds),- pqcPublicKey: pqcPublicB64,- pqcKey: pqcPrivateB64+ pqcPublicKey: ep.publicB64,+ pqcKey: ep.privateB64 ) _ = Database.shared.upsertTemporaryLink(link) } catch {- print("AddLink error: \(error)")+ print("AddLink: PQC ephemeral unavailable (native not linked?): \(error.localizedDescription)") } working = false isPresented = false
FindFamilyiOS/Util/Util.swift
diff --git a/FindFamilyiOS/Util/Util.swift b/FindFamilyiOS/Util/Util.swiftindex a4d7b97cfa..6ea2b4b543 100644--- a/FindFamilyiOS/Util/Util.swift+++ b/FindFamilyiOS/Util/Util.swift@@ -130,6 +130,10 @@ enum Strings { // PQC broken-lock info box (shown when tapping red lock for non-PQC peers) static let pqcUnprotectedTitle = "Quantum protection" static let pqcUnprotectedMessage = "Unprotected against quantum computers: this person needs to update their app."++ // 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." } // MARK: - Time formatting