Spaces:
Running
Running
Download backend/internal/proxy/proxy.go from Shadowfilebot/Bot: direct link, hf CLI and curl.
- Browser
- Download file 9.75 kB
-
https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/backend/internal/proxy/proxy.go
- Command line
-
hf download hf://spaces/Shadowfilebot/Bot/backend/internal/proxy/proxy.go
-
curl -L -o proxy.go https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/backend/internal/proxy/proxy.go
9.75 kB
| package proxy | |
| import ( | |
| "context" | |
| "errors" | |
| "fmt" | |
| "net" | |
| "net/http" | |
| "net/http/httputil" | |
| "net/url" | |
| "os" | |
| "regexp" | |
| "strconv" | |
| "strings" | |
| "sync" | |
| "time" | |
| "github.com/gorilla/websocket" | |
| "panelthtuanit/internal/config" | |
| "panelthtuanit/internal/httpx" | |
| "panelthtuanit/internal/store" | |
| ) | |
| var domainRegex = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`) | |
| var sharedTransport = &http.Transport{ | |
| Proxy: nil, | |
| DialContext: (&net.Dialer{ | |
| Timeout: 5 * time.Second, | |
| KeepAlive: 30 * time.Second, | |
| }).DialContext, | |
| MaxIdleConns: 512, | |
| MaxIdleConnsPerHost: 128, | |
| IdleConnTimeout: 90 * time.Second, | |
| ResponseHeaderTimeout: 30 * time.Second, | |
| ExpectContinueTimeout: 1 * time.Second, | |
| DisableCompression: true, | |
| } | |
| var wsUpgrader = websocket.Upgrader{ | |
| ReadBufferSize: 32 * 1024, | |
| WriteBufferSize: 32 * 1024, | |
| CheckOrigin: func(r *http.Request) bool { return true }, | |
| } | |
| // CleanDomain normalizes a domain string by stripping scheme, paths, and ports. | |
| func CleanDomain(raw string) string { | |
| d := strings.ToLower(strings.TrimSpace(raw)) | |
| if strings.HasPrefix(d, "https://") { | |
| d = d[len("https://"):] | |
| } else if strings.HasPrefix(d, "http://") { | |
| d = d[len("http://"):] | |
| } | |
| if idx := strings.IndexByte(d, '/'); idx >= 0 { | |
| d = d[:idx] | |
| } | |
| if idx := strings.IndexByte(d, ':'); idx >= 0 { | |
| d = d[:idx] | |
| } | |
| return strings.TrimSpace(d) | |
| } | |
| // IsValidDomain validates syntax and rejects localhost / *.hf.space / *.huggingface.co. | |
| func IsValidDomain(domain string) bool { | |
| if domain == "" || len(domain) > 253 { | |
| return false | |
| } | |
| switch domain { | |
| case "localhost", "127.0.0.1", "0.0.0.0": | |
| return false | |
| } | |
| if strings.HasSuffix(domain, ".hf.space") || strings.HasSuffix(domain, ".huggingface.co") { | |
| return false | |
| } | |
| return domainRegex.MatchString(domain) | |
| } | |
| func clientIP(r *http.Request) string { | |
| if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && host != "" { | |
| return host | |
| } | |
| if r.RemoteAddr != "" { | |
| return r.RemoteAddr | |
| } | |
| return "127.0.0.1" | |
| } | |
| func requestProto(r *http.Request, defaultProto string) string { | |
| if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" { | |
| return strings.TrimSpace(strings.Split(proto, ",")[0]) | |
| } | |
| if r.TLS != nil { | |
| return "https" | |
| } | |
| return defaultProto | |
| } | |
| func isTimeoutErr(err error) bool { | |
| if err == nil { | |
| return false | |
| } | |
| if errors.Is(err, context.DeadlineExceeded) || os.IsTimeout(err) { | |
| return true | |
| } | |
| var netErr net.Error | |
| return errors.As(err, &netErr) && netErr.Timeout() | |
| } | |
| // DomainProxyMiddleware intercepts custom domain HTTP/WebSocket traffic and routes it to the mapped zone port. | |
| func DomainProxyMiddleware(next http.Handler) http.Handler { | |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| rawHost := r.Header.Get("X-Forwarded-Host") | |
| if rawHost == "" { | |
| rawHost = r.Host | |
| } | |
| firstHost := strings.Split(rawHost, ",")[0] | |
| domain := CleanDomain(firstHost) | |
| mapping, ok := store.LookupDomain(domain) | |
| if !ok { | |
| next.ServeHTTP(w, r) | |
| return | |
| } | |
| if httpx.IsWebSocketUpgrade(r) { | |
| proxyWS(w, r, mapping.Port, r.URL.Path, r.URL.RawQuery, fmt.Sprintf("Không thể kết nối WebSocket tới port %d", mapping.Port)) | |
| return | |
| } | |
| target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", mapping.Port)) | |
| rp := &httputil.ReverseProxy{ | |
| Transport: sharedTransport, | |
| FlushInterval: -1, | |
| Rewrite: func(pr *httputil.ProxyRequest) { | |
| pr.SetURL(target) | |
| pr.Out.Host = fmt.Sprintf("127.0.0.1:%d", mapping.Port) | |
| pr.Out.Header.Set("X-Forwarded-For", clientIP(pr.In)) | |
| pr.Out.Header.Set("X-Forwarded-Proto", requestProto(pr.In, "https")) | |
| pr.Out.Header.Set("X-Forwarded-Host", domain) | |
| }, | |
| ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { | |
| rw.Header().Set("Content-Type", "text/plain; charset=utf-8") | |
| if isTimeoutErr(err) { | |
| rw.WriteHeader(http.StatusGatewayTimeout) | |
| _, _ = fmt.Fprintf(rw, "504 Gateway Timeout: Cổng %d phản hồi quá lâu.", mapping.Port) | |
| return | |
| } | |
| rw.WriteHeader(http.StatusBadGateway) | |
| _, _ = fmt.Fprintf(rw, "502 Bad Gateway: Không thể kết nối tới port %d trong zone '%s'. Hãy đảm bảo ứng dụng đã chạy.", mapping.Port, mapping.Zone) | |
| }, | |
| } | |
| rp.ServeHTTP(w, r) | |
| }) | |
| } | |
| func validateProxyAccess(zoneName string, port int) error { | |
| if port < config.MinPort || port > config.MaxPort { | |
| return fmt.Errorf("Port must be between %d and %d", config.MinPort, config.MaxPort) | |
| } | |
| meta := store.LoadMeta() | |
| info, ok := meta[zoneName] | |
| if !ok || info == nil { | |
| return fmt.Errorf("Zone '%s' does not exist", zoneName) | |
| } | |
| for _, p := range info.Ports { | |
| if p.Port == port { | |
| return nil | |
| } | |
| } | |
| return errors.New("Port not mapped") | |
| } | |
| // HandlePortProxy serves HTTP and WebSocket reverse proxy requests under /port/{zone_name}/{port}[/{subpath...}]. | |
| func HandlePortProxy(w http.ResponseWriter, r *http.Request) { | |
| zoneName := r.PathValue("zone_name") | |
| portStr := r.PathValue("port") | |
| port, err := strconv.Atoi(portStr) | |
| if err != nil { | |
| if httpx.IsWebSocketUpgrade(r) { | |
| if conn, uerr := wsUpgrader.Upgrade(w, r, nil); uerr == nil { | |
| _ = conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(4004, "Invalid port"), time.Now().Add(2*time.Second)) | |
| _ = conn.Close() | |
| } | |
| return | |
| } | |
| w.Header().Set("Content-Type", "text/plain; charset=utf-8") | |
| w.WriteHeader(http.StatusNotFound) | |
| _, _ = fmt.Fprintf(w, "Port not mapped or invalid: invalid port") | |
| return | |
| } | |
| if err := validateProxyAccess(zoneName, port); err != nil { | |
| if httpx.IsWebSocketUpgrade(r) { | |
| if conn, uerr := wsUpgrader.Upgrade(w, r, nil); uerr == nil { | |
| _ = conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(4004, err.Error()), time.Now().Add(2*time.Second)) | |
| _ = conn.Close() | |
| } | |
| return | |
| } | |
| w.Header().Set("Content-Type", "text/plain; charset=utf-8") | |
| w.WriteHeader(http.StatusNotFound) | |
| _, _ = fmt.Fprintf(w, "Port not mapped or invalid: %s", err.Error()) | |
| return | |
| } | |
| prefix := fmt.Sprintf("/port/%s/%d", zoneName, port) | |
| subpath := strings.TrimPrefix(r.URL.Path, prefix) | |
| if subpath == "" { | |
| subpath = "/" | |
| } | |
| if httpx.IsWebSocketUpgrade(r) { | |
| proxyWS(w, r, port, subpath, r.URL.RawQuery, fmt.Sprintf("Cannot connect WebSocket to port %d", port)) | |
| return | |
| } | |
| target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port)) | |
| portToken := fmt.Sprintf(":%d", port) | |
| rp := &httputil.ReverseProxy{ | |
| Transport: sharedTransport, | |
| FlushInterval: -1, | |
| Rewrite: func(pr *httputil.ProxyRequest) { | |
| pr.SetURL(target) | |
| pr.Out.URL.Path = subpath | |
| pr.Out.URL.RawPath = "" | |
| pr.Out.URL.RawQuery = pr.In.URL.RawQuery | |
| pr.Out.Host = fmt.Sprintf("127.0.0.1:%d", port) | |
| pr.Out.Header.Set("X-Forwarded-For", clientIP(pr.In)) | |
| pr.Out.Header.Set("X-Forwarded-Proto", requestProto(pr.In, "http")) | |
| pr.Out.Header.Set("X-Forwarded-Prefix", prefix) | |
| }, | |
| ModifyResponse: func(resp *http.Response) error { | |
| if loc := resp.Header.Get("Location"); loc != "" { | |
| if strings.HasPrefix(loc, "/") { | |
| resp.Header.Set("Location", prefix+loc) | |
| } else if idx := strings.Index(loc, portToken); idx >= 0 { | |
| rest := loc[idx+len(portToken):] | |
| resp.Header.Set("Location", prefix+rest) | |
| } | |
| } | |
| return nil | |
| }, | |
| ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { | |
| rw.Header().Set("Content-Type", "text/plain; charset=utf-8") | |
| if isTimeoutErr(err) { | |
| rw.WriteHeader(http.StatusGatewayTimeout) | |
| _, _ = fmt.Fprintf(rw, "Timeout connecting to port %d", port) | |
| return | |
| } | |
| rw.WriteHeader(http.StatusBadGateway) | |
| _, _ = fmt.Fprintf(rw, "Cannot connect to port %d. Make sure your server is running in zone '%s'.", port, zoneName) | |
| }, | |
| } | |
| rp.ServeHTTP(w, r) | |
| } | |
| var skipWSDialHeaders = map[string]bool{ | |
| "Upgrade": true, | |
| "Connection": true, | |
| "Sec-Websocket-Key": true, | |
| "Sec-Websocket-Version": true, | |
| "Sec-Websocket-Extensions": true, | |
| "Sec-Websocket-Accept": true, | |
| "Sec-Websocket-Protocol": true, | |
| } | |
| func proxyWS(w http.ResponseWriter, r *http.Request, port int, path, rawQuery, connectErrMsg string) { | |
| subprotocols := websocket.Subprotocols(r) | |
| var respHeader http.Header | |
| if len(subprotocols) > 0 { | |
| respHeader = http.Header{} | |
| respHeader.Set("Sec-WebSocket-Protocol", subprotocols[0]) | |
| } | |
| clientConn, err := wsUpgrader.Upgrade(w, r, respHeader) | |
| if err != nil { | |
| return | |
| } | |
| defer clientConn.Close() | |
| if !strings.HasPrefix(path, "/") { | |
| path = "/" + path | |
| } | |
| targetURL := fmt.Sprintf("ws://127.0.0.1:%d%s", port, path) | |
| if rawQuery != "" { | |
| targetURL += "?" + rawQuery | |
| } | |
| dialHeader := http.Header{} | |
| for k, vals := range r.Header { | |
| ck := http.CanonicalHeaderKey(k) | |
| if skipWSDialHeaders[ck] || ck == "Host" { | |
| continue | |
| } | |
| for _, v := range vals { | |
| dialHeader.Add(ck, v) | |
| } | |
| } | |
| dialer := websocket.Dialer{ | |
| HandshakeTimeout: 10 * time.Second, | |
| Subprotocols: subprotocols, | |
| } | |
| backendConn, _, err := dialer.Dial(targetURL, dialHeader) | |
| if err != nil { | |
| _ = clientConn.WriteJSON(map[string]string{"error": connectErrMsg}) | |
| return | |
| } | |
| defer backendConn.Close() | |
| var wg sync.WaitGroup | |
| wg.Add(2) | |
| pump := func(dst, src *websocket.Conn) { | |
| defer wg.Done() | |
| for { | |
| msgType, payload, rerr := src.ReadMessage() | |
| if rerr != nil { | |
| var closeErr *websocket.CloseError | |
| if errors.As(rerr, &closeErr) { | |
| _ = dst.WriteControl( | |
| websocket.CloseMessage, | |
| websocket.FormatCloseMessage(closeErr.Code, closeErr.Text), | |
| time.Now().Add(time.Second), | |
| ) | |
| } | |
| _ = dst.Close() | |
| return | |
| } | |
| if werr := dst.WriteMessage(msgType, payload); werr != nil { | |
| return | |
| } | |
| } | |
| } | |
| go pump(backendConn, clientConn) | |
| go pump(clientConn, backendConn) | |
| wg.Wait() | |
| } | |