You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.5 KiB
TypeScript

const BOT_ORIGIN = 'http://127.0.0.1:3007';
const WEB_ORIGIN = 'http://127.0.0.1:3008';
function shouldRouteToBot(pathname: string): boolean {
if (pathname === '/metrics' || pathname.startsWith('/metrics/')) return true;
if (pathname === '/webhook' || pathname.startsWith('/webhook/')) return true;
return false;
}
function buildForwardHeaders(req: Request): Headers {
const headers = new Headers(req.headers);
try {
const proto = headers.get('x-forwarded-proto') || 'https';
const fwdFor = headers.get('x-forwarded-for');
headers.set('x-forwarded-proto', proto);
headers.set('x-forwarded-for', fwdFor ? `${fwdFor}, 127.0.0.1` : '127.0.0.1');
} catch {}
return headers;
}
Bun.serve({
port: Number(process.env.PORT || process.env.ROUTER_PORT || 3000),
fetch: async (req) => {
const url = new URL(req.url);
const targetOrigin = shouldRouteToBot(url.pathname) ? BOT_ORIGIN : WEB_ORIGIN;
const targetUrl = targetOrigin + url.pathname + url.search;
const init: RequestInit = {
method: req.method,
headers: buildForwardHeaders(req),
body: req.method === 'GET' || req.method === 'HEAD' ? undefined : req.body,
redirect: 'manual',
};
try {
const res = await fetch(targetUrl, init);
// Devuelve la respuesta tal cual (incluye Set-Cookie, Location, etc.)
return res;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return new Response(`Proxy error: ${msg}\n`, { status: 502 });
}
},
});