findfamily: align iOS with Android (auto-toggle sharing, security code, waypoint hysteresis, sharing filter, atomic DB writes, self-heal, random link ids)
- Commit
39f7b75318a12a97886f0019e077534184e8f8f1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-10 18:42 UTC (3 months ago)
- Parents
1c6935c
Diff
FindFamilyiOS/Crypto/Crypto.swift
diff --git a/FindFamilyiOS/Crypto/Crypto.swift b/FindFamilyiOS/Crypto/Crypto.swiftindex ae81ee2109..5f044112db 100644--- a/FindFamilyiOS/Crypto/Crypto.swift+++ b/FindFamilyiOS/Crypto/Crypto.swift@@ -354,6 +354,56 @@ private struct ASN1Parser { } } +// MARK: - Security code formatting (shared by PQC + RSA 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`.+enum SecurityCodeFormat {+ static let iterations = 4000++ /// SHA-256(a) and SHA-256(b) are combined in canonical (sorted) order, then hashed+ /// `iterations` times, then formatted. Both peers compute the same code regardless of role.+ static func compute(_ aDigestInput: Data, _ bDigestInput: Data) -> String {+ let a = sha256(aDigestInput)+ let b = sha256(bDigestInput)+ var h = a.lexicographicallyPrecedes(b) ? a + b : b + a+ for _ in 0..<iterations { h = sha256(h) }+ return format(h)+ }++ static func sha256(_ d: Data) -> Data { Data(SHA256.hash(data: d)) }++ /// 6 groups of 5 bytes → big-endian UInt64 → `% 100000`, zero-padded, space-separated.+ 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[h.startIndex + idx + j]) }+ if group > 0 { sb.append(" ") }+ sb.append(String(format: "%05d", v % 100000))+ idx += 5+ }+ return sb+ }+}++// 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/Crypto/PQCCrypto.swift
diff --git a/FindFamilyiOS/Crypto/PQCCrypto.swift b/FindFamilyiOS/Crypto/PQCCrypto.swiftindex 8d206b4436..a14f50408d 100644--- a/FindFamilyiOS/Crypto/PQCCrypto.swift+++ b/FindFamilyiOS/Crypto/PQCCrypto.swift@@ -126,37 +126,9 @@ enum PQCAES { // 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+ SecurityCodeFormat.compute(myBundle, theirBundle) } }
FindFamilyiOS/Location/Location.swift
diff --git a/FindFamilyiOS/Location/Location.swift b/FindFamilyiOS/Location/Location.swiftindex 69b8c33410..f50689d600 100644--- a/FindFamilyiOS/Location/Location.swift+++ b/FindFamilyiOS/Location/Location.swift@@ -86,7 +86,6 @@ final class BackgroundTask { private var lastUpdateAt: Date = .distantPast private var tickCount = 0 private var lastBatteryLevels: [Int64: Float] = [:]- private var lastUserLocationName: [Int64: String] = [:] private var isProcessing = false /// Last location delivered by CoreLocation. Cached so the timer-driven@@ -150,28 +149,20 @@ final class BackgroundTask { tickCount += 1 if tickCount % 100 == 1 { _ = await Networking.shared.ensureUserExists() } - // 1. Reverse geocode -> "Home" / "Unnamed Location" placeholder.- var myPlaceName = "Unnamed Location"- if let placemarks = try? await geocoder.reverseGeocodeLocation(loc),- let p = placemarks.first {- myPlaceName = [p.name, p.locality].compactMap { $0 }.first ?? "Unnamed Location"- }-- // 2. Waypoint enter/exit using haversine.- let waypoints = Database.shared.waypointsSubject.value- for wp in waypoints {- let dist = haversine(coord, wp.coord)- if dist < wp.range { myPlaceName = wp.name; break }- }-- // Update the local "Me" user's locationName + persist our own LocationValue so- // we appear on the map and our own history works.+ // 1 + 2. Persist our own fix, then compute our current waypoint (with 1.2× exit+ // hysteresis) and a display name. Uses the atomic partial update so timers/flags+ // set elsewhere (sharingAutoToggleAt / sendingEnabled) aren't clobbered. Database.shared.insertLocationValue(me)- if var meUser = Database.shared.user(id: Networking.shared.userid) {- if meUser.locationName != myPlaceName {- meUser.locationName = myPlaceName- meUser.lastLocationChangeTime = Date()- Database.shared.upsertUser(meUser)+ if let meUser = Database.shared.user(id: Networking.shared.userid) {+ let (currentId, resolvedName) = await resolveWaypoint(coord: coord, prevId: meUser.lastWaypointId)+ let displayName = resolvedName ?? (meUser.locationName.isEmpty ? "Unnamed Location" : meUser.locationName)+ if currentId != meUser.lastWaypointId || displayName != meUser.locationName {+ Database.shared.updateLocationMeta(+ id: meUser.id,+ locationName: displayName,+ lastWaypointId: currentId,+ lastLocationChangeTime: Date()+ ) } } @@ -181,11 +172,13 @@ final class BackgroundTask { Database.shared.deleteTemporaryLink(link) } - // 4. Publish my location to EVERY user in our database (matches Modern-Apps- // behavior — there's no `sendingEnabled` / `mutualConnection` filter at this- // layer; discovery happens implicitly via location publishing).+ // 4. Apply any due auto-toggle timers, then publish. Mirrors Android: flip+ // `sendingEnabled` atomically for due timers, then publish only to peers with+ // sharing enabled (`id != me && sendingEnabled`) so the "Share your location"+ // toggle — and the auto-toggle countdown — are actually honored.+ Database.shared.applyDueAutoToggles(now: now) let users = Database.shared.usersSubject.value- for u in users where u.id != Networking.shared.userid {+ for u in users where u.id != Networking.shared.userid && u.sendingEnabled { _ = await Networking.shared.publishLocation(me, toUser: u) } for link in Database.shared.temporaryLinksSubject.value {@@ -242,37 +235,65 @@ final class BackgroundTask { } } - private func updateUserLocationName(_ loc: LocationValue) async {- guard var user = Database.shared.user(id: loc.userid) else { return }- // Recompute the display name on every incoming fix: prefer a matching waypoint,- // otherwise reverse-geocode the fresh coordinate. This mirrors the local "Me"- // handling above and Android's heartbeat. Previously the geocode only ran while- // the stored name was still "Unnamed Location", so once a peer had any real name- // it never refreshed and the main-page list showed a location stuck for weeks.- var newName: String?- for wp in Database.shared.waypointsSubject.value {- if haversine(loc.coord, wp.coord) < wp.range { newName = wp.name; break }+ /// Computes the current waypoint id for a coordinate with 1.2× exit hysteresis and a+ /// display name, mirroring Android `syncHeartbeat`. To *enter* a waypoint you must be+ /// within its radius; to *remain* in the previously-entered waypoint you only need to be+ /// within 1.2× the radius (prevents flapping at the boundary). The returned name prefers+ /// the entered/sticky waypoint name, then a reverse-geocoded address, else nil (unresolved).+ private func resolveWaypoint(coord: Coord, prevId: Int64?) async -> (currentId: Int64?, name: String?) {+ let waypoints = Database.shared.waypointsSubject.value+ let inWaypoint = waypoints.first { haversine(coord, $0.coord) < $0.range }+ let stillInsidePrev: Bool = {+ guard let pid = prevId, let wp = waypoints.first(where: { $0.id == pid }) else { return false }+ return haversine(coord, wp.coord) < wp.range * 1.2+ }()+ let currentId: Int64? = inWaypoint?.id ?? (stillInsidePrev ? prevId : nil)+ if let name = inWaypoint?.name { return (currentId, name) }+ if let cid = currentId, let wp = waypoints.first(where: { $0.id == cid }) {+ return (currentId, wp.name) }- if newName == nil,- let placemarks = try? await geocoder.reverseGeocodeLocation(- CLLocation(latitude: loc.coord.lat, longitude: loc.coord.lon)- ), let p = placemarks.first {- newName = [p.name, p.locality].compactMap { $0 }.first+ if let placemarks = try? await geocoder.reverseGeocodeLocation(+ CLLocation(latitude: coord.lat, longitude: coord.lon)+ ), let p = placemarks.first {+ return (currentId, [p.name, p.locality].compactMap { $0 }.first) }- // If we couldn't resolve a fresh name, keep the existing one rather than clobbering it.- let resolved = newName ?? user.locationName- if resolved != user.locationName {- user.locationName = resolved- user.lastLocationChangeTime = Date()- Database.shared.upsertUser(user)- if let prev = lastUserLocationName[user.id], prev != resolved {- NotificationsUtil.send(- title: Strings.notifWaypointEnterTitle,- body: Strings.notifWaypointEnterBody(user.name, resolved),- category: "WAYPOINT_ENTER_EXIT"- )- }- lastUserLocationName[user.id] = resolved+ return (currentId, nil)+ }++ private func updateUserLocationName(_ loc: LocationValue) async {+ guard let user = Database.shared.user(id: loc.userid) else { return }+ // Recompute waypoint (with hysteresis) + display name on every incoming fix. Prefer a+ // matching waypoint, otherwise reverse-geocode. Keep the existing name if we can't+ // resolve a fresh one rather than clobbering it.+ let prevId = user.lastWaypointId+ let (currentId, resolvedName) = await resolveWaypoint(coord: loc.coord, prevId: prevId)+ let resolved = resolvedName ?? user.locationName+ if currentId != prevId || resolved != user.locationName {+ // Atomic partial update — avoids a stale snapshot clobbering+ // sharingAutoToggleAt / sendingEnabled.+ Database.shared.updateLocationMeta(+ id: user.id,+ locationName: resolved,+ lastWaypointId: currentId,+ lastLocationChangeTime: Date()+ )+ }+ // Enter/exit notifications fire only on an actual waypoint transition.+ guard currentId != prevId else { return }+ if currentId != nil {+ let enteredName = Database.shared.waypointsSubject.value.first { $0.id == currentId }?.name ?? resolved+ NotificationsUtil.send(+ title: Strings.notifWaypointEnterTitle,+ body: Strings.notifWaypointEnterBody(user.name, enteredName),+ category: "WAYPOINT_ENTER_EXIT"+ )+ } else if let pid = prevId {+ let exitedName = Database.shared.waypointsSubject.value.first { $0.id == pid }?.name ?? user.locationName+ NotificationsUtil.send(+ title: Strings.notifWaypointExitTitle,+ body: Strings.notifWaypointExitBody(user.name, exitedName),+ category: "WAYPOINT_ENTER_EXIT"+ ) } } @@ -280,7 +301,8 @@ final class BackgroundTask { let prev = lastBatteryLevels[loc.userid] lastBatteryLevels[loc.userid] = loc.battery guard let prev = prev else { return }- if prev > 20 && loc.battery <= 20 {+ // Edge-triggered at 15% (matches Android): one alert as a peer crosses the threshold.+ if prev > 15 && loc.battery <= 15 { if let user = Database.shared.user(id: loc.userid) { NotificationsUtil.send( title: Strings.notifBatteryLowTitle,
FindFamilyiOS/Model/Models.swift
diff --git a/FindFamilyiOS/Model/Models.swift b/FindFamilyiOS/Model/Models.swiftindex 21b7dd3fa1..238e7386c4 100644--- a/FindFamilyiOS/Model/Models.swift+++ b/FindFamilyiOS/Model/Models.swift@@ -61,11 +61,18 @@ struct User: Identifiable, Codable, Hashable, Equatable { /// 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+ /// Id of the waypoint this user is currently inside, used for enter/exit hysteresis.+ /// Nullable for migration and when the user is outside every waypoint.+ var lastWaypointId: Int64? = nil+ /// Deadline at which `sendingEnabled` auto-flips (the "Disable/Enable after" timer).+ /// `nil` means "Never" (no pending auto-toggle). Nullable for migration.+ var sharingAutoToggleAt: Date? = nil static let empty = User( id: 0, name: "", photo: nil, locationName: "Unnamed Location", sendingEnabled: false, requestStatus: .mutualConnection,- lastLocationChangeTime: Date(), encryptionKey: nil, platform: nil, pqcEncryptionKey: nil+ lastLocationChangeTime: Date(), encryptionKey: nil, platform: nil, pqcEncryptionKey: nil,+ lastWaypointId: nil, sharingAutoToggleAt: nil ) }
FindFamilyiOS/Networking/Networking.swift
diff --git a/FindFamilyiOS/Networking/Networking.swift b/FindFamilyiOS/Networking/Networking.swiftindex b46050965a..9b9008bdae 100644--- a/FindFamilyiOS/Networking/Networking.swift+++ b/FindFamilyiOS/Networking/Networking.swift@@ -97,6 +97,9 @@ final class Networking: ObservableObject { 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() } catch { print("Networking.start error: \(error)")@@ -147,12 +150,29 @@ final class Networking: ObservableObject { func ensureUserExists() async -> Bool { var ok = true- if await getKey(forUserid: userid) == nil {+ // 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: ensure PQC key registered too if available.+ // PQC self-healing: same missing-or-mismatched detection for the PQC bundle. if pqcAvailable {- if await getPqcKeyRaw(forUserid: userid) == nil {+ 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 } }@@ -181,7 +201,35 @@ final class Networking: ObservableObject { } } - // MARK: - PQC key fetch (raw bundle)+ /// 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. Uses RSA keys to match Android's current SecurityCodeDialog.+ func securityCode(for user: User) async -> String? {+ 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+ }+ guard let peer = peerKey else { return nil }+ // Extract canonical DER on the main actor (cheap), then run the SHA-256 ×4000+ // iteration off the main actor — `Networking` is @MainActor, so a plain call would+ // otherwise block the UI. Only `Data` (Sendable) crosses the boundary.+ guard let myDer = RSASecurityCode.canonicalDER(selfPub),+ let theirDer = RSASecurityCode.canonicalDER(peer) else { return nil }+ return await Task.detached(priority: .userInitiated) {+ SecurityCodeFormat.compute(myDer, theirDer)+ }.value+ } /// Raw PQC bundle Data fetch (base64 decoded), for registration self-heal check. func getPqcKeyRaw(forUserid id: Int64) async -> Data? {@@ -208,12 +256,9 @@ final class Networking: ObservableObject { 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.+ // Cache atomically so we don't clobber other columns (sharingAutoToggleAt etc.).+ if let u = Database.shared.user(id: id), u.pqcEncryptionKey == nil {+ Database.shared.setPqcEncryptionKey(id: id, pqcEncryptionKey: data.base64EncodedString()) } return data }@@ -254,13 +299,10 @@ final class Networking: ObservableObject { let k = RSAPEM.publicKeyFromPEM(pem) { key = k } else if let k = await getKey(forUserid: user.id) {- do {- let pem = try RSAPEM.publicKeyToPEM(k)+ if let pem = try? RSAPEM.publicKeyToPEM(k) { let b64 = Data(pem.utf8).base64EncodedString()- var copy = user- copy.encryptionKey = b64- Database.shared.upsertUser(copy)- } catch {}+ Database.shared.setEncryptionKey(id: user.id, encryptionKey: b64)+ } key = k } else { key = nil@@ -358,10 +400,9 @@ final class Networking: ObservableObject { let loc = comp.toLocationValue() out.append(loc) if let platform = comp.senderPlatform,- var u = Database.shared.user(id: loc.userid),+ let u = Database.shared.user(id: loc.userid), u.platform != platform {- u.platform = platform- Database.shared.upsertUser(u)+ Database.shared.setPlatform(id: loc.userid, platform: platform) } } catch { print("receiveLocationsClassic: decrypt/parse failure: \(error.localizedDescription)")@@ -399,10 +440,9 @@ final class Networking: ObservableObject { let loc = comp.toLocationValue() out.append(loc) if let platform = comp.senderPlatform,- var u = Database.shared.user(id: loc.userid),+ let u = Database.shared.user(id: loc.userid), u.platform != platform {- u.platform = platform- Database.shared.upsertUser(u)+ Database.shared.setPlatform(id: loc.userid, platform: platform) } } catch { print("receiveLocationsPqc: decrypt/parse failure: \(error.localizedDescription)")
FindFamilyiOS/Persistence/Database.swift
diff --git a/FindFamilyiOS/Persistence/Database.swift b/FindFamilyiOS/Persistence/Database.swiftindex df2f98a109..db396f7fb8 100644--- a/FindFamilyiOS/Persistence/Database.swift+++ b/FindFamilyiOS/Persistence/Database.swift@@ -63,6 +63,14 @@ final class Database { // PQC bundle cache (base64 of [4B kemLen][kemPubDer][dsaPubDer]) — same format as Office. exec("ALTER TABLE users ADD COLUMN pqcEncryptionKey TEXT;") }+ if !columnExists(table: "users", column: "lastWaypointId") {+ // Waypoint enter/exit hysteresis state (nullable). Additive migration only.+ exec("ALTER TABLE users ADD COLUMN lastWaypointId INTEGER;")+ }+ if !columnExists(table: "users", column: "sharingAutoToggleAt") {+ // Auto-toggle deadline in epoch seconds (nullable = "Never"). Additive migration only.+ exec("ALTER TABLE users ADD COLUMN sharingAutoToggleAt INTEGER;")+ } exec(""" CREATE TABLE IF NOT EXISTS waypoints ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,@@ -140,8 +148,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, pqcEncryptionKey)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);+ INSERT OR REPLACE INTO users (id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform, pqcEncryptionKey, lastWaypointId, sharingAutoToggleAt)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); """ var stmt: OpaquePointer? sqlite3_prepare_v2(db, sql, -1, &stmt, nil)@@ -155,12 +163,127 @@ final class Database { bindOptionalText(stmt, 8, u.encryptionKey) bindOptionalText(stmt, 9, u.platform) bindOptionalText(stmt, 10, u.pqcEncryptionKey)+ bindOptionalInt64(stmt, 11, u.lastWaypointId)+ bindOptionalInt64(stmt, 12, u.sharingAutoToggleAt.map { Int64($0.timeIntervalSince1970) }) sqlite3_step(stmt) sqlite3_finalize(stmt) usersSubject.send(loadUsers()) } } + // MARK: - Atomic partial updates+ //+ // These mirror Android's UserDao partial-update queries. Whole-row `upsertUser`+ // from a stale snapshot would clobber columns another path just wrote+ // (e.g. `sharingAutoToggleAt` / `sendingEnabled`), so hot paths use these instead.++ /// Atomically update location display metadata without touching sharing/toggle columns.+ func updateLocationMeta(id: Int64, locationName: String, lastWaypointId: Int64?, lastLocationChangeTime: Date) {+ queue.sync {+ let sql = "UPDATE users SET locationName = ?, lastWaypointId = ?, lastLocationChangeTime = ? WHERE id = ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ bindText(stmt, 1, locationName)+ bindOptionalInt64(stmt, 2, lastWaypointId)+ sqlite3_bind_int64(stmt, 3, Int64(lastLocationChangeTime.timeIntervalSince1970))+ sqlite3_bind_int64(stmt, 4, id)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ usersSubject.send(loadUsers())+ }+ }++ /// Atomically set the learned peer platform tag.+ func setPlatform(id: Int64, platform: String) {+ queue.sync {+ let sql = "UPDATE users SET platform = ? WHERE id = ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ bindText(stmt, 1, platform)+ sqlite3_bind_int64(stmt, 2, id)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ usersSubject.send(loadUsers())+ }+ }++ /// Atomically cache a peer's RSA public key (base64 PEM).+ func setEncryptionKey(id: Int64, encryptionKey: String) {+ queue.sync {+ let sql = "UPDATE users SET encryptionKey = ? WHERE id = ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ bindText(stmt, 1, encryptionKey)+ sqlite3_bind_int64(stmt, 2, id)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ usersSubject.send(loadUsers())+ }+ }++ /// Atomically cache a peer's PQC public bundle (base64).+ func setPqcEncryptionKey(id: Int64, pqcEncryptionKey: String) {+ queue.sync {+ let sql = "UPDATE users SET pqcEncryptionKey = ? WHERE id = ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ bindText(stmt, 1, pqcEncryptionKey)+ sqlite3_bind_int64(stmt, 2, id)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ usersSubject.send(loadUsers())+ }+ }++ /// Atomically set only the auto-toggle deadline (nil = "Never"). Avoids clobbering other columns.+ func setSharingAutoToggleAt(id: Int64, at: Date?) {+ queue.sync {+ let sql = "UPDATE users SET sharingAutoToggleAt = ? WHERE id = ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ bindOptionalInt64(stmt, 1, at.map { Int64($0.timeIntervalSince1970) })+ sqlite3_bind_int64(stmt, 2, id)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ usersSubject.send(loadUsers())+ }+ }++ /// Atomically set sharing enabled AND clear any pending auto-toggle (manual toggle path).+ func setSendingEnabledAndClearToggle(id: Int64, enabled: Bool) {+ queue.sync {+ let sql = "UPDATE users SET sendingEnabled = ?, sharingAutoToggleAt = NULL WHERE id = ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ sqlite3_bind_int(stmt, 1, enabled ? 1 : 0)+ sqlite3_bind_int64(stmt, 2, id)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ usersSubject.send(loadUsers())+ }+ }++ /// Atomically flip sharing for every row whose timer is due, clearing the timer.+ /// The WHERE clause guards against TOCTOU races: if the user manually cleared (NULL)+ /// or rescheduled to the future, the row no longer matches. Returns rows flipped.+ @discardableResult+ func applyDueAutoToggles(now: Date) -> Int {+ queue.sync {+ let nowEpoch = Int64(now.timeIntervalSince1970)+ let sql = "UPDATE users SET sendingEnabled = CASE WHEN sendingEnabled THEN 0 ELSE 1 END, sharingAutoToggleAt = NULL WHERE sharingAutoToggleAt IS NOT NULL AND sharingAutoToggleAt <= ?;"+ var stmt: OpaquePointer?+ sqlite3_prepare_v2(db, sql, -1, &stmt, nil)+ sqlite3_bind_int64(stmt, 1, nowEpoch)+ sqlite3_step(stmt)+ sqlite3_finalize(stmt)+ let changed = Int(sqlite3_changes(db))+ if changed > 0 {+ usersSubject.send(loadUsers())+ }+ return changed+ }+ }+ func deleteUser(_ u: User) { queue.sync { exec("DELETE FROM users WHERE id = \(u.id);")@@ -172,12 +295,13 @@ final class Database { private func loadUsers() -> [User] { var out: [User] = []- // 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;"+ // pqcEncryptionKey/lastWaypointId/sharingAutoToggleAt columns added via idempotent+ // migrations; SELECT explicitly to handle older dbs (see rc-fallback below).+ let sql = "SELECT id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform, pqcEncryptionKey, lastWaypointId, sharingAutoToggleAt FROM users;" var stmt: OpaquePointer? 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).+ // Fallback: older schema without the newer columns (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)@@ -192,7 +316,9 @@ final class Database { lastLocationChangeTime: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))), encryptionKey: text(stmt, 7), platform: text(stmt, 8),- pqcEncryptionKey: nil+ pqcEncryptionKey: nil,+ lastWaypointId: nil,+ sharingAutoToggleAt: nil )) } sqlite3_finalize(stmt)@@ -209,7 +335,9 @@ final class Database { lastLocationChangeTime: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))), encryptionKey: text(stmt, 7), platform: text(stmt, 8),- pqcEncryptionKey: text(stmt, 9)+ pqcEncryptionKey: text(stmt, 9),+ lastWaypointId: optInt64(stmt, 10),+ sharingAutoToggleAt: optInt64(stmt, 11).map { Date(timeIntervalSince1970: TimeInterval($0)) } )) } sqlite3_finalize(stmt)@@ -442,6 +570,12 @@ final class Database { return String(cString: cstr) } + /// Reads a nullable INTEGER column, returning nil for SQL NULL.+ private func optInt64(_ stmt: OpaquePointer?, _ idx: Int32) -> Int64? {+ if sqlite3_column_type(stmt, idx) == SQLITE_NULL { return nil }+ return sqlite3_column_int64(stmt, idx)+ }+ private func bindText(_ stmt: OpaquePointer?, _ idx: Int32, _ s: String) { sqlite3_bind_text(stmt, idx, (s as NSString).utf8String, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self)) }@@ -453,4 +587,12 @@ final class Database { sqlite3_bind_null(stmt, idx) } }++ private func bindOptionalInt64(_ stmt: OpaquePointer?, _ idx: Int32, _ v: Int64?) {+ if let v = v {+ sqlite3_bind_int64(stmt, idx, v)+ } else {+ sqlite3_bind_null(stmt, idx)+ }+ } }
FindFamilyiOS/UI/BottomPanels.swift
diff --git a/FindFamilyiOS/UI/BottomPanels.swift b/FindFamilyiOS/UI/BottomPanels.swiftindex 90d9d4887b..537c9636a0 100644--- a/FindFamilyiOS/UI/BottomPanels.swift+++ b/FindFamilyiOS/UI/BottomPanels.swift@@ -59,6 +59,7 @@ struct UserDetailPanel: View { let latest: LocationValue? let onChangeContact: (String, String?) -> Void let onToggleSending: (Bool) -> Void+ let onSetAutoToggle: (TimeInterval?) -> Void @State private var showPqcInfo = false @@ -78,11 +79,14 @@ struct UserDetailPanel: View { } .buttonStyle(.plain) }- HStack {- Text(Strings.shareYourLocation)- Spacer()- Toggle("", isOn: Binding(get: { user.sendingEnabled }, set: { onToggleSending($0) }))- .labelsHidden()+ VStack(spacing: 8) {+ HStack {+ Text(Strings.shareYourLocation)+ Spacer()+ Toggle("", isOn: Binding(get: { user.sendingEnabled }, set: { onToggleSending($0) }))+ .labelsHidden()+ }+ AutoToggleRow(user: user, onSet: onSetAutoToggle) } .padding(12) .background(RoundedRectangle(cornerRadius: 12).fill(Color(.secondarySystemBackground)))@@ -110,6 +114,77 @@ struct UserDetailPanel: View { } } +// MARK: - Auto-toggle row ("Disable/Enable after" timer with live countdown)++/// Mirrors Android `AutoToggleRow`: a menu of durations that schedules an auto-flip of+/// `sendingEnabled`, plus a live 1-second countdown. "Never" cancels a pending timer.+struct AutoToggleRow: View {+ let user: User+ let onSet: (TimeInterval?) -> Void++ @State private var now = Date()++ private static let options: [(label: String, seconds: TimeInterval)] = [+ (Strings.duration15Minutes, 15 * 60),+ (Strings.duration30Minutes, 30 * 60),+ (Strings.duration1Hour, 60 * 60),+ (Strings.duration2Hours, 2 * 60 * 60),+ (Strings.duration4Hours, 4 * 60 * 60),+ (Strings.duration6Hours, 6 * 60 * 60),+ (Strings.duration12Hours, 12 * 60 * 60),+ (Strings.duration1Day, 24 * 60 * 60),+ (Strings.duration2Days, 2 * 24 * 60 * 60),+ (Strings.duration1Week, 7 * 24 * 60 * 60),+ ]++ /// Ticks once per second while a timer is pending so the countdown stays live.+ private let ticker = Timer.publish(every: 1, on: .main, in: .common).autoconnect()++ private var currentLabel: String {+ guard let endAt = user.sharingAutoToggleAt else { return Strings.autoToggleNever }+ let remaining = endAt.timeIntervalSince(now)+ if remaining <= 0 { return Strings.autoToggleNever }+ return Self.formatCountdown(remaining)+ }++ private var leadingLabel: String {+ user.sendingEnabled ? Strings.disableAfter : Strings.enableAfter+ }++ var body: some View {+ HStack {+ Text(leadingLabel)+ .font(.subheadline)+ Spacer()+ Menu {+ Button(Strings.autoToggleNever) { onSet(nil) }+ ForEach(Self.options, id: \.seconds) { opt in+ Button(opt.label) { onSet(opt.seconds) }+ }+ } label: {+ HStack(spacing: 4) {+ Text(currentLabel).font(.subheadline.monospacedDigit())+ Image(systemName: "chevron.up.chevron.down").font(.caption2)+ }+ .foregroundStyle(.accent)+ }+ }+ .onReceive(ticker) { t in+ // Only advance the clock while a timer is active to avoid needless redraws.+ if user.sharingAutoToggleAt != nil { now = t }+ }+ }++ /// `H:MM:SS` when ≥1 hour remains, else `MM:SS`. Matches Android's formatter.+ static func formatCountdown(_ remaining: TimeInterval) -> String {+ let total = max(0, Int(remaining))+ let h = total / 3600+ let m = (total % 3600) / 60+ let s = total % 60+ return h > 0 ? String(format: "%d:%02d:%02d", h, m, s) : String(format: "%02d:%02d", m, s)+ }+}+ // MARK: - Waypoint editor panel struct WaypointEditorPanel: View {
FindFamilyiOS/UI/Dialogs.swift
diff --git a/FindFamilyiOS/UI/Dialogs.swift b/FindFamilyiOS/UI/Dialogs.swiftindex 9b6d2e462e..12c576d678 100644--- a/FindFamilyiOS/UI/Dialogs.swift+++ b/FindFamilyiOS/UI/Dialogs.swift@@ -156,7 +156,60 @@ struct AddPersonDialog: View { } } -// MARK: - AddLinkDialog+// MARK: - SecurityCodeView++/// Displays the RSA safety number for a connection so both users can compare it out-of-band+/// (mirrors Android's SecurityCodeDialog). The code is computed off the main actor since it+/// runs SHA-256 ×4000. If the peer's key isn't available yet, an explanatory state is shown.+struct SecurityCodeView: View {+ let user: User+ @Binding var isPresented: Bool++ @State private var code: String?+ @State private var loading = true++ var body: some View {+ NavigationStack {+ VStack(spacing: 24) {+ Text(Strings.securityCodeCompare(user.name))+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)++ if loading {+ ProgressView().padding(.top, 8)+ Text(Strings.securityCodeComputing).font(.caption).foregroundStyle(.secondary)+ } else if let code = code {+ Text(code)+ .font(.title2.monospaced())+ .multilineTextAlignment(.center)+ .padding()+ .frame(maxWidth: .infinity)+ .background(RoundedRectangle(cornerRadius: 12).fill(Color(.secondarySystemBackground)))+ } else {+ Text(Strings.securityCodeUnavailable(user.name))+ .font(.callout)+ .foregroundStyle(.red)+ .multilineTextAlignment(.center)+ }+ Spacer()+ }+ .padding()+ .navigationTitle(Strings.securityCodeTitle)+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .confirmationAction) {+ Button(Strings.doneButton) { isPresented = false }+ }+ }+ .task {+ let result = await Networking.shared.securityCode(for: user)+ code = result+ loading = false+ }+ }+ }+} struct AddLinkDialog: View { @Binding var isPresented: Bool@@ -226,7 +279,12 @@ struct AddLinkDialog: View { print("AddLink: PQC ephemeral unavailable (native not linked?): \(error.localizedDescription)") } let link = TemporaryLink(- id: 0,+ // 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+ // made every device's first link id 1, so every `/view/1` collided on one+ // server queue. Use a random positive Int64 instead (mirrors Android+ // 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,
FindFamilyiOS/UI/MainView.swift
diff --git a/FindFamilyiOS/UI/MainView.swift b/FindFamilyiOS/UI/MainView.swiftindex 91dda028cd..d36c7650e7 100644--- a/FindFamilyiOS/UI/MainView.swift+++ b/FindFamilyiOS/UI/MainView.swift@@ -53,6 +53,7 @@ struct MainView: View { @State private var addPersonId: Int64? @State private var showAddLinkDialog = false @State private var showMissingFeaturesDialog = false+ @State private var showSecurityCode = false @State private var mapCenter = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),@@ -116,6 +117,11 @@ struct MainView: View { .sheet(isPresented: $showAddLinkDialog) { AddLinkDialog(isPresented: $showAddLinkDialog) }+ .sheet(isPresented: $showSecurityCode) {+ if let uid = selectedUserId, let user = vm.users.first(where: { $0.id == uid }) {+ SecurityCodeView(user: user, isPresented: $showSecurityCode)+ }+ } .alert(Strings.missingFeaturesTitle, isPresented: $showMissingFeaturesDialog) { Button(Strings.okButton, role: .cancel) {} } message: { Text(Strings.missingFeaturesExplanation) }@@ -163,6 +169,9 @@ struct MainView: View { BackupButtons() } else if let uid = selectedUserId, uid != Networking.shared.userid, let user = vm.users.first(where: { $0.id == uid }) {+ Button {+ showSecurityCode = true+ } label: { Image(systemName: "checkmark.shield") } Button(role: .destructive) { Database.shared.deleteUser(user) selectedUserId = nil@@ -247,9 +256,12 @@ struct MainView: View { Database.shared.upsertUser(u) }, onToggleSending: { send in- var u = user- u.sendingEnabled = send- Database.shared.upsertUser(u)+ // Manual toggle clears any pending auto-toggle (atomic, no clobber).+ Database.shared.setSendingEnabledAndClearToggle(id: user.id, enabled: send)+ },+ onSetAutoToggle: { seconds in+ let at = seconds.map { Date().addingTimeInterval($0) }+ Database.shared.setSharingAutoToggleAt(id: user.id, at: at) } ) .padding(.vertical, 12)
FindFamilyiOS/Util/Util.swift
diff --git a/FindFamilyiOS/Util/Util.swift b/FindFamilyiOS/Util/Util.swiftindex 57601cf288..a4d7b97cfa 100644--- a/FindFamilyiOS/Util/Util.swift+++ b/FindFamilyiOS/Util/Util.swift@@ -93,9 +93,39 @@ enum Strings { static func notifBatteryLowBody(_ name: String, _ pct: Int) -> String { "\(name)'s battery is at \(pct)%" } static let notifWaypointEnterTitle = "Place Update" static func notifWaypointEnterBody(_ name: String, _ place: String) -> String { "\(name) is at \(place)" }+ static let notifWaypointExitTitle = "Place Update"+ static func notifWaypointExitBody(_ name: String, _ place: String) -> String { "\(name) left \(place)" } static let okButton = "OK" static let cancelButton = "Cancel"+ static let doneButton = "Done"++ // Auto-toggle sharing ("Disable/Enable after" timer)+ static let autoToggleNever = "Never"+ static let disableAfter = "Disable after"+ static let enableAfter = "Enable after"++ // Duration options (shared with temporary-link expiry)+ static let duration15Minutes = "15 minutes"+ static let duration30Minutes = "30 minutes"+ static let duration1Hour = "1 hour"+ static let duration2Hours = "2 hours"+ static let duration4Hours = "4 hours"+ static let duration6Hours = "6 hours"+ static let duration12Hours = "12 hours"+ static let duration1Day = "1 day"+ static let duration2Days = "2 days"+ static let duration1Week = "1 week"++ // Security code (safety number) verification+ static let securityCodeTitle = "Security Code"+ static func securityCodeCompare(_ name: String) -> String {+ "Compare this code with the one shown on \(name)'s device. If they match, your connection is verified and no one is intercepting it."+ }+ static let securityCodeComputing = "Computing…"+ static func securityCodeUnavailable(_ name: String) -> String {+ "Couldn't compute the code yet — \(name)'s key isn't available. Try again once they've shared their location."+ } // PQC broken-lock info box (shown when tapping red lock for non-PQC peers) static let pqcUnprotectedTitle = "Quantum protection"