( req: IncomingMessage, socket: Duplex, head: Buffer, options: ProxyOptions )
| 210 | } |
| 211 | |
| 212 | export function handleWebSocketUpgrade( |
| 213 | req: IncomingMessage, |
| 214 | socket: Duplex, |
| 215 | head: Buffer, |
| 216 | options: ProxyOptions |
| 217 | ): void { |
| 218 | const backendHost = options.backendHost ?? '127.0.0.1'; |
| 219 | const backendPort = options.backendPort ?? 3001; |
| 220 | const wsIdleTimeoutMs = options.wsIdleTimeoutMs ?? DEFAULT_WS_IDLE_TIMEOUT_MS; |
| 221 | const wsHandshakeTimeoutMs = options.wsHandshakeTimeoutMs ?? DEFAULT_WS_HANDSHAKE_TIMEOUT_MS; |
| 222 | const maxWsConnections = options.maxWsConnections ?? DEFAULT_MAX_WS_CONNS; |
| 223 | const wsState = options.wsState ?? { activeConnections: 0 }; |
| 224 | |
| 225 | const token = getHeaderToken(req.headers['x-kiloclaw-proxy-token']); |
| 226 | |
| 227 | if (!hasValidProxyToken(token, options.requireProxyToken, options.expectedToken)) { |
| 228 | socketWriteUnauthorized(socket); |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | if (options.supervisor && options.supervisor.getState() !== 'running') { |
| 233 | socketWriteServiceUnavailable(socket); |
| 234 | return; |
| 235 | } |
| 236 | if (wsState.activeConnections >= maxWsConnections) { |
| 237 | socketWriteServiceUnavailable(socket); |
| 238 | return; |
| 239 | } |
| 240 | |
| 241 | wsState.activeConnections += 1; |
| 242 | let releasedConnection = false; |
| 243 | const releaseConnection = () => { |
| 244 | if (releasedConnection) return; |
| 245 | releasedConnection = true; |
| 246 | wsState.activeConnections = Math.max(0, wsState.activeConnections - 1); |
| 247 | }; |
| 248 | |
| 249 | const forwardedHeaders = { ...req.headers }; |
| 250 | delete forwardedHeaders['x-kiloclaw-proxy-token']; |
| 251 | // Rewrite Host so the gateway sees a loopback origin (matching the HTTP proxy path). |
| 252 | // Strip proxy/forwarding headers injected by upstream proxies (Fly, CF) so the gateway's |
| 253 | // isLocalDirectRequest check doesn't conclude the request came from a remote client. |
| 254 | forwardedHeaders['host'] = `${backendHost}:${backendPort}`; |
| 255 | delete forwardedHeaders['forwarded']; |
| 256 | delete forwardedHeaders['x-real-ip']; |
| 257 | for (const headerName of Object.keys(forwardedHeaders)) { |
| 258 | if (headerName.toLowerCase().startsWith('x-forwarded-')) { |
| 259 | delete forwardedHeaders[headerName]; |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | const backendReq = http.request({ |
| 264 | hostname: backendHost, |
| 265 | port: backendPort, |
| 266 | path: req.url, |
| 267 | method: req.method, |
| 268 | headers: forwardedHeaders, |
| 269 | }); |
no test coverage detected