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