SPB Git

Repository Public

HookServer.swift 6.1 KB 141 lines swift

1import Foundation2import Network34/// Minimal HTTP/1.1 receiver bound to 127.0.0.1 on an ephemeral port. Accepts only POSTs that carry5/// the bearer token, parses the JSON body as a `HookEvent`, and always answers 200 with an empty body6/// (so Claude Code proceeds exactly as if no hook existed — NEXTERM observes, it never decides).7public final class HookServer: @unchecked Sendable {8    public typealias Handler = @Sendable (HookEvent) -> Void910    private let listener: NWListener11    private let queue = DispatchQueue(label: "ai.spboucher.nexterm.hooks")12    private let token: String13    private let handler: Handler14    private let maxBody = 2 * 1024 * 102415    private let lock = NSLock()16    private var _port: UInt16?17    private var connections: Set<ObjectIdentifier> = []1819    public var port: UInt16? { lock.withLock { _port } }20    public var url: String? { port.map { "http://127.0.0.1:\($0)/hook" } }2122    public init(token: String, handler: @escaping Handler) throws {23        self.token = token24        self.handler = handler25        let params = NWParameters.tcp26        params.allowLocalEndpointReuse = true27        params.requiredInterfaceType = .loopback28        params.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any)29        listener = try NWListener(using: params)30    }3132    /// Starts listening; resolves once a port is bound.33    public func start() async throws {34        try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in35            let once = OnceContinuation(cont)36            listener.stateUpdateHandler = { [weak self] state in37                guard let self else { return }38                switch state {39                case .ready:40                    self.lock.withLock { self._port = self.listener.port?.rawValue }41                    once.resume(nil)42                case .failed(let error):43                    once.resume(error)44                default: break45                }46            }47            listener.newConnectionHandler = { [weak self] connection in self?.accept(connection) }48            listener.start(queue: queue)49        }50    }5152    public func stop() {53        listener.cancel()54    }5556    private func accept(_ connection: NWConnection) {57        connection.start(queue: queue)58        var buffer = Data()59        func readMore() {60            connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { [weak self] data, _, isComplete, error in61                guard let self else { return }62                if let data { buffer.append(data) }63                if buffer.count > self.maxBody + 8192 { self.respond(connection, status: "413 Payload Too Large"); return }64                if let request = HTTPRequestParser.parse(buffer) {65                    self.handle(request, on: connection)66                } else if isComplete || error != nil {67                    self.respond(connection, status: "400 Bad Request")68                } else {69                    readMore()70                }71            }72        }73        readMore()74    }7576    private func handle(_ request: HTTPRequestParser.Request, on connection: NWConnection) {77        guard request.method == "POST", request.path == "/hook" else { respond(connection, status: "404 Not Found"); return }78        let auth = request.headers["authorization"] ?? ""79        guard constantTimeEquals(auth, "Bearer \(token)") else { respond(connection, status: "401 Unauthorized"); return }80        if let event = try? HookEvent(json: request.body) {81            handler(event)82            respond(connection, status: "200 OK")83        } else {84            respond(connection, status: "400 Bad Request")85        }86    }8788    private func respond(_ connection: NWConnection, status: String) {89        let response = "HTTP/1.1 \(status)\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"90        connection.send(content: Data(response.utf8), completion: .contentProcessed { _ in connection.cancel() })91    }9293    private func constantTimeEquals(_ a: String, _ b: String) -> Bool {94        let x = Array(a.utf8), y = Array(b.utf8)95        guard x.count == y.count else { return false }96        var diff: UInt8 = 097        for i in 0..<x.count { diff |= x[i] ^ y[i] }98        return diff == 099    }100}101102/// Just enough HTTP/1.1 parsing for a local hook POST. Returns nil until the full body has arrived.103public enum HTTPRequestParser {104    public struct Request: Sendable {105        public let method: String106        public let path: String107        public let headers: [String: String]108        public let body: Data109    }110111    public static func parse(_ data: Data) -> Request? {112        guard let headerEnd = data.range(of: Data("\r\n\r\n".utf8)) else { return nil }113        let head = String(decoding: data[data.startIndex..<headerEnd.lowerBound], as: UTF8.self)114        var lines = head.components(separatedBy: "\r\n")115        guard !lines.isEmpty else { return nil }116        let requestLine = lines.removeFirst().split(separator: " ")117        guard requestLine.count >= 2 else { return nil }118        var headers: [String: String] = [:]119        for line in lines {120            guard let colon = line.firstIndex(of: ":") else { continue }121            headers[line[..<colon].lowercased()] = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)122        }123        let length = Int(headers["content-length"] ?? "0") ?? 0124        let bodyStart = headerEnd.upperBound125        guard data.count - (bodyStart - data.startIndex) >= length else { return nil }126        let body = data[bodyStart..<bodyStart + length]127        return Request(method: String(requestLine[0]), path: String(requestLine[1]).split(separator: "?").first.map(String.init) ?? "/", headers: headers, body: Data(body))128    }129}130131/// Resumes a continuation at most once (NWListener may report several states).132private final class OnceContinuation: @unchecked Sendable {133    private var cont: CheckedContinuation<Void, Error>?134    private let lock = NSLock()135    init(_ c: CheckedContinuation<Void, Error>) { cont = c }136    func resume(_ error: Error?) {137        lock.lock(); let c = cont; cont = nil; lock.unlock()138        if let error { c?.resume(throwing: error) } else { c?.resume() }139    }140}141
Files main
Menu

Theme