Files
libredesk/internal/httputil/httputil.go
T
Abhinav Raut 8ee81c2d64 feat: Widget dark mode and chat reply expectation message in chat title.
feat: Add HTTP utility functions for trusted origin checks

feat: Implement typing status broadcasting for live chat clients and agents.

feat: Add support for signed URLs in media manager

fix: Update database migration to handle duplicate visitors with same email address.

feat: Add conversation subscription and typing message models for WebSocket communication

feat: Implement conversation subscription management in WebSocket hub this is used for broadcasting typing indicator.

feat: Revamp widget JavaScript to improve mobile responsiveness and show unread messages if any.
2025-07-17 01:06:54 +05:30

90 lines
2.0 KiB
Go

package httputil
import (
"net"
"net/url"
"strings"
)
// IsOriginTrusted checks if the given origin is trusted based on the trusted domains list
// Expects trustedDomains to be a list of domain strings, which can include wildcards.
// Like "*.example.com" or "example.com".
func IsOriginTrusted(origin string, trustedDomains []string) bool {
if len(trustedDomains) == 0 {
return false
}
originHost, originPort := parseHostPort(origin)
if originHost == "" {
return false
}
for _, trusted := range trustedDomains {
trustedHost, trustedPort := parseTrustedDomain(trusted)
if portMatches(originPort, trustedPort) && hostMatches(originHost, trustedHost) {
return true
}
}
return false
}
// parseHostPort extracts host and port from origin URL
func parseHostPort(origin string) (host, port string) {
u, err := url.Parse(strings.ToLower(origin))
if err != nil {
return "", ""
}
host, port, _ = net.SplitHostPort(u.Host)
if host == "" {
host = u.Host
}
return host, port
}
// parseTrustedDomain extracts host and port from trusted domain entry
func parseTrustedDomain(domain string) (host, port string) {
domain = strings.ToLower(domain)
if strings.HasPrefix(domain, "http://") || strings.HasPrefix(domain, "https://") {
u, err := url.Parse(domain)
if err != nil {
return "", ""
}
host, port, _ = net.SplitHostPort(u.Host)
if host == "" {
host = u.Host
}
return host, port
}
// Handle non-URL patterns (wildcards/domains)
host, port, _ = net.SplitHostPort(domain)
if host == "" {
host = domain
}
return host, port
}
// portMatches checks if ports are compatible
func portMatches(originPort, trustedPort string) bool {
if trustedPort == "" || trustedPort == originPort {
return true
}
return false
}
// hostMatches checks if host matches trusted pattern
func hostMatches(origin, trusted string) bool {
if trusted == origin {
return true
}
if strings.HasPrefix(trusted, "*.") {
base := trusted[2:]
return origin == base || strings.HasSuffix(origin, "."+base)
}
return false
}