xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / GrandSlam / Operations / GrandSlamFetchAppTokensOperation.swift
GrandSlamFetchAppTokensOperation.swift78 lines · 2.1 KiBRaw
| 1 | // |
| 2 | // GrandSlamFetchAppTokensOperation.swift |
| 3 | // XKit |
| 4 | // |
| 5 | // Created by Kabir Oberai on 20/11/19. |
| 6 | // Copyright © 2019 Kabir Oberai. All rights reserved. |
| 7 | // |
| 8 | |
| 9 | import Foundation |
| 10 | |
| 11 | struct AppTokenKey: Hashable { |
| 12 | let rawValue: String |
| 13 | init(_ rawValue: String) { self.rawValue = rawValue } |
| 14 | } |
| 15 | |
| 16 | extension AppTokenKey { |
| 17 | static let xcode = AppTokenKey("com.apple.gs.xcode.auth") |
| 18 | } |
| 19 | |
| 20 | struct GrandSlamFetchAppTokensOperation { |
| 21 | |
| 22 | enum Error: Swift.Error { |
| 23 | case invalidResponse |
| 24 | } |
| 25 | |
| 26 | struct Token: Decodable { |
| 27 | let value: String |
| 28 | |
| 29 | private let _expiry: Int |
| 30 | var expiry: Date { |
| 31 | Date(timeIntervalSince1970: .init(_expiry) / 1000) |
| 32 | } |
| 33 | |
| 34 | private enum CodingKeys: String, CodingKey { |
| 35 | case value = "token" |
| 36 | case _expiry = "expiry" |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | private struct Response: Decodable { |
| 41 | let tokens: [String: Token] |
| 42 | |
| 43 | private enum CodingKeys: String, CodingKey { |
| 44 | case tokens = "t" |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | private static let decoder = PropertyListDecoder() |
| 49 | |
| 50 | let client: GrandSlamClient |
| 51 | let apps: [AppTokenKey] |
| 52 | let loginData: GrandSlamLoginData |
| 53 | |
| 54 | private func handle( |
| 55 | response: GrandSlamAppTokensRequest.Decoder.Value |
| 56 | ) async throws -> [AppTokenKey: Token] { |
| 57 | let decrypted = try AppTokens.decrypt(gcm: response.encryptedToken, withSK: loginData.sk) |
| 58 | let pairs = try Self.decoder |
| 59 | .decode(Response.self, from: decrypted) |
| 60 | .tokens |
| 61 | .map { (AppTokenKey($0), $1) } |
| 62 | return Dictionary(uniqueKeysWithValues: pairs) |
| 63 | } |
| 64 | |
| 65 | func perform() async throws -> [AppTokenKey: Token] { |
| 66 | let checksum = AppTokens.checksum(withSK: loginData.sk, adsid: loginData.adsid, apps: apps.map { $0.rawValue }) |
| 67 | let appTokensRequest = GrandSlamAppTokensRequest( |
| 68 | username: loginData.adsid, |
| 69 | apps: apps, |
| 70 | cookie: loginData.cookie, |
| 71 | idmsToken: loginData.idmsToken, |
| 72 | checksum: checksum |
| 73 | ) |
| 74 | let response = try await client.send(appTokensRequest) |
| 75 | return try await self.handle(response: response) |
| 76 | } |
| 77 | |
| 78 | } |