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

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

RelayKeyLookup.swift102 lines · 4.6 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/// Asked on the app's live relay socket (`RelaySocket`) when it is subscribed. Otherwise
13/// one request/response on a throwaway connection, deliberately with **no SUB frame**:
14/// SUB is what makes the relay treat a socket as a live subscriber and fan that user's
15/// locations out to it instead of the queue, so a SUB here would steal pushes from the
16/// real socket. Without SUB the throwaway socket is inert apart from this exchange.
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://api.maproj.org/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 if let live = await RelaySocket.shared.getKey(userId: userId) { return live }
47 let session = URLSession(configuration: .ephemeral)
48 let task = session.webSocketTask(with: url)
49 task.resume()
50 defer {
51 task.cancel(with: .goingAway, reason: nil)
52 session.invalidateAndCancel()
53 }
54
55 var request = Data([opGetKeyRequest])
56 withUnsafeBytes(of: UInt64(bitPattern: userId).bigEndian) { request.append(contentsOf: $0) }
57 guard (try? await task.send(.data(request))) != nil else { return nil }
58
59 return await firstKeyResponse(task, target: userId)
60 }
61
62 /// Reads frames until the KEYRESP for `target` arrives, or the timeout wins. The relay
63 /// only ever answers a GETKEY on an unsubscribed socket, but skipping non-matching
64 /// frames keeps this from being desynced by anything else it might send.
65 private static func firstKeyResponse(_ task: URLSessionWebSocketTask, target: Int64) async -> KeyResult? {
66 await withTaskGroup(of: KeyResult?.self) { group in
67 group.addTask {
68 while true {
69 guard let message = try? await task.receive() else { return nil }
70 guard case .data(let frame) = message else { continue }
71 if let result = parse(frame, target: target) { return result }
72 }
73 }
74 group.addTask {
75 try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
76 return nil
77 }
78 let first = await group.next() ?? nil
79 group.cancelAll()
80 return first
81 }
82 }
83
84 /// Parses `[0x05][status][u64 target][bundle…]`, or nil if this isn't the KEYRESP for
85 /// `target`.
86 private static func parse(_ frame: Data, target: Int64) -> KeyResult? {
87 guard let reply = parseAny(frame), reply.target == target else { return nil }
88 return reply.result
89 }
90
91 /// Parses any KEYRESP `[0x05][status][u64 target][bundle…]` into its target and result
92 /// (shared with `RelaySocket`, which matches replies to its pending lookups).
93 static func parseAny(_ frame: Data) -> (target: Int64, result: KeyResult)? {
94 let bytes = [UInt8](frame)
95 guard bytes.count >= 10, bytes[0] == opGetKeyResponse,
96 let status = Status(rawValue: bytes[1]) else { return nil }
97 var echoed: UInt64 = 0
98 for i in 0..<8 { echoed = (echoed << 8) | UInt64(bytes[2 + i]) }
99 let bundle = bytes.count > 10 ? Data(bytes[10...]) : nil
100 return (Int64(bitPattern: echoed), KeyResult(status: status, bundle: bundle))
101 }
102}