Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / Networking / Networking.swift

Networking.swift531 lines · 23.4 KiBRaw
1import Foundation
2
3enum NetworkError: Error {
4 case badStatus(Int)
5 case badBody
6}
7
8/// Thin URLSession wrapper for JSON POST endpoints.
9final class NetworkClient {
10 let baseURL = URL(string: "https://api.maproj.org")!
11 private let session: URLSession
12
13 init() {
14 let cfg = URLSessionConfiguration.default
15 cfg.timeoutIntervalForRequest = 60
16 cfg.timeoutIntervalForResource = 120
17 cfg.waitsForConnectivity = true
18 cfg.httpMaximumConnectionsPerHost = 4
19 self.session = URLSession(configuration: cfg)
20 }
21
22 func postJSON(path: String, jsonBody: Data) async throws -> (Data, HTTPURLResponse) {
23 var req = URLRequest(url: baseURL.appendingPathComponent(path))
24 req.httpMethod = "POST"
25 req.setValue("application/json", forHTTPHeaderField: "Content-Type")
26 req.httpBody = jsonBody
27 let (data, resp) = try await session.data(for: req)
28 guard let http = resp as? HTTPURLResponse else { throw NetworkError.badBody }
29 return (data, http)
30 }
31}
32
33// MARK: - Networking singleton
34
35/// Mirrors `Networking.kt` from Modern-Apps. Owns identity (userid, RSA + PQC key pairs),
36/// registration with the server, and the encrypted publish/receive flows.
37///
38/// PQC support mirrors Office's Android `PqcIdentity.loadOrCreate` system:
39/// - Device PQC identity uses `PQCKeyManager` which stores `ff_pqcKemPub/Priv`, `ff_pqcDsaPub/Priv`
40/// (same as Android's `ff_pqc` prefix) in Keychain, with bundle format [4B kemLen][kemPub][dsaPub]
41/// and sealed layout [4B encapLen][encap][aes] (aes = [12B iv][ct||tag]), KDF SHA256(BE32(1)||Z).
42/// - Server parallel endpoints `/api/pqc/*` store PQC bundles separately from RSA.
43///
44/// This app is **post-quantum only**: it publishes to and receives from the `_pqc` queues
45/// exclusively and never touches the classic RSA location/UWB queues, and it registers only a
46/// PQC bundle. Publish, receive and peer key lookup ride the relay socket (`RelaySocket`)
47/// when it is up; the HTTP `_pqc` endpoints here remain the fallback. Android keeps its classic fallback for other peers, but it always prefers PQC
48/// when the peer has a bundle registered — which this app does on every launch.
49@MainActor
50final class Networking: ObservableObject {
51 static let shared = Networking()
52
53 private let client = NetworkClient()
54 private(set) var userid: Int64 = 0
55 // PQC identity — mirrors Office/FF Android ff_pqc prefix. FindFamily is post-quantum only.
56 private var pqcPublicBundleB64: String = ""
57 private var pqcIdentity: PQCIdentity?
58 var pqcAvailable: Bool { pqcIdentity != nil }
59 /// Our public PQC bundle, sent with every relay-socket SUB (which doubles as registration).
60 var pqcPublicBundle: Data? { pqcIdentity?.publicBundle }
61
62 private var networkIsDown = false
63
64 /// Local platform tag included in outgoing heartbeat payloads so peers learn we're on iOS.
65 static let platformTag = "ios"
66
67 @Published private(set) var isReady = false
68
69 private init() {}
70
71 func start() async {
72 // Stable identity: only generate userid on first launch.
73 if let stored = Keychain.getInt64(key: "userid"), stored != 0 {
74 userid = stored
75 } else {
76 userid = Int64.random(in: Int64.min...Int64.max)
77 Keychain.setInt64(userid, key: "userid")
78 }
79
80 // PQC identity — post-quantum only. If the Rust XCFramework isn't linked this throws and
81 // pqcAvailable stays false; the app cannot share until the native lib is present. There is
82 // deliberately no RSA fallback.
83 do {
84 let id = try PQCKeyManager.shared.identity()
85 pqcIdentity = id
86 pqcPublicBundleB64 = id.publicBundle.base64EncodedString()
87 print("Networking: PQC identity ready bundleLen=\(id.publicBundle.count)")
88 } catch {
89 print("Networking: PQC unavailable (native not linked?): \(error.localizedDescription)")
90 pqcIdentity = nil
91 pqcPublicBundleB64 = ""
92 }
93
94 isReady = true
95 ensureMeUserExists()
96 // Apply any auto-toggle timers that fell due while the app was not running
97 // (mirrors Android's cold-start applyDueAutoToggles in the ViewModel init).
98 Database.shared.applyDueAutoToggles(now: Date())
99 _ = await ensureUserExists()
100 }
101
102 /// Ensure there's a "Me" entry in the users table representing the device owner.
103 /// id matches `userid` so the rest of the UI can identify it and so incoming
104 /// LocationValues stored for our own id stitch together correctly.
105 private func ensureMeUserExists() {
106 if Database.shared.user(id: userid) == nil {
107 let me = User(
108 id: userid,
109 name: "Me",
110 photo: nil,
111 locationName: "Unnamed Location",
112 sendingEnabled: false,
113 requestStatus: .mutualConnection,
114 lastLocationChangeTime: Date(),
115 encryptionKey: nil,
116 pqcEncryptionKey: nil
117 )
118 Database.shared.upsertUser(me)
119 }
120 }
121
122 // MARK: - Endpoints
123
124 func registerPqc() async -> Bool {
125 guard !pqcPublicBundleB64.isEmpty else { return false }
126 let body = encodeJSON([
127 "userid": .uint64(UInt64(bitPattern: userid)),
128 "key": .string(pqcPublicBundleB64),
129 ])
130 let ok = await postBool("/api/pqc/register", body: body)
131 print("Networking: registerPqc userid=\(UInt64(bitPattern: userid)) ok=\(ok) bundleLen=\(pqcIdentity?.publicBundle.count ?? -1)")
132 return ok
133 }
134
135 func ensureUserExists() async -> Bool {
136 // PQC-only: register/self-heal the post-quantum bundle. Without PQC there is nothing to
137 // register and the app cannot share until the native lib is present.
138 guard pqcAvailable else { return false }
139 if let serverBundle = await getPqcKeyRaw(forUserid: userid) {
140 if serverBundle.base64EncodedString() != pqcPublicBundleB64 {
141 print("Networking: server PQC bundle mismatch for self, re-registering")
142 return await registerPqc()
143 }
144 return true
145 }
146 return await registerPqc()
147 }
148
149 /// Post-quantum capability of a peer, used to gate connecting/sharing.
150 enum PeerCrypto {
151 case pqc // peer has a PQC bundle — sharing works
152 case needsUpdate // peer has only a classic key — outdated app, must update
153 case unknown // not registered, or the lookup failed (offline)
154 case keyMismatch // the relay's bundle doesn't match the invite link's fingerprint
155 }
156
157 /// Outcome of the connect-time key check. `verifiedBundleB64` is set only when an
158 /// invite fingerprint was supplied and matched, and is meant to go straight onto the
159 /// `User` row being created — pinning the key that was checked, so `resolvedPqcBundle`
160 /// prefers it and a later lookup can't swap in one the fingerprint never covered.
161 struct PeerKeyCheck {
162 let status: PeerCrypto
163 let verifiedBundleB64: String?
164 }
165
166 /// Checks a peer's PQC capability "when connecting", over the relay socket. A PQC
167 /// bundle → `.pqc`; only a classic key → `.needsUpdate` (show the update prompt);
168 /// neither, or the lookup failed → `.unknown`.
169 ///
170 /// `expectedFingerprint` is the `k=` value of the invite link this came from, when
171 /// there was one. The relay's bundle has to hash to it, or the result is
172 /// `.keyMismatch` — this is what stops the relay handing out a key it controls
173 /// instead of the sender's.
174 func peerCryptoStatus(forUserid id: Int64, expectedFingerprint: String? = nil) async -> PeerKeyCheck {
175 guard let res = await RelayKeyLookup.getKey(userId: id) else {
176 return PeerKeyCheck(status: .unknown, verifiedBundleB64: nil)
177 }
178 switch res.status {
179 case .pqc:
180 guard let expected = expectedFingerprint else {
181 return PeerKeyCheck(status: .pqc, verifiedBundleB64: nil)
182 }
183 guard let bundle = res.bundle, !bundle.isEmpty else {
184 return PeerKeyCheck(status: .unknown, verifiedBundleB64: nil)
185 }
186 guard InviteFingerprint.matches(userId: id, publicBundle: bundle, expected: expected) else {
187 print("Networking: invite fingerprint mismatch for \(UInt64(bitPattern: id))")
188 return PeerKeyCheck(status: .keyMismatch, verifiedBundleB64: nil)
189 }
190 return PeerKeyCheck(status: .pqc, verifiedBundleB64: bundle.base64EncodedString())
191 case .classic:
192 return PeerKeyCheck(status: .needsUpdate, verifiedBundleB64: nil)
193 case .noKey:
194 return PeerKeyCheck(status: .unknown, verifiedBundleB64: nil)
195 }
196 }
197
198 /// The invite link to share: the https bounce page, which many messaging apps will
199 /// linkify where a bare `findfamily://` URI is left as plain text. Both values ride in
200 /// the fragment, which browsers never send, so the server sees only that some share
201 /// page was opened. `k` is a 22-character hash of our public bundle, not the bundle
202 /// itself (~4 kB base64) — the recipient fetches the key from the relay and checks it
203 /// against this. Omitted when PQC is unavailable, leaving the id-only link.
204 func inviteLink() -> String {
205 let base = "https://ma.vayunmathur.com/ff/share#id=\(Base26.encode(userid))"
206 guard let bundle = pqcIdentity?.publicBundle else { return base }
207 return base + "&k=" + InviteFingerprint.encode(userId: userid, publicBundle: bundle)
208 }
209
210 /// Computes the quantum-safe verification "security code" (safety number) for a connection:
211 /// a fingerprint of both this device's and [user]'s PQC bundles, identical on both peers.
212 /// Returns nil if PQC is unavailable locally or the peer has no PQC bundle. The heavy
213 /// SHA-256 ×4000 runs off the main actor.
214 func securityCode(for user: User) async -> String? {
215 guard pqcAvailable, let myBundle = pqcIdentity?.publicBundle,
216 let peerBundle = await resolvedPqcBundle(for: user) else { return nil }
217 return await Task.detached(priority: .userInitiated) {
218 PQCSecurityCode.compute(myBundle: myBundle, theirBundle: peerBundle)
219 }.value
220 }
221
222 /// Raw PQC bundle Data fetch (base64 decoded), for registration self-heal check.
223 func getPqcKeyRaw(forUserid id: Int64) async -> Data? {
224 guard pqcAvailable else { return nil }
225 let body = Data(#"{"userid": \#(UInt64(bitPattern: id))}"#.utf8)
226 do {
227 let (data, http) = try await client.postJSON(path: "/api/pqc/getkey", jsonBody: body)
228 networkIsDown = false
229 guard http.statusCode == 200 else { return nil }
230 guard let b64 = String(data: data, encoding: .utf8)?
231 .trimmingCharacters(in: .whitespacesAndNewlines)
232 .trimmingCharacters(in: CharacterSet(charactersIn: "\"")),
233 let bundleData = Data(base64Encoded: b64),
234 !bundleData.isEmpty
235 else { return nil }
236 return bundleData
237 } catch {
238 checkNetworkDown(error)
239 return nil
240 }
241 }
242
243 /// Fetches peer PQC bundle, caches to DB, returns Data.
244 func getPqcBundle(forUserid id: Int64) async -> Data? {
245 guard pqcAvailable else { return nil }
246 // GETKEY on the live relay socket when it is up (no extra connection); otherwise
247 // the HTTP lookup as before.
248 var fetched: Data? = nil
249 if let live = await RelaySocket.shared.getKey(userId: id), live.status == .pqc,
250 let bundle = live.bundle, !bundle.isEmpty {
251 fetched = bundle
252 }
253 if fetched == nil { fetched = await getPqcKeyRaw(forUserid: id) }
254 if let data = fetched {
255 // Overwrite rather than fill-only-if-empty, matching Android: this is only
256 // reached when there was no cached bundle to prefer, and a stale value here
257 // would keep us encrypting to a key the peer has already replaced. Written on
258 // its own so the other columns (sharingAutoToggleAt etc.) aren't clobbered.
259 if Database.shared.user(id: id) != nil {
260 Database.shared.setPqcEncryptionKey(id: id, pqcEncryptionKey: data.base64EncodedString())
261 }
262 return data
263 }
264 return nil
265 }
266
267 // MARK: - Publish Location (post-quantum only)
268
269 func publishLocation(_ location: LocationValue, toUser user: User) async -> Bool {
270 guard let bundle = await resolvedPqcBundle(for: user) else {
271 print("Networking: publishLocation no PQC bundle for \(UInt64(bitPattern: user.id)); peer must update")
272 return false
273 }
274 return await publishEncryptedPqc(location: location, recipientID: user.id, bundle: bundle) ?? false
275 }
276
277 private func resolvedPqcBundle(for user: User) async -> Data? {
278 guard pqcAvailable else { return nil }
279 if let b64 = user.pqcEncryptionKey, let data = Data(base64Encoded: b64), !data.isEmpty {
280 return data
281 }
282 // Opportunistic fetch from server.
283 if let data = await getPqcBundle(forUserid: user.id) {
284 return data
285 }
286 return nil
287 }
288
289 func publishLocation(_ location: LocationValue, toLink link: TemporaryLink) async -> Bool {
290 guard pqcAvailable, let b64 = link.pqcPublicKey, let bundle = Data(base64Encoded: b64), !bundle.isEmpty else {
291 return false
292 }
293 return await publishEncryptedPqc(location: location, recipientID: link.id, bundle: bundle) ?? false
294 }
295
296 private func publishEncryptedPqc(location: LocationValue, recipientID: Int64, bundle: Data) async -> Bool? {
297 guard pqcAvailable else { return nil }
298 do {
299 let json = try JSONEncoder().encode(location.toCompatible(senderPlatform: Self.platformTag))
300 // Encrypt via PQC (ML-KEM encaps + AES-GCM), same as Kotlin Pqc.encryptTo
301 let sealed = try PQCKeyManager.shared.encryptTo(bundle: bundle, plaintext: json)
302 // Relay socket first (PUB); HTTP when the socket is down or not fresh.
303 if await RelaySocket.shared.publish(recipient: recipientID, isUwb: false, sealed: sealed) {
304 print("publishEncryptedPqc to \(UInt64(bitPattern: recipientID)) via ws encLen=\(sealed.count)")
305 return true
306 }
307 let body = encodeJSON([
308 "recipientUserID": .uint64(UInt64(bitPattern: recipientID)),
309 "encryptedLocation": .string(sealed.base64EncodedString()),
310 ])
311 let ok = await postBool("/api/location/publish_pqc", body: body)
312 print("publishEncryptedPqc to \(UInt64(bitPattern: recipientID)) ok=\(ok) encLen=\(sealed.count)")
313 return ok
314 } catch {
315 print("publishEncryptedPqc error: \(error.localizedDescription)")
316 return nil
317 }
318 }
319
320 // MARK: - Receive (post-quantum only)
321
322 /// Drains the post-quantum queue. The classic RSA queue is deliberately not read:
323 /// this app publishes and receives post-quantum only, so anything sitting in the
324 /// classic queue was sent by a peer that hasn't picked up our PQC key yet.
325 func receiveLocations() async -> [LocationValue]? {
326 return await receiveLocationsPqc()
327 }
328
329 private func receiveLocationsPqc() async -> [LocationValue]? {
330 guard pqcAvailable, (try? PQCKeyManager.shared.identity()) != nil else { return [] }
331 let body = Data(#"{"userid": \#(UInt64(bitPattern: userid))}"#.utf8)
332 do {
333 let (data, http) = try await client.postJSON(path: "/api/location/receive_pqc", jsonBody: body)
334 networkIsDown = false
335 if http.statusCode == 204 || data.isEmpty { return [] }
336 guard http.statusCode == 200 else {
337 print("receiveLocationsPqc: HTTP \(http.statusCode)")
338 return nil
339 }
340 let arr = try JSONDecoder().decode([String].self, from: data)
341 var out: [LocationValue] = []
342 for b64 in arr {
343 guard let sealed = Data(base64Encoded: b64) else {
344 print("receiveLocationsPqc: skipped non-base64")
345 continue
346 }
347 // Already taken from the relay socket (a requeued un-ACKed frame).
348 if RelayDedup.shared.contains(sealed) { continue }
349 RelayDedup.shared.insert(sealed)
350 if let loc = decodeLocation(sealed: sealed) { out.append(loc) }
351 }
352 print("receiveLocationsPqc: \(out.count) location(s) for userid=\(UInt64(bitPattern: userid))")
353 return out
354 } catch {
355 checkNetworkDown(error)
356 return nil
357 }
358 }
359
360 /// Decrypts one sealed location (HTTP drain or relay-socket push) and records the
361 /// sender's platform tag. Nil on decrypt/parse failure.
362 func decodeLocation(sealed: Data) -> LocationValue? {
363 do {
364 let plain = try PQCKeyManager.shared.decrypt(sealed: sealed)
365 let comp = try JSONDecoder().decode(LocationValueCompatible.self, from: plain)
366 let loc = comp.toLocationValue()
367 if let platform = comp.senderPlatform,
368 let u = Database.shared.user(id: loc.userid),
369 u.platform != platform {
370 Database.shared.setPlatform(id: loc.userid, platform: platform)
371 }
372 return loc
373 } catch {
374 print("decodeLocation: decrypt/parse failure: \(error.localizedDescription)")
375 return nil
376 }
377 }
378
379 /// Decrypts one sealed UWB envelope (HTTP drain or relay-socket push).
380 func decodeUwb(sealed: Data) -> UwbEnvelope? {
381 guard let plain = try? PQCKeyManager.shared.decrypt(sealed: sealed) else { return nil }
382 return try? JSONDecoder().decode(UwbEnvelope.self, from: plain)
383 }
384
385 // MARK: - UWB session-setup channel (post-quantum only)
386
387 /// Publishes [envelope] to [recipientID] via the peer's PQC bundle. Returns false if the peer
388 /// has no PQC bundle (they are on an outdated app).
389 func publishUwbMessage(_ envelope: UwbEnvelope, to recipientID: Int64) async -> Bool {
390 guard pqcAvailable else { return false }
391 var pqcBundle: Data? = nil
392 if let user = Database.shared.user(id: recipientID),
393 let b64 = user.pqcEncryptionKey,
394 let data = Data(base64Encoded: b64), !data.isEmpty {
395 pqcBundle = data
396 } else if let data = await getPqcBundle(forUserid: recipientID) {
397 pqcBundle = data
398 }
399 guard let bundle = pqcBundle else {
400 print("publishUwbMessage: no PQC bundle for \(UInt64(bitPattern: recipientID)); peer must update")
401 return false
402 }
403 return await publishUwbMessagePqc(envelope, to: recipientID, bundle: bundle) ?? false
404 }
405
406 private func publishUwbMessagePqc(_ envelope: UwbEnvelope, to recipientID: Int64, bundle: Data) async -> Bool? {
407 guard pqcAvailable else { return nil }
408 do {
409 let json = try JSONEncoder().encode(envelope)
410 let sealed = try PQCKeyManager.shared.encryptTo(bundle: bundle, plaintext: json)
411 if await RelaySocket.shared.publish(recipient: recipientID, isUwb: true, sealed: sealed) {
412 print("publishUwbMessagePqc to \(UInt64(bitPattern: recipientID)) via ws")
413 return true
414 }
415 let body = encodeJSON([
416 "recipientUserID": .uint64(UInt64(bitPattern: recipientID)),
417 "encryptedLocation": .string(sealed.base64EncodedString()),
418 ])
419 let ok = await postBool("/api/uwb/publish_pqc", body: body)
420 print("publishUwbMessagePqc to \(UInt64(bitPattern: recipientID)) ok=\(ok)")
421 return ok
422 } catch {
423 print("publishUwbMessagePqc encrypt error: \(error)")
424 return nil
425 }
426 }
427
428 /// Drains incoming UWB envelopes from the PQC queue (post-quantum only).
429 func receiveUwbMessages() async -> [UwbEnvelope]? {
430 return await receiveUwbMessagesPqc()
431 }
432
433 private func receiveUwbMessagesPqc() async -> [UwbEnvelope]? {
434 guard pqcAvailable, (try? PQCKeyManager.shared.identity()) != nil else { return [] }
435 let body = Data(#"{"userid": \#(UInt64(bitPattern: userid))}"#.utf8)
436 do {
437 let (data, http) = try await client.postJSON(path: "/api/uwb/receive_pqc", jsonBody: body)
438 networkIsDown = false
439 if http.statusCode == 204 || data.isEmpty { return [] }
440 guard http.statusCode == 200 else { return nil }
441 let arr = try JSONDecoder().decode([String].self, from: data)
442 var out: [UwbEnvelope] = []
443 for b64 in arr {
444 guard let sealed = Data(base64Encoded: b64) else { continue }
445 if RelayDedup.shared.contains(sealed) { continue }
446 RelayDedup.shared.insert(sealed)
447 if let env = decodeUwb(sealed: sealed) { out.append(env) }
448 }
449 return out
450 } catch {
451 checkNetworkDown(error)
452 return nil
453 }
454 }
455
456 // MARK: - Helpers
457
458 private func postBool(_ path: String, body: Data) async -> Bool {
459 do {
460 let (_, http) = try await client.postJSON(path: path, jsonBody: body)
461 networkIsDown = false
462 // Server returns 200 *or* 204 No Content on success for register/publish.
463 return (200..<300).contains(http.statusCode)
464 } catch {
465 checkNetworkDown(error)
466 return false
467 }
468 }
469
470 private func checkNetworkDown(_ error: Error) {
471 if !networkIsDown {
472 print("network error: \(error.localizedDescription)")
473 }
474 networkIsDown = true
475 }
476}
477
478// MARK: - Minimal JSON encoder that preserves UInt64 unquoted
479
480/// We need numeric values for `userid` etc. to remain unquoted JSON numbers, even when they
481/// exceed `Int64.max` (since the Android side encodes them as `ULong`). JSONEncoder handles
482/// `UInt64` as a number for values that fit, so this is a simple wrapper that keeps the
483/// per-key types explicit.
484private enum JSONValue {
485 case string(String)
486 case uint64(UInt64)
487 case int64(Int64)
488 case double(Double)
489 case bool(Bool)
490}
491
492private func encodeJSON(_ dict: [String: JSONValue]) -> Data {
493 var parts: [String] = []
494 // Preserve insertion order by iterating over keys array — Swift dictionary literals
495 // don't preserve order, but the server is fine with any ordering.
496 for (k, v) in dict {
497 parts.append("\(quote(k)):\(serialize(v))")
498 }
499 return Data("{\(parts.joined(separator: ","))}".utf8)
500}
501
502private func serialize(_ value: JSONValue) -> String {
503 switch value {
504 case .string(let s): return quote(s)
505 case .uint64(let n): return String(n)
506 case .int64(let n): return String(n)
507 case .double(let d): return String(d)
508 case .bool(let b): return b ? "true" : "false"
509 }
510}
511
512private func quote(_ s: String) -> String {
513 var out = "\""
514 for ch in s.unicodeScalars {
515 switch ch {
516 case "\"": out += "\\\""
517 case "\\": out += "\\\\"
518 case "\n": out += "\\n"
519 case "\r": out += "\\r"
520 case "\t": out += "\\t"
521 default:
522 if ch.value < 0x20 {
523 out += String(format: "\\u%04x", ch.value)
524 } else {
525 out.unicodeScalars.append(ch)
526 }
527 }
528 }
529 out += "\""
530 return out
531}