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

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

RelayKeyLookup.swift95 lines · 4.1 KiBRaw
1import Foundation
2
3/// Peer key lookup over the live relay's binary socket — the same GETKEY exchange the
4/// Android client uses, so both platforms read a peer's key capability through one code
5/// path and one set of status codes:
6///
7/// client→server [0x04][u64 target]
8/// server→client [0x05][status][u64 target][bundle…]
9///
10/// status: 0 = not registered, 1 = classic key only (outdated app), 2 = PQC bundle follows.
11///
12/// One request/response per connection, and deliberately **no SUB frame**. SUB is what
13/// makes the relay treat a socket as a live subscriber and fan that user's locations out
14/// to it instead of the queue that `/api/location/receive_pqc` drains — which this app
15/// still polls. Without SUB the socket is inert apart from this exchange, so the HTTP
16/// receive path is untouched.
17///
18/// Replaces the two-request HTTP probe (`/api/pqc/getkey` then `/api/getkey`): one frame
19/// returns the status *and* the bundle together, so there is no window between deciding a
20/// peer has a PQC key and fetching the key that gets verified.
21enum RelayKeyLookup {
22 /// Key capability of a peer, as reported by the relay.
23 enum Status: UInt8 {
24 case noKey = 0
25 case classic = 1
26 case pqc = 2
27 }
28
29 struct KeyResult {
30 let status: Status
31 /// The peer's public bundle — present only for `.pqc`.
32 let bundle: Data?
33 }
34
35 private static let url = URL(string: "wss://findfamily.cc/api/ws")!
36
37 /// Matches the Android client's GETKEY timeout.
38 private static let timeout: TimeInterval = 5
39
40 private static let opGetKeyRequest: UInt8 = 0x04
41 private static let opGetKeyResponse: UInt8 = 0x05
42
43 /// Looks up `userId`'s key. Returns nil when the socket can't be established or the
44 /// reply doesn't arrive in time; callers treat that as "unknown" rather than "absent".
45 static func getKey(userId: Int64) async -> KeyResult? {
46 let session = URLSession(configuration: .ephemeral)
47 let task = session.webSocketTask(with: url)
48 task.resume()
49 defer {
50 task.cancel(with: .goingAway, reason: nil)
51 session.invalidateAndCancel()
52 }
53
54 var request = Data([opGetKeyRequest])
55 withUnsafeBytes(of: UInt64(bitPattern: userId).bigEndian) { request.append(contentsOf: $0) }
56 guard (try? await task.send(.data(request))) != nil else { return nil }
57
58 return await firstKeyResponse(task, target: userId)
59 }
60
61 /// Reads frames until the KEYRESP for `target` arrives, or the timeout wins. The relay
62 /// only ever answers a GETKEY on an unsubscribed socket, but skipping non-matching
63 /// frames keeps this from being desynced by anything else it might send.
64 private static func firstKeyResponse(_ task: URLSessionWebSocketTask, target: Int64) async -> KeyResult? {
65 await withTaskGroup(of: KeyResult?.self) { group in
66 group.addTask {
67 while true {
68 guard let message = try? await task.receive() else { return nil }
69 guard case .data(let frame) = message else { continue }
70 if let result = parse(frame, target: target) { return result }
71 }
72 }
73 group.addTask {
74 try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
75 return nil
76 }
77 let first = await group.next() ?? nil
78 group.cancelAll()
79 return first
80 }
81 }
82
83 /// Parses `[0x05][status][u64 target][bundle…]`, or nil if this isn't the KEYRESP for
84 /// `target`.
85 private static func parse(_ frame: Data, target: Int64) -> KeyResult? {
86 let bytes = [UInt8](frame)
87 guard bytes.count >= 10, bytes[0] == opGetKeyResponse,
88 let status = Status(rawValue: bytes[1]) else { return nil }
89 var echoed: UInt64 = 0
90 for i in 0..<8 { echoed = (echoed << 8) | UInt64(bytes[2 + i]) }
91 guard Int64(bitPattern: echoed) == target else { return nil }
92 let bundle = bytes.count > 10 ? Data(bytes[10...]) : nil
93 return KeyResult(status: status, bundle: bundle)
94 }
95}