(options: ProxyOptions)
| 70 | } |
| 71 | |
| 72 | export function createHttpProxy(options: ProxyOptions) { |
| 73 | const backendHost = options.backendHost ?? '127.0.0.1'; |
| 74 | const backendPort = options.backendPort ?? 3001; |
| 75 | |
| 76 | return async (c: Context): Promise<Response> => { |
| 77 | const token = c.req.header('x-kiloclaw-proxy-token'); |
| 78 | if (!hasValidProxyToken(token, options.requireProxyToken, options.expectedToken)) { |
| 79 | const isUnknownControllerRoute = c.req.path.startsWith('/_kilo/'); |
| 80 | return c.json( |
| 81 | isUnknownControllerRoute |
| 82 | ? { code: 'controller_route_unavailable', error: 'Unauthorized' } |
| 83 | : { error: 'Unauthorized' }, |
| 84 | 401 |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | if (options.supervisor && options.supervisor.getState() !== 'running') { |
| 89 | return c.json( |
| 90 | { error: 'Gateway not ready' }, |
| 91 | { status: 503, headers: { 'Retry-After': '5' } } |
| 92 | ); |
| 93 | } |
| 94 | |
| 95 | const incomingUrl = new URL(c.req.url); |
| 96 | const method = c.req.method.toUpperCase(); |
| 97 | |
| 98 | const headers = new Headers(c.req.raw.headers); |
| 99 | headers.delete('x-kiloclaw-proxy-token'); |
| 100 | headers.set('host', `${backendHost}:${backendPort}`); |
| 101 | |
| 102 | // Stream the request body through http.request + stream.pipeline so we |
| 103 | // never buffer uploads or large plugin payloads. Mirrors the WS-upgrade |
| 104 | // path's use of http.request for raw Node stream control. |
| 105 | return await new Promise<Response>(resolve => { |
| 106 | const upstreamReq = http.request({ |
| 107 | hostname: backendHost, |
| 108 | port: backendPort, |
| 109 | path: `${incomingUrl.pathname}${incomingUrl.search}`, |
| 110 | method, |
| 111 | headers: headersToOutgoing(headers), |
| 112 | }); |
| 113 | |
| 114 | let settled = false; |
| 115 | const settle = (response: Response): void => { |
| 116 | if (settled) return; |
| 117 | settled = true; |
| 118 | resolve(response); |
| 119 | }; |
| 120 | const fail = (error: unknown): void => { |
| 121 | console.error('[controller] HTTP proxy backend error:', error); |
| 122 | settle( |
| 123 | new Response(JSON.stringify({ error: 'Bad Gateway' }), { |
| 124 | status: 502, |
| 125 | headers: { 'content-type': 'application/json' }, |
| 126 | }) |
| 127 | ); |
| 128 | }; |
| 129 |
no test coverage detected