Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / LoopbackOAuth.swift
| 1 | import AppKit |
| 2 | import Network |
| 3 | |
| 4 | @MainActor |
| 5 | final class LoopbackOAuth { |
| 6 | private let callback: URL |
| 7 | private let state: String |
| 8 | private var listener: NWListener? |
| 9 | private var continuation: CheckedContinuation<URL, Error>? |
| 10 | private var timeout: Task<Void, Never>? |
| 11 | private var connections: [ObjectIdentifier: NWConnection] = [:] |
| 12 | private var completing = false |
| 13 | |
| 14 | init(callback: URL, state: String) { |
| 15 | self.callback = callback |
| 16 | self.state = state |
| 17 | } |
| 18 | |
| 19 | func wait(opening url: URL) async throws -> URL { |
| 20 | try await withCheckedThrowingContinuation { continuation in |
| 21 | let parameters = NWParameters.tcp |
| 22 | parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: 43821) |
| 23 | do { |
| 24 | let listener = try NWListener(using: parameters) |
| 25 | self.listener = listener |
| 26 | self.continuation = continuation |
| 27 | listener.stateUpdateHandler = { [weak self] state in |
| 28 | Task { @MainActor in |
| 29 | guard let self else { return } |
| 30 | switch state { |
| 31 | case .ready: |
| 32 | if !NSWorkspace.shared.open(url) { self.finish(.failure(WorkspaceError("Couldn’t open the browser."))) } |
| 33 | case .failed: |
| 34 | self.finish(.failure(WorkspaceError("The local sign-in port is unavailable. Finish any other Inkspring sign-in and try again."))) |
| 35 | default: break |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | listener.newConnectionHandler = { [weak self] connection in |
| 40 | Task { @MainActor in self?.accept(connection) } |
| 41 | } |
| 42 | listener.start(queue: .main) |
| 43 | timeout = Task { @MainActor in |
| 44 | try? await Task.sleep(for: .seconds(600)) |
| 45 | if !Task.isCancelled { self.finish(.failure(WorkspaceError("Sign-in timed out. Connect again."))) } |
| 46 | } |
| 47 | } catch { |
| 48 | continuation.resume(throwing: WorkspaceError("Couldn’t open the local sign-in callback.")) |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func cancel() { finish(.failure(CancellationError())) } |
| 54 | |
| 55 | private func accept(_ connection: NWConnection) { |
| 56 | guard continuation != nil, !completing, connections.count < 8 else { connection.cancel(); return } |
| 57 | connections[ObjectIdentifier(connection)] = connection |
| 58 | connection.start(queue: .main) |
| 59 | receive(connection, bytes: Data()) |
| 60 | } |
| 61 | |
| 62 | private func receive(_ connection: NWConnection, bytes: Data) { |
| 63 | connection.receive(minimumIncompleteLength: 1, maximumLength: 16_384) { [weak self] data, _, done, error in |
| 64 | Task { @MainActor in |
| 65 | guard let self else { connection.cancel(); return } |
| 66 | var received = bytes |
| 67 | if let data { received.append(data) } |
| 68 | if received.count > 16_384 || error != nil { |
| 69 | self.reply(connection, callback: nil) |
| 70 | } else if let end = received.range(of: Data("\r\n\r\n".utf8)) { |
| 71 | let headers = String(decoding: received[..<end.lowerBound], as: UTF8.self) |
| 72 | self.reply(connection, callback: self.parse(headers)) |
| 73 | } else if done { |
| 74 | self.reply(connection, callback: nil) |
| 75 | } else { |
| 76 | self.receive(connection, bytes: received) |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func parse(_ headers: String) -> URL? { |
| 83 | let lines = headers.components(separatedBy: "\r\n") |
| 84 | let request = lines.first?.split(separator: " ") ?? [] |
| 85 | guard request.count == 3, request[0] == "GET", ["HTTP/1.0", "HTTP/1.1"].contains(request[2]), |
| 86 | request[1].hasPrefix("/oauth/"), |
| 87 | let url = URL(string: "http://127.0.0.1:43821" + request[1]), url.path == callback.path, |
| 88 | url.fragment == nil, |
| 89 | URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.filter({ $0.name == "state" }).map(\.value) == [state] else { return nil } |
| 90 | let fields = lines.dropFirst().map { $0.split(separator: ":", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) } } |
| 91 | let hosts = fields.filter { $0.first?.lowercased() == "host" } |
| 92 | guard hosts.count == 1, hosts[0].count == 2, hosts[0][1] == "127.0.0.1:43821", |
| 93 | !fields.contains(where: { $0.first?.lowercased() == "origin" }) else { return nil } |
| 94 | return url |
| 95 | } |
| 96 | |
| 97 | private func reply(_ connection: NWConnection, callback: URL?) { |
| 98 | let accepted = callback != nil && !completing |
| 99 | if accepted { completing = true } |
| 100 | let status = accepted ? "200 OK" : "400 Bad Request" |
| 101 | let page = accepted ? "Return to Inkspring to finish connecting." : "The sign-in return was not accepted." |
| 102 | let body = "<!doctype html><title>Inkspring</title><p>" + page + "</p>" |
| 103 | let response = "HTTP/1.1 \(status)\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \(body.utf8.count)\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nConnection: close\r\n\r\n\(body)" |
| 104 | connection.send(content: Data(response.utf8), completion: .contentProcessed { [weak self] _ in |
| 105 | Task { @MainActor in |
| 106 | connection.cancel() |
| 107 | self?.connections.removeValue(forKey: ObjectIdentifier(connection)) |
| 108 | if accepted, let callback { self?.finish(.success(callback)) } |
| 109 | } |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | private func finish(_ result: Result<URL, Error>) { |
| 114 | timeout?.cancel() |
| 115 | timeout = nil |
| 116 | listener?.cancel() |
| 117 | listener = nil |
| 118 | for connection in connections.values { connection.cancel() } |
| 119 | connections.removeAll() |
| 120 | let continuation = continuation |
| 121 | self.continuation = nil |
| 122 | continuation?.resume(with: result) |
| 123 | } |
| 124 | } |