Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / GrandSlam / Anisette / ADIDataProvider.swift

ADIDataProvider.swift312 lines · 10.4 KiBRaw
1import Foundation
2import Crypto
3import ConcurrencyExtras
4import Dependencies
5
6public protocol RawADIProvider: Sendable {
7 func clientInfo() async throws -> ClientInfoWithUserAgent
8
9 func startProvisioning(
10 spim: Data,
11 userID: UUID
12 ) async throws -> (RawADIProvisioningSession, Data)
13
14 func requestOTP(
15 userID: UUID,
16 routingInfo: inout UInt64,
17 provisioningInfo: Data
18 ) async throws -> (machineID: Data, otp: Data)
19}
20
21public struct ClientInfoWithUserAgent: Sendable {
22 public let clientInfo: String
23 public let akdUserAgent: String
24}
25
26private struct UnimplementedRawADIProvider: RawADIProvider {
27 func startProvisioning(
28 spim: Data,
29 userID: UUID
30 ) async throws -> (any RawADIProvisioningSession, Data) {
31 let closure: (Data, UUID) async throws -> (any RawADIProvisioningSession, Data) = unimplemented()
32 return try await closure(spim, userID)
33 }
34
35 func requestOTP(
36 userID: UUID,
37 routingInfo: inout UInt64,
38 provisioningInfo: Data
39 ) async throws -> (machineID: Data, otp: Data) {
40 let closure: (UUID, inout UInt64, Data) async throws -> (Data, Data) = unimplemented()
41 return try await closure(userID, &routingInfo, provisioningInfo)
42 }
43
44 func clientInfo() async throws -> ClientInfoWithUserAgent {
45 let closure: () async throws -> ClientInfoWithUserAgent = unimplemented()
46 return try await closure()
47 }
48}
49
50private enum RawADIProviderDependencyKey: DependencyKey {
51 static let testValue: RawADIProvider = UnimplementedRawADIProvider()
52 static let liveValue: RawADIProvider = OmnisetteADIProvider()
53}
54
55extension DependencyValues {
56 public var rawADIProvider: RawADIProvider {
57 get { self[RawADIProviderDependencyKey.self] }
58 set { self[RawADIProviderDependencyKey.self] = newValue }
59 }
60}
61
62public protocol RawADIProvisioningSession: Sendable {
63 func endProvisioning(
64 routingInfo: UInt64,
65 ptm: Data,
66 tk: Data
67 ) async throws -> Data
68}
69
70// uses CoreADI APIs
71public struct ADIDataProvider: AnisetteDataProvider {
72
73 public enum ADIError: Error {
74 case hashingFailed
75 case noResponse
76 case badStartResponse
77 case badEndResponse
78 }
79
80 @Dependency(\.keyValueStorage) var storage
81 @Dependency(\.rawADIProvider) var rawProvider
82 @Dependency(\.httpClient) var httpClient
83
84 private let lookupManager = GrandSlamLookupManager()
85 private let localUserUID: UUID
86 private let localUserID: String
87
88 private let _clientInfo = LockIsolated<ClientInfoWithUserAgent?>(nil)
89
90 public init() {
91 @Dependency(\.keyValueStorage) var storage
92
93 if let localUserUIDString = try? storage.string(forKey: Self.localUserUIDKey),
94 let localUserUID = UUID(uuidString: localUserUIDString) {
95 self.localUserUID = localUserUID
96 } else {
97 let localUserUID = UUID()
98 try? storage.setString(localUserUID.uuidString, forKey: Self.localUserUIDKey)
99 self.localUserUID = localUserUID
100 }
101 // localUserID = SHA256(local user UID)
102 self.localUserID = SHA256.hash(data: Data(localUserUID.uuidString.utf8))
103 .map { String(format: "%02X", $0) }
104 .joined()
105
106 if (try? storage.string(forKey: Self.providerIDKey)) != Self.providerID {
107 self.resetProvisioning()
108 try? storage.setString(Self.providerID, forKey: Self.providerIDKey)
109 }
110 }
111
112 private static let localUserUIDKey = "XTLLocalUserUID"
113 private static let providerIDKey = "XTLADIProviderID"
114 private static let provisioningKey = "XTLProvisioningInfo"
115 private static let routingInfoKey = "XTLRoutingInfo"
116
117 private struct GSARequest<T: Encodable>: Encodable {
118 let header: [String: String] = [:]
119 let request: T
120
121 private enum CodingKeys: String, CodingKey {
122 case header = "Header"
123 case request = "Request"
124 }
125 }
126
127 private struct StartProvisioningRequest: Encodable {}
128 private struct StartProvisioningResponse: Decodable {
129 let spim: String
130 }
131
132 private struct EndProvisioningRequest: Encodable {
133 let cpim: String
134 }
135 private struct EndProvisioningResponse: Decodable {
136 let ptm: String // base64
137 let tk: String // base64
138 let rinfo: String // number (u64)
139
140 private enum CodingKeys: String, CodingKey {
141 case ptm
142 case tk
143 case rinfo = "X-Apple-I-MD-RINFO"
144 }
145 }
146
147 private static let encoder: PropertyListEncoder = {
148 let encoder = PropertyListEncoder()
149 encoder.outputFormat = .xml
150 return encoder
151 }()
152
153 private func clientInfo() async throws -> ClientInfoWithUserAgent {
154 if let clientInfo = _clientInfo.value { return clientInfo }
155 let clientInfo = try await rawProvider.clientInfo()
156 _clientInfo.setValue(clientInfo)
157 return clientInfo
158 }
159
160 private func sendRequest<Request: Encodable, Response: Decodable>(
161 endpoint: GrandSlamEndpoint,
162 request: Request
163 ) async throws -> Response {
164 let endpointURL = try await lookupManager.fetchURL(forEndpoint: endpoint)
165
166 let body = try Self.encoder.encode(GSARequest(request: request))
167
168 var request = HTTPRequest(url: endpointURL)
169 request.method = .post
170 request.headerFields = [
171 .contentType: "text/x-xml-plist",
172 .acceptLanguage: "en_US",
173 .init(AnisetteData.localUserIDKey)!: self.localUserID,
174 ]
175 request.headerFields[.init("X-MMe-Country")!] = Locale.current.region?.identifier
176
177 for (key, value) in try await deviceInfo().dictionary {
178 request.headerFields[.init(key)!] = value
179 }
180
181 let (_, response) = try await self.httpClient.makeRequest(request, body: body, ephemeral: true)
182
183 return try GrandSlamOperationDecoder<Response>.decode(data: response)
184 }
185
186 private func endProvisioning(
187 session: RawADIProvisioningSession,
188 cpim: Data
189 ) async throws -> (routingInfo: UInt64, provisioningInfo: Data) {
190 let resp: EndProvisioningResponse = try await sendRequest(
191 endpoint: .lookup(\.midFinishProvisioning),
192 request: EndProvisioningRequest(cpim: cpim.base64EncodedString())
193 )
194
195 guard let rinfo = UInt64(resp.rinfo),
196 let ptm = Data(base64Encoded: resp.ptm),
197 let tk = Data(base64Encoded: resp.tk)
198 else { throw ADIError.badEndResponse }
199
200 let provisioningInfo = try await session.endProvisioning(
201 routingInfo: rinfo, ptm: ptm, tk: tk
202 )
203
204 return (rinfo, provisioningInfo)
205 }
206
207 private func provision() async throws -> (routingInfo: UInt64, provisioningInfo: Data) {
208 let resp: StartProvisioningResponse = try await sendRequest(
209 endpoint: .lookup(\.midStartProvisioning),
210 request: StartProvisioningRequest()
211 )
212 guard let spim = Data(base64Encoded: resp.spim) else { throw ADIError.badStartResponse }
213 let (session, cpim) = try await rawProvider.startProvisioning(spim: spim, userID: localUserUID)
214 return try await endProvisioning(session: session, cpim: cpim)
215 }
216
217 private func fetchAnisetteData(
218 routingInfo: UInt64,
219 provisioningInfo: Data
220 ) async throws -> AnisetteData {
221 let requestTime = Date()
222 var routingInfo = routingInfo
223 let (mid, otp) = try await rawProvider.requestOTP(
224 userID: localUserUID,
225 routingInfo: &routingInfo,
226 provisioningInfo: provisioningInfo
227 )
228 return AnisetteData(
229 clientTime: requestTime,
230 routingInfo: routingInfo,
231 machineID: mid.base64EncodedString(),
232 localUserID: self.localUserID,
233 oneTimePassword: otp.base64EncodedString(),
234 deviceInfo: try await deviceInfo(),
235 )
236 }
237
238 public func resetProvisioning() {
239 try? storage.setData(nil, forKey: Self.provisioningKey)
240 try? storage.setString(nil, forKey: Self.routingInfoKey)
241 }
242
243 private static var providerID: String? {
244 "mac-omnisette"
245 }
246
247 public var providerID: String? { Self.providerID }
248
249 public func provisioningData() -> ProvisioningData? {
250 guard let provisioningInfo = try? storage.data(forKey: Self.provisioningKey),
251 let routingInfoString = try? storage.string(forKey: Self.routingInfoKey),
252 let routingInfo = UInt64(routingInfoString)
253 else { return nil }
254 return ProvisioningData(
255 localUserUID: localUserUID,
256 routingInfo: routingInfo,
257 adiPb: provisioningInfo
258 )
259 }
260
261 public func fetchAnisetteData() async throws -> AnisetteData {
262 if let provisioningInfo = try storage.data(forKey: Self.provisioningKey),
263 let routingInfoString = try storage.string(forKey: Self.routingInfoKey),
264 let routingInfo = UInt64(routingInfoString) {
265 return try await fetchAnisetteData(
266 routingInfo: routingInfo,
267 provisioningInfo: provisioningInfo
268 )
269 }
270
271 let (rinfo, data) = try await provision()
272
273 try self.storage.setData(data, forKey: Self.provisioningKey)
274 try self.storage.setString("\(rinfo)", forKey: Self.routingInfoKey)
275
276 return try await fetchAnisetteData(
277 routingInfo: rinfo,
278 provisioningInfo: data
279 )
280 }
281
282 public func deviceInfo() async throws -> DeviceInfo {
283 let clientInfo = try await clientInfo()
284 return DeviceInfo(
285 deviceID: localUserUID.uuidString,
286 clientInfo: clientInfo.clientInfo,
287 akdUserAgent: clientInfo.akdUserAgent,
288 )
289 }
290
291}
292
293public struct ADIError: Error, CustomStringConvertible {
294 public var code: Int
295
296 public var description: String {
297 switch code {
298 case -45061:
299 return """
300 You were logged out. Please log in again with `xtool auth`.
301
302 If you see this repeatedly, please file an issue at https://github.com/xtool-org/xtool/issues/new/choose
303 """
304 default:
305 return """
306 Apple Anisette library returned error \(code). Please try logging in again with `xtool auth`.
307
308 If this problem persists, file an issue at https://github.com/xtool-org/xtool/issues/new/choose
309 """
310 }
311 }
312}