MCPcopy Create free account
hub / github.com/Kilo-Org/cloud / createHttpProxy

Function createHttpProxy

services/kiloclaw/controller/src/proxy.ts:72–188  ·  view source on GitHub ↗
(options: ProxyOptions)

Source from the content-addressed store, hash-verified

70}
71
72export 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

Callers 2

startControllerFunction · 0.90
proxy.test.tsFile · 0.90

Calls 14

hasValidProxyTokenFunction · 0.85
headersToOutgoingFunction · 0.85
settleFunction · 0.70
failFunction · 0.70
jsonMethod · 0.65
deleteMethod · 0.65
setMethod · 0.65
errorMethod · 0.65
endMethod · 0.65
destroyMethod · 0.65
getStateMethod · 0.45

Tested by

no test coverage detected