| const express = require("express"); |
| const { createProxyMiddleware } = require("http-proxy-middleware"); |
| const http = require("http"); |
|
|
| const app = express(); |
| const server = http.createServer(app); |
|
|
| |
| const activePorts = new Set(["5000"]); |
|
|
| |
| function makeProxy(port, wsOnly = false) { |
| return createProxyMiddleware({ |
| target: `http://127.0.0.1:${port}`, |
| changeOrigin: true, |
| ws: true, |
| pathRewrite: { [`^/s${port}`]: "" }, |
| logLevel: "warn", |
| |
| onProxyReq: (proxyReq, req, res) => { |
| if (wsOnly && req.method !== "GET" && req.headers.upgrade !== "websocket") { |
| res.writeHead(400, { "Content-Type": "text/plain" }); |
| res.end("Somente conexões WebSocket são aceitas nesta rota"); |
| } |
| } |
| }); |
| } |
|
|
| |
| app.use("/s8000", (req, res, next) => { |
| res.status(400).send("Use WebSocket (wss://) nesta rota"); |
| }); |
| app.use("/s8080", (req, res, next) => { |
| res.status(400).send("Use WebSocket (wss://) nesta rota"); |
| }); |
|
|
| |
| app.use("/s:port", (req, res, next) => { |
| const port = req.params.port; |
| if (!/^\d+$/.test(port)) { |
| return res.status(400).send("Porta inválida"); |
| } |
| if (port === "8000" || port === "8080") { |
| return res.status(400).send("Esta porta aceita apenas WebSocket (wss://)"); |
| } |
| activePorts.add(port); |
| return makeProxy(port)(req, res, next); |
| }); |
|
|
| |
| app.get("/", (req, res) => { |
| const list = Array.from(activePorts) |
| .concat(["8000 (WS only)", "8080 (WS only)"]) |
| .map(p => `<li><a href="/s${p.replace(' (WS only)','')}" target="_blank">/s${p}</a></li>`) |
| .join(""); |
| res.send(`<h1>Portas ativas</h1><ul>${list}</ul>`); |
| }); |
|
|
| |
| server.on("upgrade", (req, socket, head) => { |
| const url = req.url || ""; |
| const match = url.match(/^\/s(\d+)/); |
| if (match) { |
| const port = match[1]; |
| if (port === "8000" || port === "8080") { |
| console.log(`Conexão WebSocket em /s${port}`); |
| makeProxy(port, true).upgrade(req, socket, head); |
| } else { |
| activePorts.add(port); |
| console.log(`Conexão WebSocket em /s${port}`); |
| makeProxy(port).upgrade(req, socket, head); |
| } |
| } else { |
| socket.destroy(); |
| } |
| }); |
|
|
| server.listen(7860, "0.0.0.0", () => { |
| console.log("Proxy ativo em http://localhost:7860"); |
| console.log("Portas WS dedicadas: 8000, 8080"); |
| }); |
|
|