// Package links finds, validates and redacts URLs in chat messages. package links import ( "errors" "net" "net/url" "regexp" "strings" "unicode/utf16" ) // Errors returned by Normalize. var ( ErrNotURL = errors.New("links: not a url") ErrScheme = errors.New("links: only http and https are allowed") ErrPrivateHost = errors.New("links: host is local or private") ) // Entity is the part of a Telegram message entity that matters here. // Offset and Length are in UTF-16 code units, as Telegram sends them. type Entity struct { Type string Offset int Length int URL string } var urlRe = regexp.MustCompile(`(?i)\bhttps?://[^\s<>"'` + "`" + `]+`) // Extract returns the URLs found in a message, in order, without duplicates. // Telegram entities are trusted first because they also catch links without // a scheme (youtu.be/abc) and text links. A regular expression is the // fallback for clients that send no entities. func Extract(text string, entities []Entity) []string { var out []string seen := map[string]bool{} add := func(raw string) { u, err := Normalize(raw) if err != nil || seen[u] { return } seen[u] = true out = append(out, u) } if len(entities) > 0 { units := utf16.Encode([]rune(text)) for _, e := range entities { switch e.Type { case "text_link": add(e.URL) case "url": if e.Offset < 0 || e.Length <= 0 || e.Offset+e.Length > len(units) { continue } add(string(utf16.Decode(units[e.Offset : e.Offset+e.Length]))) } } } if len(out) == 0 { for _, m := range urlRe.FindAllString(text, -1) { add(m) } } return out } // Normalize validates a raw link and returns a cleaned form. It adds https // when the scheme is missing, lowercases the host, drops the fragment and // trailing punctuation, and rejects local or private hosts. func Normalize(raw string) (string, error) { raw = strings.TrimSpace(raw) raw = strings.TrimRight(raw, ".,;:!?)]}>\"'") if raw == "" { return "", ErrNotURL } if !strings.Contains(raw, "://") { if strings.ContainsAny(raw, " \t\n") || !strings.Contains(raw, ".") { return "", ErrNotURL } raw = "https://" + raw } u, err := url.Parse(raw) if err != nil { return "", ErrNotURL } u.Scheme = strings.ToLower(u.Scheme) if u.Scheme != "http" && u.Scheme != "https" { return "", ErrScheme } host := strings.ToLower(u.Hostname()) if host == "" || !strings.Contains(host, ".") && net.ParseIP(host) == nil { if host == "localhost" { return "", ErrPrivateHost } return "", ErrNotURL } if isPrivateHost(host) { return "", ErrPrivateHost } if port := u.Port(); port != "" { u.Host = net.JoinHostPort(host, port) } else if strings.Contains(host, ":") { u.Host = "[" + host + "]" } else { u.Host = host } u.Fragment = "" u.User = nil return u.String(), nil } func isPrivateHost(host string) bool { if host == "localhost" || strings.HasSuffix(host, ".localhost") || strings.HasSuffix(host, ".local") || strings.HasSuffix(host, ".internal") || strings.HasSuffix(host, ".lan") || strings.HasSuffix(host, ".home.arpa") { return true } ip := net.ParseIP(host) if ip == nil { return false } return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast() || ip.IsUnspecified() } // Site returns the host of a URL without a leading "www." or "m.", for use // in allow lists, block lists and per-site metrics. It returns "" on error. func Site(raw string) string { u, err := url.Parse(raw) if err != nil { return "" } h := strings.ToLower(u.Hostname()) h = strings.TrimPrefix(h, "www.") h = strings.TrimPrefix(h, "m.") return h } // sensitiveParams are query keys whose values never reach the logs. var sensitiveParams = []string{ "token", "key", "sig", "signature", "pass", "password", "pwd", "auth", "secret", "session", "sid", "code", "credential", "jwt", "policy", "expires", } // Redact makes a URL safe for logs: it removes user info and blanks the // values of query parameters that look like credentials. func Redact(raw string) string { u, err := url.Parse(raw) if err != nil { return "[unparseable url]" } u.User = nil if u.RawQuery != "" { q := u.Query() for k := range q { lk := strings.ToLower(k) for _, s := range sensitiveParams { if strings.Contains(lk, s) { q.Set(k, "REDACTED") break } } } u.RawQuery = q.Encode() } return u.String() } var anyURLRe = regexp.MustCompile(`(?i)\bhttps?://[^\s<>"'` + "`" + `]+`) // RedactText redacts every URL inside free text such as tool error output. func RedactText(s string) string { return anyURLRe.ReplaceAllStringFunc(s, Redact) }