xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / DeveloperServices / OpenAPI / DeveloperServices+OpenAPI.swift
DeveloperServices+OpenAPI.swift280 lines · 9.2 KiBRaw
| 1 | import Foundation |
| 2 | import DeveloperAPI |
| 3 | import HTTPTypes |
| 4 | import OpenAPIRuntime |
| 5 | import OpenAPIURLSession |
| 6 | import Dependencies |
| 7 | |
| 8 | extension DeveloperAPIClient { |
| 9 | @TaskLocal fileprivate static var cursor: [URLQueryItem] = [] |
| 10 | |
| 11 | public init( |
| 12 | auth: DeveloperAPIAuthData |
| 13 | ) { |
| 14 | @Dependency(\.httpClient) var httpClient |
| 15 | self.init( |
| 16 | // swiftlint:disable:next force_try |
| 17 | serverURL: try! Servers.Server1.url(), |
| 18 | configuration: .init( |
| 19 | dateTranscoder: .iso8601WithFractionalSeconds |
| 20 | ), |
| 21 | transport: httpClient.asOpenAPITransport, |
| 22 | middlewares: [ |
| 23 | auth.middleware, |
| 24 | LoggingMiddleware(), |
| 25 | ] |
| 26 | ) |
| 27 | } |
| 28 | |
| 29 | /// Perform a paginated request, starting at the page given by `link`. |
| 30 | /// |
| 31 | /// `link` should be a URL that contains a `cursor` query parameter. The |
| 32 | /// cursor will be applied to any requests made inside the closure. |
| 33 | public static func withNextLink<T>( |
| 34 | _ link: String?, |
| 35 | isolation: isolated (any Actor)? = #isolation, |
| 36 | perform action: () async throws -> T |
| 37 | ) async throws -> T { |
| 38 | let cursor: [URLQueryItem] |
| 39 | |
| 40 | if let link { |
| 41 | guard let components = URLComponents(string: link), |
| 42 | let newOffset = components.queryItems?.first(where: { $0.name == "cursor" }), |
| 43 | let newLimit = components.queryItems?.first(where: { $0.name == "limit" }) |
| 44 | else { throw Errors.badNextLink(link) } |
| 45 | // the next value will contain a cursor (offset) *and* a limit even if we didn't |
| 46 | // provide a limit in our initial request. we need to include the limit in subsequent |
| 47 | // requests, otherwise the cursor isn't respected. |
| 48 | cursor = [newOffset, newLimit] |
| 49 | } else { |
| 50 | cursor = [] |
| 51 | } |
| 52 | |
| 53 | return try await $cursor.withValue(cursor) { |
| 54 | try await action() |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | public enum Errors: Error { |
| 59 | case badNextLink(String) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | public enum DeveloperAPIAuthData: Sendable { |
| 64 | case appStoreConnect(ASCKey) |
| 65 | case xcode(XcodeAuthData) |
| 66 | |
| 67 | fileprivate var middleware: ClientMiddleware { |
| 68 | switch self { |
| 69 | case .appStoreConnect(let key): |
| 70 | DeveloperAPIASCAuthMiddleware(key: key) |
| 71 | case .xcode(let authData): |
| 72 | DeveloperAPIXcodeAuthMiddleware(authData: authData) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | public var isPublicAPI: Bool { |
| 77 | switch self { |
| 78 | case .appStoreConnect: true |
| 79 | case .xcode: false |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // A unique ID tied to this token |
| 84 | public var identityID: String { |
| 85 | switch self { |
| 86 | case .appStoreConnect(let key): |
| 87 | key.issuerID |
| 88 | case .xcode(let data): |
| 89 | data.teamID.rawValue |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | public struct XcodeAuthData: Sendable { |
| 95 | public var loginToken: DeveloperServicesLoginToken |
| 96 | public var teamID: DeveloperServicesTeam.ID |
| 97 | |
| 98 | public init( |
| 99 | loginToken: DeveloperServicesLoginToken, |
| 100 | teamID: DeveloperServicesTeam.ID |
| 101 | ) { |
| 102 | self.loginToken = loginToken |
| 103 | self.teamID = teamID |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | public struct DeveloperAPIXcodeAuthMiddleware: ClientMiddleware { |
| 108 | @Dependency(\.anisetteDataProvider) private var anisetteDataProvider |
| 109 | |
| 110 | public var authData: XcodeAuthData |
| 111 | |
| 112 | public init(authData: XcodeAuthData) { |
| 113 | self.authData = authData |
| 114 | } |
| 115 | |
| 116 | private static let baseURL = URL(string: "https://developerservices2.apple.com/services")! |
| 117 | private static let queryEncoder = JSONEncoder() |
| 118 | |
| 119 | public func intercept( |
| 120 | _ request: HTTPRequest, |
| 121 | body: HTTPBody?, |
| 122 | baseURL: URL, |
| 123 | operationID: String, |
| 124 | next: @Sendable ( |
| 125 | _ request: HTTPRequest, |
| 126 | _ body: HTTPBody?, |
| 127 | _ baseURL: URL |
| 128 | ) async throws -> (HTTPResponse, HTTPBody?) |
| 129 | ) async throws -> (HTTPResponse, HTTPBody?) { |
| 130 | var request = request |
| 131 | |
| 132 | let anisetteData = try await anisetteDataProvider.fetchAnisetteData() |
| 133 | |
| 134 | // General |
| 135 | request.headerFields[.acceptLanguage] = Locale.preferredLanguages.joined(separator: ", ") |
| 136 | request.headerFields[.accept] = "application/vnd.api+json" |
| 137 | request.headerFields[.contentType] = "application/vnd.api+json" |
| 138 | request.headerFields[.acceptEncoding] = "gzip, deflate" |
| 139 | |
| 140 | // Xcode-specific |
| 141 | request.headerFields[.userAgent] = "Xcode" |
| 142 | request.headerFields[.init(DeviceInfo.xcodeVersionKey)!] = DeviceInfo.xcodeVersion |
| 143 | |
| 144 | // GrandSlam authentication |
| 145 | request.headerFields[.init("X-Apple-App-Info")!] = AppTokenKey.xcode.rawValue |
| 146 | request.headerFields[.init("X-Apple-I-Identity-Id")!] = authData.loginToken.adsid |
| 147 | request.headerFields[.init("X-Apple-GS-Token")!] = authData.loginToken.token |
| 148 | |
| 149 | // Anisette |
| 150 | for (key, value) in anisetteData.dictionary { |
| 151 | request.headerFields[.init(key)!] = value |
| 152 | } |
| 153 | |
| 154 | // Body |
| 155 | var body = body |
| 156 | let originalMethod = request.method |
| 157 | switch originalMethod { |
| 158 | case .get, .delete: |
| 159 | request.headerFields[.init("X-HTTP-Method-Override")!] = originalMethod.rawValue |
| 160 | request.method = .post |
| 161 | |
| 162 | let path = request.path ?? "/" |
| 163 | var components = URLComponents(string: path) ?? .init() |
| 164 | |
| 165 | var items = components.queryItems ?? [] |
| 166 | items.upsertQueryItems(DeveloperAPIClient.cursor + [ |
| 167 | URLQueryItem(name: "teamId", value: authData.teamID.rawValue) |
| 168 | ]) |
| 169 | components.queryItems = items |
| 170 | |
| 171 | let query = components.percentEncodedQuery ?? "" |
| 172 | |
| 173 | components.query = nil |
| 174 | request.path = components.path |
| 175 | |
| 176 | let bodyData = try DeveloperAPIXcodeAuthMiddleware.queryEncoder.encode(["urlEncodedQueryParams": query]) |
| 177 | body = HTTPBody(bodyData) |
| 178 | case .patch, .post: |
| 179 | // set .data.attributes.teamId = teamID |
| 180 | |
| 181 | var workingBody: [String: Any] = [:] |
| 182 | if let existingBody = body { |
| 183 | let data = try await Data(collecting: existingBody, upTo: .max) |
| 184 | guard let decodedBody = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { |
| 185 | throw Errors.malformedPayload("body") |
| 186 | } |
| 187 | workingBody = decodedBody |
| 188 | } |
| 189 | |
| 190 | var workingData: [String: Any] = [:] |
| 191 | if let existingData = workingBody["data"] { |
| 192 | guard let decodedData = existingData as? [String: Any] else { |
| 193 | throw Errors.malformedPayload("data") |
| 194 | } |
| 195 | workingData = decodedData |
| 196 | } |
| 197 | |
| 198 | var workingAttributes: [String: Any] = [:] |
| 199 | if let existingAttributes = workingData["attributes"] { |
| 200 | guard let decodedAttributes = existingAttributes as? [String: Any] else { |
| 201 | throw Errors.malformedPayload("attributes") |
| 202 | } |
| 203 | workingAttributes = decodedAttributes |
| 204 | } |
| 205 | |
| 206 | workingAttributes["teamId"] = authData.teamID.rawValue |
| 207 | workingData["attributes"] = workingAttributes |
| 208 | workingBody["data"] = workingData |
| 209 | |
| 210 | let encodedBody = try JSONSerialization.data(withJSONObject: workingBody) |
| 211 | |
| 212 | body = HTTPBody(encodedBody) |
| 213 | request.headerFields[.contentLength] = "\(encodedBody.count)" |
| 214 | default: |
| 215 | throw Errors.unrecognizedHTTPMethod(originalMethod.rawValue) |
| 216 | } |
| 217 | |
| 218 | var (response, responseBody) = try await next(request, body, DeveloperAPIXcodeAuthMiddleware.baseURL) |
| 219 | |
| 220 | if response.headerFields[.contentType] == "application/vnd.api+json" { |
| 221 | response.headerFields[.contentType] = "application/json" |
| 222 | } |
| 223 | |
| 224 | return (response, responseBody) |
| 225 | } |
| 226 | |
| 227 | public enum Errors: Error { |
| 228 | case unrecognizedHTTPMethod(String) |
| 229 | case malformedPayload(String) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | public struct DeveloperAPIASCAuthMiddleware: ClientMiddleware { |
| 234 | private var generator: ASCJWTGenerator |
| 235 | |
| 236 | public var key: ASCKey { |
| 237 | get { generator.key } |
| 238 | set { generator = ASCJWTGenerator(key: newValue) } |
| 239 | } |
| 240 | |
| 241 | public init(key: ASCKey) { |
| 242 | generator = ASCJWTGenerator(key: key) |
| 243 | } |
| 244 | |
| 245 | public func intercept( |
| 246 | _ request: HTTPRequest, |
| 247 | body: HTTPBody?, |
| 248 | baseURL: URL, |
| 249 | operationID: String, |
| 250 | next: @Sendable ( |
| 251 | _ request: HTTPRequest, |
| 252 | _ body: HTTPBody?, |
| 253 | _ baseURL: URL |
| 254 | ) async throws -> (HTTPResponse, HTTPBody?) |
| 255 | ) async throws -> (HTTPResponse, HTTPBody?) { |
| 256 | var request = request |
| 257 | |
| 258 | let jwt = try await generator.generate() |
| 259 | request.headerFields[.authorization] = "Bearer \(jwt)" |
| 260 | |
| 261 | let cursor = DeveloperAPIClient.cursor |
| 262 | if !cursor.isEmpty { |
| 263 | var components = URLComponents(string: request.path ?? "") ?? .init() |
| 264 | var items = components.queryItems ?? [] |
| 265 | items.upsertQueryItems(cursor) |
| 266 | components.queryItems = items |
| 267 | request.path = components.string |
| 268 | } |
| 269 | |
| 270 | return try await next(request, body, baseURL) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | extension [URLQueryItem] { |
| 275 | fileprivate mutating func upsertQueryItems(_ items: [URLQueryItem]) { |
| 276 | let newNames = Set(items.map(\.name)) |
| 277 | removeAll { newNames.contains($0.name) } |
| 278 | append(contentsOf: items) |
| 279 | } |
| 280 | } |