feat: publish generic Telegram WEB proxy stack
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Proxy Edge</title><style>body{margin:0;background:#0b1220;color:#dce7f7;font:16px system-ui,sans-serif}main{max-width:720px;margin:16vh auto;padding:32px}h1{font-size:42px;margin:0 0 12px;color:#fff}p{line-height:1.6;color:#9eb2cc}.badge{display:inline-block;padding:6px 10px;border:1px solid #274262;border-radius:999px;color:#86b7ea;font-size:13px}</style></head><body><main><span class="badge">Proxy Edge</span><h1>Private edge transport</h1><p>This endpoint provides resilient transport and availability services for authorized clients.</p></main></body></html>`
|
||||
|
||||
func requestHostname(hostport string) string {
|
||||
host := strings.TrimSpace(hostport)
|
||||
if parsed, _, err := net.SplitHostPort(host); err == nil {
|
||||
return strings.ToLower(parsed)
|
||||
}
|
||||
return strings.ToLower(strings.Trim(host, "[]"))
|
||||
}
|
||||
|
||||
func main() {
|
||||
hostname := strings.ToLower(strings.TrimSpace(os.Getenv("TPROXY_HOSTNAME")))
|
||||
if hostname == "" {
|
||||
log.Fatal("TPROXY_HOSTNAME is required")
|
||||
}
|
||||
|
||||
target, err := url.Parse("http://127.0.0.1:8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
proxy := &httputil.ReverseProxy{
|
||||
Rewrite: func(request *httputil.ProxyRequest) {
|
||||
request.SetURL(target)
|
||||
request.Out.Host = request.In.Host
|
||||
|
||||
clientIP := strings.TrimSpace(request.In.Header.Get("X-Real-IP"))
|
||||
if net.ParseIP(clientIP) == nil {
|
||||
clientIP, _, _ = net.SplitHostPort(request.In.RemoteAddr)
|
||||
}
|
||||
request.Out.Header.Set("X-Real-IP", clientIP)
|
||||
request.Out.Header.Set("X-Forwarded-For", clientIP)
|
||||
if proto := request.In.Header.Get("X-Forwarded-Proto"); proto != "" {
|
||||
request.Out.Header.Set("X-Forwarded-Proto", proto)
|
||||
}
|
||||
},
|
||||
ErrorHandler: func(response http.ResponseWriter, _ *http.Request, proxyErr error) {
|
||||
log.Printf("relay error: %v", proxyErr)
|
||||
http.Error(response, "upstream unavailable", http.StatusBadGateway)
|
||||
},
|
||||
}
|
||||
|
||||
handler := http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
if requestHostname(request.Host) != hostname {
|
||||
http.Error(response, "misdirected request", http.StatusMisdirectedRequest)
|
||||
return
|
||||
}
|
||||
|
||||
response.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
response.Header().Set("Referrer-Policy", "no-referrer")
|
||||
|
||||
staticPath := request.URL.Path == "/" ||
|
||||
request.URL.Path == "/about" ||
|
||||
request.URL.Path == "/privacy"
|
||||
if request.Method == http.MethodGet && request.URL.RawQuery == "" && staticPath {
|
||||
response.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
response.Header().Set("Cache-Control", "public, max-age=300")
|
||||
_, _ = fmt.Fprint(response, page)
|
||||
return
|
||||
}
|
||||
|
||||
proxy.ServeHTTP(response, request)
|
||||
})
|
||||
|
||||
server := &http.Server{
|
||||
Addr: ":8088",
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 90 * time.Second,
|
||||
}
|
||||
|
||||
log.Printf("ingress listening on %s for %s", server.Addr, hostname)
|
||||
log.Fatal(server.ListenAndServe())
|
||||
}
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const http = require('http');
|
||||
const net = require('net');
|
||||
|
||||
const expectedHostname = (process.env.TPROXY_HOSTNAME || '').toLowerCase();
|
||||
const upstreamHost = '127.0.0.1';
|
||||
const upstreamPort = 8080;
|
||||
const listenPort = 8088;
|
||||
|
||||
const page = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Proxy Edge</title><style>body{margin:0;background:#0b1220;color:#dce7f7;font:16px system-ui,sans-serif}main{max-width:720px;margin:16vh auto;padding:32px}h1{font-size:42px;margin:0 0 12px;color:#fff}p{line-height:1.6;color:#9eb2cc}.badge{display:inline-block;padding:6px 10px;border:1px solid #274262;border-radius:999px;color:#86b7ea;font-size:13px}</style></head><body><main><span class="badge">Proxy Edge</span><h1>Private edge transport</h1><p>This endpoint provides resilient transport and availability services for authorized clients.</p></main></body></html>';
|
||||
|
||||
function requestHostname(req) {
|
||||
return (req.headers.host || '').split(':', 1)[0].toLowerCase();
|
||||
}
|
||||
|
||||
function acceptHost(req) {
|
||||
return expectedHostname !== '' && requestHostname(req) === expectedHostname;
|
||||
}
|
||||
|
||||
function failMisdirected(response) {
|
||||
response.writeHead(421, {
|
||||
'content-type': 'text/plain; charset=utf-8',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'referrer-policy': 'no-referrer',
|
||||
});
|
||||
response.end('misdirected request\n');
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (!acceptHost(req)) {
|
||||
failMisdirected(res);
|
||||
return;
|
||||
}
|
||||
|
||||
const requestUrl = new URL(req.url, 'http://localhost');
|
||||
const staticPath =
|
||||
requestUrl.pathname === '/' ||
|
||||
requestUrl.pathname === '/about' ||
|
||||
requestUrl.pathname === '/privacy';
|
||||
|
||||
if (req.method === 'GET' && staticPath && requestUrl.search === '') {
|
||||
res.writeHead(200, {
|
||||
'content-type': 'text/html; charset=utf-8',
|
||||
'cache-control': 'public, max-age=300',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'referrer-policy': 'no-referrer',
|
||||
});
|
||||
res.end(page);
|
||||
return;
|
||||
}
|
||||
|
||||
const upstream = http.request(
|
||||
{
|
||||
host: upstreamHost,
|
||||
port: upstreamPort,
|
||||
method: req.method,
|
||||
path: req.url,
|
||||
headers: req.headers,
|
||||
},
|
||||
(upstreamResponse) => {
|
||||
const headers = { ...upstreamResponse.headers };
|
||||
headers['x-content-type-options'] = 'nosniff';
|
||||
headers['referrer-policy'] = 'no-referrer';
|
||||
res.writeHead(upstreamResponse.statusCode || 502, headers);
|
||||
upstreamResponse.pipe(res);
|
||||
},
|
||||
);
|
||||
|
||||
upstream.on('error', (error) => {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
||||
}
|
||||
res.end('upstream unavailable\n');
|
||||
console.error(`relay error: ${error.message}`);
|
||||
});
|
||||
req.pipe(upstream);
|
||||
});
|
||||
|
||||
server.on('upgrade', (req, clientSocket, head) => {
|
||||
if (!acceptHost(req)) {
|
||||
clientSocket.end(
|
||||
'HTTP/1.1 421 Misdirected Request\r\nConnection: close\r\n\r\n',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const upstreamSocket = net.connect(upstreamPort, upstreamHost, () => {
|
||||
let requestHead = `${req.method} ${req.url} HTTP/${req.httpVersion}\r\n`;
|
||||
for (let index = 0; index < req.rawHeaders.length; index += 2) {
|
||||
requestHead += `${req.rawHeaders[index]}: ${req.rawHeaders[index + 1]}\r\n`;
|
||||
}
|
||||
upstreamSocket.write(`${requestHead}\r\n`);
|
||||
if (head.length > 0) upstreamSocket.write(head);
|
||||
upstreamSocket.pipe(clientSocket);
|
||||
clientSocket.pipe(upstreamSocket);
|
||||
});
|
||||
|
||||
upstreamSocket.on('error', () => clientSocket.destroy());
|
||||
clientSocket.on('error', () => upstreamSocket.destroy());
|
||||
});
|
||||
|
||||
server.headersTimeout = 10_000;
|
||||
server.keepAliveTimeout = 90_000;
|
||||
server.listen(listenPort, '0.0.0.0', () => {
|
||||
console.log(`ingress listening on :${listenPort} for ${expectedHostname}`);
|
||||
});
|
||||
Reference in New Issue
Block a user