internal/webfetch/options.go

package webfetch

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

// Operation identifies the implementation selected by the URL scheme or --mcp.
type Operation uint8

const (
	OperationHTTP Operation = iota + 1
	OperationWebSocket
	OperationMCP
)

// Information identifies a URL-free informational command.
type Information uint8

const (
	InformationNone Information = iota
	InformationHelp
	InformationHelpHTTP
	InformationHelpHTML
	InformationHelpWebSocket
	InformationHelpFramed
	InformationHelpAll
	InformationVersion
)

const (
	defaultHTMLWidth     = 120
	defaultWSFrameSize   = int64(65536)
	defaultWSFrameDelay  = 10 * time.Millisecond
	defaultWSEOFTimeout  = 10 * time.Second
	defaultTransformMax  = int64(10 * 1024 * 1024)
	defaultResponseMax   = int64(10 * 1024 * 1024)
	maxWSStreamFrameSize = int64(65536)
	maxWSMessageSize     = int64(1<<63 - 2)
	minWSTextFrameSize   = int64(utf8.UTFMax)
)

// Options is the fully parsed and validated command configuration. Defaults do
// not imply explicit presence; use Present when that distinction is material.
type Options struct {
	Information Information
	Operation   Operation
	URL         *url.URL

	HeaderValues     []string
	HeaderFiles      []string
	SensitiveHeaders []string
	Headers          ParsedHeaders
	UserAgent        string
	Timeout          time.Duration
	MCP              MCPOptions

	Method        string
	Data          string
	DataFile      string
	Output        string
	Force         bool
	FailWithBody  bool
	NoRedirect    bool
	MaxBytes      int64
	Normalize     bool
	StripAndIndex bool
	HTMLWidth     int

	WSMode         string
	WSType         string
	WSFrameSize    int64
	WSFrameDelay   time.Duration
	WSEOFTimeout   time.Duration
	WSSubprotocols []string
	WSCompression  string
	WSMaxMessage   int64
	WSPingInterval time.Duration

	positionals []string
	present     map[string]bool
}

// optionScope says which URL schemes accept an option.
type optionScope uint8

const (
	scopeAny optionScope = iota
	scopeHTTP
	scopeWebSocket
)

// optionDef is the one place an option is defined. Parsing, alias lookup,
// scheme checks, and usage hints all read this table.
type optionDef struct {
	name       string
	short      string
	takesValue bool
	scope      optionScope
	// hint overrides the help section implied by scope.
	hint   Information
	assign func(o *Options, option optionDef, value string) error
}

func (d optionDef) usageHint() Information {
	if d.hint != InformationNone {
		return d.hint
	}
	switch d.scope {
	case scopeHTTP:
		return InformationHelpHTTP
	case scopeWebSocket:
		return InformationHelpWebSocket
	default:
		return InformationHelp
	}
}

var optionDefinitions = []optionDef{
	// Informational options.
	{name: "help", short: "h", assign: informationOpt(InformationHelp)},
	{name: "help-http", assign: informationOpt(InformationHelpHTTP)},
	{name: "help-html", assign: informationOpt(InformationHelpHTML)},
	{name: "help-websocket", assign: informationOpt(InformationHelpWebSocket)},
	{name: "help-framed", assign: informationOpt(InformationHelpFramed)},
	{name: "help-all", assign: informationOpt(InformationHelpAll)},
	{name: "version", assign: informationOpt(InformationVersion)},

	// Options shared by HTTP and WebSocket.
	{name: "header", short: "H", takesValue: true, assign: appendOpt(func(o *Options) *[]string { return &o.HeaderValues })},
	{name: "header-file", takesValue: true, assign: appendOpt(func(o *Options) *[]string { return &o.HeaderFiles })},
	{name: "sensitive-header", takesValue: true, assign: appendOpt(func(o *Options) *[]string { return &o.SensitiveHeaders })},
	{name: "user-agent", short: "A", takesValue: true, assign: stringOpt(func(o *Options) *string { return &o.UserAgent })},
	{name: "timeout", takesValue: true, assign: durationOpt(func(o *Options) *time.Duration { return &o.Timeout })},

	// HTTP options. Table order is the order scheme errors are reported.
	{name: "method", short: "X", takesValue: true, scope: scopeHTTP, assign: stringOpt(func(o *Options) *string { return &o.Method })},
	{name: "data", short: "d", takesValue: true, scope: scopeHTTP, assign: stringOpt(func(o *Options) *string { return &o.Data })},
	{name: "data-file", takesValue: true, scope: scopeHTTP, assign: stringOpt(func(o *Options) *string { return &o.DataFile })},
	{name: "output", short: "o", takesValue: true, scope: scopeHTTP, assign: stringOpt(func(o *Options) *string { return &o.Output })},
	{name: "force", scope: scopeHTTP, assign: flagOpt(func(o *Options) *bool { return &o.Force })},
	{name: "fail-with-body", scope: scopeHTTP, assign: flagOpt(func(o *Options) *bool { return &o.FailWithBody })},
	{name: "no-redirect", scope: scopeHTTP, assign: flagOpt(func(o *Options) *bool { return &o.NoRedirect })},
	{name: "max-bytes", takesValue: true, scope: scopeHTTP, assign: intOpt(func(o *Options) *int64 { return &o.MaxBytes })},
	{name: "normalize", scope: scopeHTTP, hint: InformationHelpHTML, assign: flagOpt(func(o *Options) *bool { return &o.Normalize })},
	{name: "strip-and-index", scope: scopeHTTP, hint: InformationHelpHTML, assign: flagOpt(func(o *Options) *bool { return &o.StripAndIndex })},
	{name: "html-width", takesValue: true, scope: scopeHTTP, hint: InformationHelpHTML, assign: assignHTMLWidth},

	// WebSocket options.
	{name: "ws-mode", takesValue: true, scope: scopeWebSocket, assign: stringOpt(func(o *Options) *string { return &o.WSMode })},
	{name: "ws-type", takesValue: true, scope: scopeWebSocket, assign: stringOpt(func(o *Options) *string { return &o.WSType })},
	{name: "ws-frame-size", takesValue: true, scope: scopeWebSocket, assign: intOpt(func(o *Options) *int64 { return &o.WSFrameSize })},
	{name: "ws-frame-delay", takesValue: true, scope: scopeWebSocket, assign: durationOpt(func(o *Options) *time.Duration { return &o.WSFrameDelay })},
	{name: "ws-eof-timeout", takesValue: true, scope: scopeWebSocket, assign: durationOpt(func(o *Options) *time.Duration { return &o.WSEOFTimeout })},
	{name: "ws-subprotocol", takesValue: true, scope: scopeWebSocket, assign: appendOpt(func(o *Options) *[]string { return &o.WSSubprotocols })},
	{name: "ws-compression", takesValue: true, scope: scopeWebSocket, assign: stringOpt(func(o *Options) *string { return &o.WSCompression })},
	{name: "ws-max-message", takesValue: true, scope: scopeWebSocket, assign: intOpt(func(o *Options) *int64 { return &o.WSMaxMessage })},
	{name: "ws-ping-interval", takesValue: true, scope: scopeWebSocket, assign: durationOpt(func(o *Options) *time.Duration { return &o.WSPingInterval })},
}

func findOption(name string) (optionDef, bool) {
	for _, option := range mcpOptionDefinitions {
		if option.name == name {
			return option, true
		}
	}
	for _, option := range optionDefinitions {
		if option.name == name {
			return option, true
		}
	}
	return optionDef{}, false
}

func findShortOption(short string) (optionDef, bool) {
	for _, option := range optionDefinitions {
		if option.short != "" && option.short == short {
			return option, true
		}
	}
	return optionDef{}, false
}

func informationOpt(information Information) func(*Options, optionDef, string) error {
	return func(o *Options, _ optionDef, _ string) error {
		o.setInformation(information)
		return nil
	}
}

func stringOpt(target func(*Options) *string) func(*Options, optionDef, string) error {
	return func(o *Options, _ optionDef, value string) error {
		*target(o) = value
		return nil
	}
}

func appendOpt(target func(*Options) *[]string) func(*Options, optionDef, string) error {
	return func(o *Options, _ optionDef, value string) error {
		values := target(o)
		*values = append(*values, value)
		return nil
	}
}

func flagOpt(target func(*Options) *bool) func(*Options, optionDef, string) error {
	return func(o *Options, _ optionDef, _ string) error {
		*target(o) = true
		return nil
	}
}

func durationOpt(target func(*Options) *time.Duration) func(*Options, optionDef, string) error {
	return func(o *Options, option optionDef, value string) error {
		duration, err := parseDuration(option.name, value, option.usageHint())
		if err != nil {
			return err
		}
		*target(o) = duration
		return nil
	}
}

func intOpt(target func(*Options) *int64) func(*Options, optionDef, string) error {
	return func(o *Options, option optionDef, value string) error {
		n, err := parseNonnegativeInt(option.name, value, option.usageHint())
		if err != nil {
			return err
		}
		*target(o) = n
		return nil
	}
}

func assignHTMLWidth(o *Options, option optionDef, value string) error {
	n, err := parseNonnegativeInt(option.name, value, option.usageHint())
	if err != nil {
		return err
	}
	if int64(int(n)) != n {
		return usageError(option.usageHint(), "invalid --%s %q: value is too large", option.name, value)
	}
	o.HTMLWidth = int(n)
	return nil
}

// Present reports whether a canonical long option was explicitly supplied.
// Aliases such as -H and --header both record "header". This can differ from
// the option's effective default value.
func (o Options) Present(name string) bool {
	name = strings.TrimLeft(name, "-")
	if option, ok := findShortOption(name); ok {
		name = option.name
	}
	return o.present[name]
}

// EffectiveMaxBytes returns the response limit. All HTTP modes default to
// 10 MiB; an explicit zero retains the raw streaming opt-out.
func (o Options) EffectiveMaxBytes() int64 {
	if !o.Present("max-bytes") {
		if o.Normalize || o.StripAndIndex {
			return defaultTransformMax
		}
		return defaultResponseMax
	}
	return o.MaxBytes
}

// SafeURL returns a diagnostic form without userinfo, query, or fragment.
func (o Options) SafeURL() string {
	return SanitizeURL(o.URL)
}

// UsageError is a command-line contract failure and carries the most relevant
// detailed-help hint.
type UsageError struct {
	Message string
	Hint    Information
}

func (e *UsageError) Error() string { return e.Message }

func usageError(hint Information, format string, args ...any) error {
	return &UsageError{Message: fmt.Sprintf(format, args...), Hint: hint}
}

// ParseOptions parses interspersed options and validates the complete CLI
// contract, applies defaults, and never opens files, starts networking, or
// reads stdin.
func ParseOptions(args []string) (Options, error) {
	o := Options{
		HTMLWidth:     defaultHTMLWidth,
		WSMode:        "stream",
		WSType:        "text",
		WSFrameSize:   defaultWSFrameSize,
		WSFrameDelay:  defaultWSFrameDelay,
		WSEOFTimeout:  defaultWSEOFTimeout,
		WSCompression: "disabled",
		WSMaxMessage:  defaultResponseMax,
		present:       make(map[string]bool),
	}

	options := true
	mcpCLI := hasMCPArguments(args)
	for i := 0; i < len(args); i++ {
		arg := args[i]
		if options && arg == "--" {
			options = false
			continue
		}
		if !options || arg == "-" || !strings.HasPrefix(arg, "-") {
			o.positionals = append(o.positionals, arg)
			continue
		}

		name, value, hasValue, err := splitOption(arg)
		if err != nil {
			if mcpCLI {
				return Options{}, usageError(InformationHelp, "invalid MCP command option")
			}
			return Options{}, err
		}
		option, known := findOption(name)
		if !known {
			if mcpCLI {
				return Options{}, usageError(InformationHelp, "unknown MCP command option; secrets must use protected input")
			}
			return Options{}, usageError(InformationHelp, "unknown option %s", quoteOptionName(name))
		}
		if option.takesValue {
			if !hasValue {
				if i+1 >= len(args) {
					return Options{}, usageError(option.usageHint(), "option --%s requires a value", option.name)
				}
				i++
				value = args[i]
			}
		} else if hasValue {
			return Options{}, usageError(option.usageHint(), "option --%s does not take a value", option.name)
		}

		if strings.HasPrefix(option.name, "mcp") && o.present[option.name] {
			return Options{}, usageError(InformationHelp, "MCP options may not be repeated")
		}
		o.present[option.name] = true
		if err := option.assign(&o, option, value); err != nil {
			if mcpCLI {
				return Options{}, usageError(InformationHelp, "invalid MCP command option value")
			}
			return Options{}, err
		}
	}

	if o.Information != InformationNone {
		return o, nil
	}
	if mcpCLI {
		if err := o.validateMCP(); err != nil {
			return Options{}, err
		}
		return o, nil
	}
	if err := o.validateURL(); err != nil {
		return Options{}, err
	}
	if err := o.validateCombinations(); err != nil {
		return Options{}, err
	}
	return o, nil
}

func splitOption(arg string) (name, value string, hasValue bool, err error) {
	if strings.HasPrefix(arg, "--") {
		if arg == "--" {
			return "", "", false, usageError(InformationHelp, "internal option parser error")
		}
		body := strings.TrimPrefix(arg, "--")
		if body == "" {
			return "", "", false, usageError(InformationHelp, "invalid empty option")
		}
		if at := strings.IndexByte(body, '='); at >= 0 {
			return body[:at], body[at+1:], true, nil
		}
		return body, "", false, nil
	}

	for _, option := range optionDefinitions {
		if option.short == "" {
			continue
		}
		spelling := "-" + option.short
		if arg == spelling {
			return option.name, "", false, nil
		}
		if option.takesValue && strings.HasPrefix(arg, spelling) {
			value := strings.TrimPrefix(arg, spelling)
			value = strings.TrimPrefix(value, "=")
			return option.name, value, true, nil
		}
	}
	return "", "", false, usageError(InformationHelp, "unknown option %s", arg)
}

func quoteOptionName(name string) string {
	if len(name) == 1 {
		return "-" + name
	}
	return "--" + name
}

func (o *Options) setInformation(info Information) {
	if o.Information == InformationNone {
		o.Information = info
	}
}

func parseNonnegativeInt(name, value string, hint Information) (int64, error) {
	n, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		return 0, usageError(hint, "invalid --%s %q: expected a decimal integer", name, value)
	}
	if n < 0 {
		return 0, usageError(hint, "invalid --%s %q: value must be nonnegative", name, value)
	}
	return n, nil
}

func parseDuration(name, value string, hint Information) (time.Duration, error) {
	d, err := time.ParseDuration(value)
	if err != nil {
		return 0, usageError(hint, "invalid --%s %q: expected a Go duration such as 500ms or 30s", name, value)
	}
	if d < 0 {
		return 0, usageError(hint, "invalid --%s %q: duration must be nonnegative", name, value)
	}
	return d, nil
}

// validateURL selects HTTP or WebSocket from the scheme and rejects unsafe or
// unsupported URL forms before dispatch.
func (o *Options) validateURL() error {
	if len(o.positionals) == 0 {
		return usageError(InformationHelp, "exactly one URL is required")
	}
	if len(o.positionals) > 1 {
		return usageError(InformationHelp, "exactly one URL is required; got %d positional arguments", len(o.positionals))
	}
	raw := o.positionals[0]
	u, err := url.Parse(raw)
	if err != nil {
		return usageError(InformationHelp, "malformed URL")
	}
	if u.Scheme == "" {
		return usageError(InformationHelp, "URL must include an http, https, ws, or wss scheme")
	}
	if u.Opaque != "" || u.Host == "" {
		return usageError(InformationHelp, "malformed %s URL: an authority/host is required", strings.ToLower(u.Scheme))
	}
	if u.User != nil {
		return usageError(InformationHelp, "URL userinfo is not supported (%s)", SanitizeURL(u))
	}
	if u.Fragment != "" || strings.Contains(raw, "#") {
		return usageError(InformationHelp, "URL fragments are not supported (%s)", SanitizeURL(u))
	}
	switch strings.ToLower(u.Scheme) {
	case "http", "https":
		o.Operation = OperationHTTP
	case "ws", "wss":
		o.Operation = OperationWebSocket
	default:
		return usageError(InformationHelp, "unsupported URL scheme %q; expected http, https, ws, or wss", strings.ToLower(u.Scheme))
	}
	u.Scheme = strings.ToLower(u.Scheme)
	o.URL = u
	return nil
}

// validateCombinations checks shared constraints before applying protocol- and
// transformation-specific validation.
func (o *Options) validateCombinations() error {
	for _, path := range o.HeaderFiles {
		if path == "" || path == "-" {
			return usageError(headerHint(o.Operation), "--header-file requires a filesystem path; stdin remains request input")
		}
	}
	if err := o.rejectOtherSchemeOptions(); err != nil {
		return err
	}
	if o.Operation == OperationWebSocket {
		if err := o.validateWebSocket(); err != nil {
			return err
		}
	} else {
		if err := o.validateHTTP(); err != nil {
			return err
		}
	}

	headers, err := ParseHeaders(o.HeaderValues, o.Present("user-agent"), o.UserAgent, o.Operation)
	if err != nil {
		return err
	}
	o.Headers = headers
	o.UserAgent = headers.UserAgent
	seenSensitive := make(map[string]bool)
	for i, name := range o.SensitiveHeaders {
		if !validToken(name) {
			return usageError(headerHint(o.Operation), "invalid --sensitive-header %q: expected a header field name", name)
		}
		canonical := strings.ToLower(name)
		if seenSensitive[canonical] {
			return usageError(headerHint(o.Operation), "duplicate --sensitive-header %q", name)
		}
		seenSensitive[canonical] = true
		o.SensitiveHeaders[i] = canonical
	}
	if o.Operation == OperationHTTP && (o.Normalize || o.StripAndIndex) {
		if values, present := o.Headers.Header["Accept-Encoding"]; present &&
			(len(values) != 1 || values[0] != "identity") {
			return usageError(InformationHelpHTML, "a response transform requires Accept-Encoding: identity")
		}
	}
	return nil
}

// rejectOtherSchemeOptions rejects options whose table scope excludes the
// selected URL scheme.
func (o *Options) rejectOtherSchemeOptions() error {
	for _, option := range optionDefinitions {
		if !o.present[option.name] {
			continue
		}
		switch {
		case option.scope == scopeHTTP && o.Operation != OperationHTTP:
			return usageError(option.usageHint(), "--%s applies only to HTTP URLs", option.name)
		case option.scope == scopeWebSocket && o.Operation != OperationWebSocket:
			return usageError(option.usageHint(), "--%s applies only to WebSocket URLs", option.name)
		}
	}
	return nil
}

// validateHTTP enforces HTTP request and response-transform option rules.
func (o *Options) validateHTTP() error {
	if o.Present("data") && o.Present("data-file") {
		return usageError(InformationHelpHTTP, "--data and --data-file are mutually exclusive")
	}
	if o.Present("method") && !validToken(o.Method) {
		return usageError(InformationHelpHTTP, "invalid --method %q: expected a nonempty HTTP token", o.Method)
	}
	if o.Method == "" {
		if o.Present("data") || o.Present("data-file") {
			o.Method = "POST"
		} else {
			o.Method = "GET"
		}
	}
	if o.Present("html-width") {
		if !o.Normalize && !o.StripAndIndex {
			return usageError(InformationHelpHTML, "--html-width requires --normalize or --strip-and-index")
		}
		if o.HTMLWidth < 80 || o.HTMLWidth > 160 {
			return usageError(InformationHelpHTML, "--html-width must be from 80 through 160")
		}
	}
	if (o.Normalize || o.StripAndIndex) && o.Present("max-bytes") && o.MaxBytes == 0 {
		return usageError(InformationHelpHTML, "explicit --max-bytes 0 is invalid with a response transform")
	}
	if o.StripAndIndex {
		o.Normalize = true
	}
	if o.Force && (!o.Present("output") || o.Output == "" || o.Output == "-") {
		return usageError(InformationHelpHTTP, "--force requires a filesystem --output PATH (not -)")
	}
	if o.Present("output") && o.Output == "" {
		return usageError(InformationHelpHTTP, "--output requires a nonempty path or - for stdout")
	}
	return nil
}

// validateWebSocket checks mode-specific framing, compression, and protocol
// settings before the WebSocket runner is called.
func (o *Options) validateWebSocket() error {
	if o.WSMode != "stream" && o.WSMode != "framed" {
		return usageError(InformationHelpWebSocket, "invalid --ws-mode %q: expected stream or framed", o.WSMode)
	}
	if o.WSMaxMessage > maxWSMessageSize {
		return usageError(InformationHelpWebSocket, "--ws-max-message must not exceed 9223372036854775806")
	}
	if o.WSMode == "framed" {
		for _, name := range []string{"ws-type", "ws-frame-size", "ws-frame-delay"} {
			if o.Present(name) {
				return usageError(InformationHelpFramed, "--%s applies only to WebSocket stream mode", name)
			}
		}
	} else {
		if o.WSType != "text" && o.WSType != "binary" {
			return usageError(InformationHelpWebSocket, "invalid --ws-type %q: expected text or binary", o.WSType)
		}
		if o.WSFrameSize < 1 || o.WSFrameSize > maxWSStreamFrameSize {
			return usageError(InformationHelpWebSocket, "--ws-frame-size must be from 1 through 65536")
		}
		if o.WSType == "text" && o.WSFrameSize < minWSTextFrameSize {
			return usageError(InformationHelpWebSocket, "--ws-frame-size must be from 4 through 65536 in text mode")
		}
		if o.WSMaxMessage > 0 && o.WSFrameSize > o.WSMaxMessage {
			return usageError(InformationHelpWebSocket, "--ws-frame-size may not exceed positive --ws-max-message")
		}
	}
	if o.WSCompression != "disabled" && o.WSCompression != "no-context" && o.WSCompression != "context" {
		return usageError(InformationHelpWebSocket, "invalid --ws-compression %q: expected disabled, no-context, or context", o.WSCompression)
	}
	seenProtocols := make(map[string]bool)
	for _, protocol := range o.WSSubprotocols {
		if !validToken(protocol) {
			return usageError(InformationHelpWebSocket, "invalid --ws-subprotocol %q: expected a nonempty HTTP token", protocol)
		}
		if seenProtocols[protocol] {
			return usageError(InformationHelpWebSocket, "duplicate --ws-subprotocol %q", protocol)
		}
		seenProtocols[protocol] = true
	}
	return nil
}

// SanitizeURL removes credentials, query, and fragment from a parsed URL for
// diagnostics. It never mutates the supplied URL.
func SanitizeURL(u *url.URL) string {
	if u == nil {
		return "URL"
	}
	copy := *u
	copy.User = nil
	copy.RawQuery = ""
	copy.ForceQuery = false
	copy.Fragment = ""
	copy.RawFragment = ""
	return copy.String()
}