package webui import ( "fmt" "net" "net/netip" "net/url" "strconv" "strings" ) // ParseOrigin reads an origin and returns it in the form a browser writes in an // Origin header: scheme and host only, the host in lower case, a default port // left out. A flag and the header the same page sends then name the same origin // even when one says https://Host:443 and the other https://host. A nil URL is // no origin at all. func ParseOrigin(text string) (*url.URL, error) { trimmed := strings.TrimSpace(text) if trimmed == "" { return nil, fmt.Errorf("no origin given") } parsed, err := url.Parse(trimmed) if err != nil { return nil, fmt.Errorf("origin %q: %w", text, err) } parsed.Scheme = strings.ToLower(parsed.Scheme) if parsed.Scheme != "http" && parsed.Scheme != "https" { return nil, fmt.Errorf("origin %q: scheme must be http or https", text) } if parsed.User != nil { return nil, fmt.Errorf("origin %q: no credentials", text) } if parsed.Hostname() == "" { return nil, fmt.Errorf("origin %q: no host", text) } if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { return nil, fmt.Errorf("origin %q: give only the scheme and host, without a path, query or fragment", text) } if port := parsed.Port(); port != "" { if _, err := strconv.ParseUint(port, 10, 16); err != nil { return nil, fmt.Errorf("origin %q: port %s is not a TCP port", text, port) } } parsed.Host = canonicalHost(parsed) parsed.Path, parsed.RawPath = "", "" return parsed, nil } // canonicalHost is u's host as a browser writes an origin: lower case, without // the scheme's default port, and an IPv6 literal in brackets. func canonicalHost(u *url.URL) string { host := hostKey(u.Hostname()) if port := portNumber(u.Port()); port != "" && port != defaultPort(u.Scheme) { return net.JoinHostPort(host, port) } if strings.Contains(host, ":") { return "[" + host + "]" } return host } // hostKey is a host as a browser writes it in Host and Origin, without // brackets: lower case, and an IPv6 literal in the URL Standard's form, so // [0:0::1] written in a flag is the [::1] a browser sends. func hostKey(host string) string { host = strings.ToLower(strings.Trim(host, "[]")) if !strings.Contains(host, ":") { return host } addr, err := netip.ParseAddr(host) if err != nil || !addr.Is6() || addr.Zone() != "" { return host } return serializeIPv6(addr.As16()) } // serializeIPv6 writes an address as the URL Standard does: lower-case hex // pieces without leading zeros, the first longest run of two or more zero // pieces compressed, and an embedded IPv4 address as hex pieces, which // netip's RFC 5952 form writes dotted. func serializeIPv6(bytes [16]byte) string { var pieces [8]uint16 for i := range pieces { pieces[i] = uint16(bytes[2*i])<<8 | uint16(bytes[2*i+1]) } start, length := -1, 1 for i := 0; i < len(pieces); { run := 0 for i+run < len(pieces) && pieces[i+run] == 0 { run++ } if run > length { start, length = i, run } i += max(run, 1) } var out strings.Builder for i := 0; i < len(pieces); i++ { if i == start { out.WriteString("::") i += length - 1 continue } if i > 0 && i != start+length { out.WriteByte(':') } out.WriteString(strconv.FormatUint(uint64(pieces[i]), 16)) } return out.String() } // defaultPort is the port a browser leaves out of an origin for scheme. func defaultPort(scheme string) string { if scheme == "http" { return "80" } return "443" } // portNumber writes a port as the number it names, as a browser serializes // it: 0443 is 443. Text that names no number is left as written. func portNumber(port string) string { if number, err := strconv.ParseUint(port, 10, 16); err == nil { return strconv.FormatUint(number, 10) } return port } // originPort is the port u is reached on: its own, or the scheme's default. func originPort(u *url.URL) string { if port := portNumber(u.Port()); port != "" { return port } return defaultPort(u.Scheme) } // SameOrigin reports whether a and b name the same origin; nil is no origin. func SameOrigin(a, b *url.URL) bool { if a == nil || b == nil { return a == nil && b == nil } return a.Scheme == b.Scheme && hostKey(a.Hostname()) == hostKey(b.Hostname()) && originPort(a) == originPort(b) } // Loopback is the origin of a listener on port at 127.0.0.1. func Loopback(port int) *url.URL { return &url.URL{Scheme: "http", Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(port))} } // LaunchLink is the address that signs a browser in through origin: the key // trades once for the cookie, so the link itself is the secret. func LaunchLink(origin *url.URL, key string) string { link := *origin link.Path = "/" link.RawQuery = url.Values{"key": {key}}.Encode() return link.String() }