// Cotton chat's socket on the person's own object, opened by the app because // only URLSession's WebSocket lives on an iPhone: the address and a ticket the // core hands in `chat.socket`'s answer, opened as given. The core asked the // object for the ticket on its own door (signed, in Rust); the object minted // it for this one socket (`cts__`, spent by opening it, // dead after a minute) and checks it as the Bearer, never in the URL. It is no // credential of this app's and opens nothing else (`apps/business/src/chat/chat.ts`). import CottonKit import Foundation /// `URLSessionWebSocketTask`, the ticket the Bearer the object checks. @MainActor public final class WebSocketChatSocket: ChatSocketPort { private let session: URLSession private var task: URLSessionWebSocketTask? private let log: @Sendable (String) -> Void public init(session: URLSession = .shared, log: @escaping @Sendable (String) -> Void = { _ in }) { self.session = session self.log = log } public func open(url: URL, ticket: String, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) { close() var request = URLRequest(url: url) request.setValue("Bearer \(ticket)", forHTTPHeaderField: "Authorization") let task = session.webSocketTask(with: request) self.task = task task.resume() listen(task, received: received, closed: closed) } public func send(_ frame: JSONValue) { guard let task, let data = try? JSONEncoder().encode(frame) else { return } task.send(.string(String(decoding: data, as: UTF8.self))) { [log] error in if let error { log("chat socket: a send failed: \(error.localizedDescription)") } } } public func close() { task?.cancel(with: .normalClosure, reason: nil) task = nil } private func listen(_ task: URLSessionWebSocketTask, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) { task.receive { [weak self] result in Task { @MainActor in guard let self, self.task === task else { return } switch result { case .success(let message): let data: Data? = switch message { case .string(let text): Data(text.utf8) case .data(let data): data @unknown default: nil } if let data, let frame = try? JSONDecoder().decode(JSONValue.self, from: data) { received(frame) } self.listen(task, received: received, closed: closed) case .failure(let error): self.log("chat socket: closed: \(error.localizedDescription)") self.task = nil closed() } } } } }