Modern Apps git

← xtool.git

More linux

Commit
bc9af7dd1e2cf7b8f0f231aadaff9b6218605d3e
Author
Kabir Oberai <[email protected]>
When
2024-11-11 23:39 UTC (2 years ago)
Parents
c3776f4

Diff

Supersign/Package.swift
diff --git a/Supersign/Package.swift b/Supersign/Package.swiftindex b232446..da6db1c 100644--- a/Supersign/Package.swift+++ b/Supersign/Package.swift@@ -33,7 +33,8 @@ let package = Package(         .package(path: "../SuperchargeCore"),         .package(path: "../SwiftyMobileDevice"),         .package(path: "../USBMuxSim"),-        .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.18.0"),+        .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.23.0"),+        .package(url: "https://github.com/vapor/websocket-kit.git", from: "2.15.0"),         .package(url: "https://github.com/apple/swift-certificates", from: "1.0.0-beta.1"),     ],     targets: [@@ -59,7 +60,12 @@ let package = Package(                     name: "AsyncHTTPClient",                     package: "async-http-client",                     condition: .when(platforms: [.linux])-                )+                ),+                .product(+                    name: "WebSocketKit",+                    package: "websocket-kit",+                    condition: .when(platforms: [.linux])+                ),             ],             cSettings: cSettings         ),
Supersign/Sources/Supersign/GrandSlam/Anisette/OmnisetteADIProvider.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/OmnisetteADIProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/OmnisetteADIProvider.swiftindex 98e5503..0726581 100644--- a/Supersign/Sources/Supersign/GrandSlam/Anisette/OmnisetteADIProvider.swift+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/OmnisetteADIProvider.swift@@ -1,12 +1,21 @@ import Foundation  struct OmnisetteADIProvider: RawADIProvider {+    enum Errors: Error {+        case websocketClosed(URLSessionWebSocketTask.CloseCode)+    }+     // should implement v3 of https://github.com/SideStore/omnisette-server     // list: https://servers.sidestore.io/servers.json     // e.g. https://ani.sidestore.io     private let url: URL-    init(url: URL = URL(string: "https://ani.sidestore.io")!) {+    private let client: HTTPClientProtocol+    init(+        url: URL = URL(string: "https://ani.sidestore.io")!, // URL(string: "http://localhost:6969")!,+        httpFactory: HTTPClientFactory = defaultHTTPClientFactory+    ) {         self.url = url+        self.client = httpFactory.makeClient()     }      static let decoder: JSONDecoder = {@@ -27,8 +36,10 @@ struct OmnisetteADIProvider: RawADIProvider {         struct ClientInfo: Decodable {             let clientInfo: String         }-        let (response, _) = try await URLSession.shared.data(from: url.appendingPathComponent("v3/client_info"))-        let clientInfo = try Self.decoder.decode(ClientInfo.self, from: response)+        let body = try await client.makeRequest(+            HTTPRequest(url: url.appendingPathComponent("v3/client_info"))+        ).body ?? Data()+        let clientInfo = try Self.decoder.decode(ClientInfo.self, from: body)         return clientInfo.clientInfo     } @@ -37,8 +48,8 @@ struct OmnisetteADIProvider: RawADIProvider {         var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!         components.scheme = components.scheme == "http" ? "ws" : "wss"         url = components.url!-        let task = URLSession.shared.webSocketTask(with: url)-        task.resume()++        let task = try await client.makeWebSocket(url: url)         let connection = OmnisetteProvisioningSession(task: task)         let cpim = try await connection.startProvisioning(spim: spim, userID: userID)         return (connection, cpim)@@ -66,14 +77,14 @@ struct OmnisetteADIProvider: RawADIProvider {             }         } -        var request = URLRequest(url: url.appendingPathComponent("v3/get_headers"))-        request.httpMethod = "POST"-        request.httpBody = try Self.encoder.encode(Request(+        var request = HTTPRequest(url: url.appendingPathComponent("v3/get_headers"))+        request.method = "POST"+        request.body = .buffer(try Self.encoder.encode(Request(             identifier: userID.rawBytes,             adiPb: provisioningInfo-        ))-        request.setValue("application/json", forHTTPHeaderField: "Content-Type")-        let (response, _) = try await URLSession.shared.data(for: request)+        )))+        request.headers["Content-Type"] = "application/json"+        let response = try await client.makeRequest(request).body ?? Data()         let decoded = try Self.decoder.decode(Response.self, from: response)         if let rinfo = UInt64(decoded.rinfo) {             routingInfo = rinfo@@ -83,9 +94,9 @@ struct OmnisetteADIProvider: RawADIProvider { }  private final class OmnisetteProvisioningSession: RawADIProvisioningSession {-    let task: URLSessionWebSocketTask+    let task: WebSocketSession -    init(task: URLSessionWebSocketTask) {+    init(task: WebSocketSession) {         self.task = task     } @@ -94,7 +105,7 @@ private final class OmnisetteProvisioningSession: RawADIProvisioningSession {     }      private func close() {-        task.cancel(with: .normalClosure, reason: nil)+        task.close()     }      func startProvisioning(@@ -151,7 +162,7 @@ private final class OmnisetteProvisioningSession: RawADIProvisioningSession {     private func receive<T: Decodable>(_ message: String, as type: T.Type = EmptyResponse.self) async throws -> T {         let data = switch try await task.receive() {         case .data(let data): data-        case .string(let text): Data(text.utf8)+        case .text(let text): Data(text.utf8)         @unknown default: Data()         }         let header = try OmnisetteADIProvider.decoder.decode(Header.self, from: data)@@ -166,7 +177,7 @@ private final class OmnisetteProvisioningSession: RawADIProvisioningSession {      private func send<T: Encodable>(_ message: T) async throws {         let encoded = try OmnisetteADIProvider.encoder.encode(message)-        try await task.send(.string(String(decoding: encoded, as: UTF8.self)))+        try await task.send(.text(String(decoding: encoded, as: UTF8.self)))     } } 
Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
diff --git a/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swiftindex 5c82bf7..7bf8b46 100644--- a/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift+++ b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift@@ -36,7 +36,7 @@ class GrandSlamClient {         var httpRequest = HTTPRequest(url: url, method: method.name)         httpRequest.headers = [             "Content-Type": "text/x-xml-plist",-            DeviceInfo.clientInfoKey: deviceInfo.clientInfo.clientString+            DeviceInfo.clientInfoKey: "<PC> <Windows;6.2(0,0);9200> <com.apple.AuthKitWin/1 (com.apple.iCloud/7.21)>" // deviceInfo.clientInfo.clientString         ]         switch method {         case .get:
Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swiftindex 384b53a..5938b1b 100644--- a/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift@@ -12,6 +12,7 @@ import NIO import NIOHTTP1 import NIOSSL import NIOFoundationCompat+import WebSocketKit  extension HTTPClient: HTTPClientProtocol {     @discardableResult@@ -37,6 +38,70 @@ extension HTTPClient: HTTPClientProtocol {             body: body         )     }++    public func makeWebSocket(url: URL) async throws -> any WebSocketSession {+        let (stream, continuation) = AsyncStream.makeStream(of: WebSocketSessionWrapper.self)+        async let value = stream.first(where: { _ in true })+        // must be after the `async let` so that we finish if connect throws+        defer { continuation.finish() }+        // we can't use the async overload because we need to immediately subscribe+        // to onText/onBinary in the same EventLoop tick that the WebSocket is created.+        // This is also why we create the SessionWrapper inside the closure.+        let future = WebSocket.connect(to: url, on: eventLoopGroup) {+            continuation.yield(WebSocketSessionWrapper(webSocket: $0))+        }+        try await future.get()+        guard let webSocket = await value else {+            throw Errors.connectFailed+        }+        return webSocket+    }++    private enum Errors: Error {+        case connectFailed+    }+}++private final class WebSocketSessionWrapper: WebSocketSession {+    let webSocket: WebSocket+    let stream: AsyncStream<WebSocketMessage>+    private let finishStream: () -> Void++    init(webSocket: WebSocket) {+        self.webSocket = webSocket++        let (stream, continuation) = AsyncStream<WebSocketMessage>.makeStream(bufferingPolicy: .unbounded)+        self.stream = stream+        self.finishStream = { continuation.finish() }+        webSocket.onText { _, text in+            continuation.yield(.text(text))+        }+        webSocket.onBinary { _, data in+            continuation.yield(.data(Data(data.readableBytesView)))+        }+    }++    deinit {+        close()+    }++    func close() {+        finishStream()+        Task { [webSocket] in try? await webSocket.close() }+    }++    func send(_ message: WebSocketMessage) async throws {+        switch message {+        case .text(let text):+            try await webSocket.send(text)+        case .data(let data):+            try await webSocket.send(.init(data))+        }+    }++    func receive() async throws -> WebSocketMessage {+        await stream.first(where: { _ in true }) ?? .data(Data())+    } }  final class AsyncHTTPClientFactory: HTTPClientFactory {@@ -82,7 +147,7 @@ final class AsyncHTTPClientFactory: HTTPClientFactory {             tlsConfiguration: tlsConfiguration,             decompression: .enabled(limit: .none)         )-        client = HTTPClient(eventLoopGroupProvider: .createNew, configuration: config)+        client = HTTPClient(configuration: config)     }     static let shared = AsyncHTTPClientFactory() 
Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swiftindex 0da91ee..a9c702a 100644--- a/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift@@ -52,6 +52,18 @@ public struct HTTPResponse {  public protocol HTTPClientProtocol {     func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse+    func makeWebSocket(url: URL) async throws -> WebSocketSession+}++public protocol WebSocketSession {+    func receive() async throws -> WebSocketMessage+    func send(_ message: WebSocketMessage) async throws+    func close()+}++public enum WebSocketMessage {+    case text(String)+    case data(Data) }  public protocol HTTPClientFactory {
Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swiftindex 325284f..ab2e4d3 100644--- a/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift@@ -10,7 +10,47 @@ import Foundation  public struct UnknownHTTPError: Error {} -extension URLSession: HTTPClientProtocol {+final class URLHTTPClientFactory: HTTPClientFactory {+    static let shared = URLHTTPClientFactory()++    private let client = Client()++    func shutdown() {}+    func makeClient() -> HTTPClientProtocol { client }+}++private final class Client: HTTPClientProtocol {+    final class WebSocketDelegate: NSObject, URLSessionWebSocketDelegate {+        var callbacks: [URLSessionWebSocketTask: (URLSessionWebSocketTask.CloseCode?) -> Void] = [:]++        func urlSession(+            _ session: URLSession,+            webSocketTask: URLSessionWebSocketTask,+            didOpenWithProtocol protocol: String?+        ) {+            callbacks.removeValue(forKey: webSocketTask)?(nil)+        }++        func urlSession(+            _ session: URLSession,+            webSocketTask: URLSessionWebSocketTask,+            didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,+            reason: Data?+        ) {+            callbacks.removeValue(forKey: webSocketTask)?(closeCode)+        }+    }++    private let webSocketDelegate = WebSocketDelegate()+    private let session: URLSession++    init() {+        // no need for cert handling since the Apple Root CA is already+        // installed on any devices which support the Security APIs which+        // would have been required to add the custom root anyway+        self.session = URLSession(configuration: .ephemeral, delegate: webSocketDelegate, delegateQueue: .main)+    }+     public func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse {         var req = URLRequest(url: request.url)         req.httpMethod = request.method@@ -25,7 +65,7 @@ extension URLSession: HTTPClientProtocol {         case nil:             break         }-        let (data, resp) = try await data(for: req)+        let (data, resp) = try await session.data(for: req)         guard let httpResp = resp as? HTTPURLResponse else { throw UnknownHTTPError() }         let headers = [String: String](             uniqueKeysWithValues: httpResp.allHeaderFields.compactMap { k, v in@@ -42,18 +82,48 @@ extension URLSession: HTTPClientProtocol {             body: data         )     }++    public func makeWebSocket(url: URL) async throws -> any WebSocketSession {+        let task = session.webSocketTask(with: url)+        async let event = withCheckedContinuation { continuation in+            webSocketDelegate.callbacks[task] = { continuation.resume(returning: $0) }+        }+        task.resume()+        let code = await event+        if let code { throw Errors.webSocketClosed(code) }+        return WebSocketSessionWrapper(task: task)+    }++    enum Errors: Error {+        case webSocketClosed(URLSessionWebSocketTask.CloseCode)+    } } -final class URLHTTPClientFactory: HTTPClientFactory {-    static let shared = URLHTTPClientFactory()+private final class WebSocketSessionWrapper: WebSocketSession {+    let task: URLSessionWebSocketTask++    init(task: URLSessionWebSocketTask) {+        self.task = task+    } -    // no need for cert handling since the Apple Root CA is already-    // installed on any devices which support the Security APIs which-    // would have been required to add the custom root anyway-    private let session = URLSession(configuration: .ephemeral)-    private init() {}+    func receive() async throws -> WebSocketMessage {+        switch try await task.receive() {+        case .data(let data): .data(data)+        case .string(let text): .text(text)+        @unknown default: .data(Data())+        }+    } -    func shutdown() {}-    func makeClient() -> HTTPClientProtocol { session }+    func send(_ message: WebSocketMessage) async throws {+        let message: URLSessionWebSocketTask.Message = switch message {+        case .data(let data): .data(data)+        case .text(let text): .string(text)+        }+        try await task.send(message)+    }++    func close() {+        task.cancel(with: .normalClosure, reason: nil)+    } } #endif