From 4d661c073cd775d30ddb7ee40bd3aa7f232ae347 Mon Sep 17 00:00:00 2001 From: CyberL1 Date: Tue, 7 Jan 2025 12:12:57 -0500 Subject: [PATCH] feat proxy --- .env.example | 3 +++ src/index.ts | 1 + src/proxy.ts | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 src/proxy.ts diff --git a/.env.example b/.env.example index 7c767a3..96f1397 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,5 @@ PORT=3000 HOST="0.0.0.0" + +PROXY_DOMAIN="localhost" +PROXY_PORT=3001 diff --git a/src/index.ts b/src/index.ts index a933196..900116b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import "dotenv/config"; import fastify from "fastify"; import { readdirSync } from "fs"; +import "./proxy.ts"; const app = fastify(); diff --git a/src/proxy.ts b/src/proxy.ts new file mode 100644 index 0000000..bea8ed0 --- /dev/null +++ b/src/proxy.ts @@ -0,0 +1,39 @@ +import fastify from "fastify"; +import { getContainer } from "./utils/containers.ts"; + +const app = fastify(); + +app.all( + "/*", + { constraints: { host: new RegExp(`.*\.${process.env.PROXY_DOMAIN}`) } }, + async (req) => { + const subdomains = req.headers.host.split("."); + + const port = subdomains[0].startsWith("port-") + ? subdomains[0].slice(5) + : 80; + + const containerName = subdomains[subdomains[0].startsWith("port-") ? 1 : 0]; + + const { NetworkSettings } = await getContainer(containerName).inspect(); + const { IPAddress: ip } = NetworkSettings; + + const proxyRequest = await fetch(`http://${ip}:${port}${req.url}`, { + headers: req.headers, + method: req.method, + }); + + const proxyResponse = await proxyRequest.text(); + return proxyResponse; + }, +); + +await app.listen({ + port: Number(process.env.PROXY_PORT), + host: process.env.HOST, +}); + +console.log( + "Proxy ready on", + `http://${process.env.HOST}:${Number(process.env.PROXY_PORT)}`, +);