From 45cacd18aa2dccaa12bdd41f7406f1462f67742a Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 28 Nov 2026 09:24:04 +0100 Subject: [PATCH 1/8] Use plain logging for subcommands and require subcommands first Subcommands such as 'devproxy api show' now print plain text without level labels; the decorated output is kept for the root command that monitors traffic. Options placed before a subcommand are now rejected, so the root command can be detected reliably from the first argument, even for subcommands contributed by plugins. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/ConfigValidateTests.cs | 9 +- DevProxy.Tests/DevProxyCommandTests.cs | 39 ++++- DevProxy.Tests/DevProxyConfigOptionsTests.cs | 10 -- DevProxy.Tests/LoggingConfigurationTests.cs | 15 ++ DevProxy.Tests/ProxyConsoleFormatterTests.cs | 16 ++ DevProxy/Commands/ConfigCommand.cs | 1 + DevProxy/Commands/DevProxyCommand.cs | 162 +++++++----------- DevProxy/Commands/PluginCommand.cs | 1 + .../Extensions/ILoggingBuilderExtensions.cs | 5 +- DevProxy/Logging/ProxyConsoleFormatter.cs | 24 ++- .../Logging/ProxyConsoleFormatterOptions.cs | 4 + 11 files changed, 155 insertions(+), 131 deletions(-) diff --git a/DevProxy.Tests/ConfigValidateTests.cs b/DevProxy.Tests/ConfigValidateTests.cs index 921d1476..05d992b6 100644 --- a/DevProxy.Tests/ConfigValidateTests.cs +++ b/DevProxy.Tests/ConfigValidateTests.cs @@ -383,10 +383,9 @@ public async Task AcceptsCaseInsensitiveKeyCollisionsInYaml() [Theory] [InlineData(new[] { "validate" }, true)] [InlineData(new[] { "config", "validate" }, true)] - [InlineData(new[] { "--output", "json", "validate" }, true)] - [InlineData(new[] { "--output=json", "config", "validate" }, true)] - [InlineData(new[] { "--output:json", "validate" }, true)] - [InlineData(new[] { "--log-level:Warning", "validate" }, true)] + [InlineData(new[] { "validate", "--output", "json" }, true)] + [InlineData(new[] { "config", "validate", "--output=json" }, true)] + [InlineData(new[] { "--output", "json", "validate" }, false)] [InlineData(new[] { "validate", "--help" }, false)] [InlineData(new[] { "config", "get", "validate" }, false)] [InlineData(new[] { "--config-file", "validate" }, false)] @@ -395,7 +394,7 @@ public void DetectsValidateInvocation(string[] args, bool expected) => [Theory] [InlineData(new[] { "validate", "--config-file=my.json" }, "my.json")] - [InlineData(new[] { "--output", "json", "config", "validate", "-c", "my.json" }, "my.json")] + [InlineData(new[] { "config", "validate", "--output", "json", "-c", "my.json" }, "my.json")] public void ParsesValidateArgs(string[] args, string expectedConfigFile) { var parseResult = ConfigCommand.ParseValidateArgs(args, out var configFileOptions, out _); diff --git a/DevProxy.Tests/DevProxyCommandTests.cs b/DevProxy.Tests/DevProxyCommandTests.cs index f1f79b8d..0f8e3e99 100644 --- a/DevProxy.Tests/DevProxyCommandTests.cs +++ b/DevProxy.Tests/DevProxyCommandTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using DevProxy.Commands; +using System.CommandLine; using Xunit; @@ -54,15 +55,39 @@ public void ApplyDiscoverOption_False_KeepsRecordingEnabledFromOtherSources() [Theory] [InlineData(true, "stdio", "npx", "@devproxy/mcp")] - [InlineData(true, "--log-level", "debug", "stdio", "npx")] + [InlineData(true, "stdio", "-c", "myconfig.json", "node", "app.js")] + [InlineData(false, "--log-level", "debug", "stdio", "npx")] [InlineData(false, "jwt", "create", "--name", "stdio", "--output", "json")] - [InlineData(true, "--env", "A=1", "B=2", "stdio", "node", "server.js")] - [InlineData(true, "-e", "A=1", "B=2", "--log-level", "debug", "stdio", "node")] - [InlineData(true, "--urls-to-watch", "https://a/*", "https://b/*", "stdio", "node")] - [InlineData(true, "--watch-pids", "1", "2", "stdio", "node")] - [InlineData(true, "--watch-process-names", "a", "b", "stdio", "node")] [InlineData(false, "config", "get", "stdio")] [InlineData(false)] - public void IsStdioSubcommand_DetectsSubcommandNotArgumentValues(bool expected, params string[] args) => + public void IsStdioSubcommand_DetectsSubcommandOnlyAsFirstArgument(bool expected, params string[] args) => Assert.Equal(expected, DevProxyCommand.IsStdioSubcommand(args)); + + [Theory] + [InlineData(null)] + [InlineData(null, "--port", "0")] + [InlineData(null, "--help")] + [InlineData(null, "api", "show", "--log-level", "debug")] + [InlineData("api show", "--log-level", "debug", "api", "show")] + [InlineData("api show", "--port", "1", "api", "show")] + [InlineData("api", "--output", "json", "api")] + public void GetLeadingOptionsError_RejectsOptionsBeforeSubcommand(string? expectedCommandPath, params string[] args) + { + var logLevelOption = new Option(DevProxyCommand.LogLevelOptionName) { Recursive = true }; + var outputOption = new Option(DevProxyCommand.OutputOptionName) { Recursive = true }; + var portOption = new Option(DevProxyCommand.PortOptionName); + var apiCommand = new Command("api") { new Command("show") }; + var rootCommand = new RootCommand { logLevelOption, outputOption, portOption, apiCommand }; + + var error = DevProxyCommand.GetLeadingOptionsError(rootCommand.Parse(args), args); + + if (expectedCommandPath is null) + { + Assert.Null(error); + } + else + { + Assert.Contains($"devproxy {expectedCommandPath} [options]", error, StringComparison.Ordinal); + } + } } diff --git a/DevProxy.Tests/DevProxyConfigOptionsTests.cs b/DevProxy.Tests/DevProxyConfigOptionsTests.cs index 04801dee..b4a17313 100644 --- a/DevProxy.Tests/DevProxyConfigOptionsTests.cs +++ b/DevProxy.Tests/DevProxyConfigOptionsTests.cs @@ -23,14 +23,4 @@ public void Discover_ParsesOptionalValue(string[] args, bool expected) Assert.Equal(expected, options.Discover); } - - [Fact] - public void ParseOptions_MultipleEnvValuesBeforeStdio_SelectsStdio() - { - var options = new DevProxyConfigOptions(); - options.ParseOptions(["--env", "A=1", "B=2", "stdio", "node", "server.js"]); - - Assert.True(options.IsStdioMode); - Assert.Equal(new Dictionary { ["A"] = "1", ["B"] = "2" }, options.Env); - } } diff --git a/DevProxy.Tests/LoggingConfigurationTests.cs b/DevProxy.Tests/LoggingConfigurationTests.cs index 18f367bb..7b10dd81 100644 --- a/DevProxy.Tests/LoggingConfigurationTests.cs +++ b/DevProxy.Tests/LoggingConfigurationTests.cs @@ -34,6 +34,21 @@ public void ConfigureDevProxyLogging_Interactive_HonorsShowTimestamps(bool showT Assert.False(options.IncludeFullTimestamps); } + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + public void ConfigureDevProxyLogging_UsesPlainOutputOnlyForSubcommands(bool isRootCommand, bool expectedPlainOutput) + { + using var configuration = new ConfigurationManager(); + var services = new ServiceCollection(); + services.AddLogging(builder => builder.ConfigureDevProxyLogging(configuration, new DevProxyConfigOptions(), isStdioCommand: false, isJwtCommand: false, isRootCommand)); + using var provider = services.BuildServiceProvider(); + + var options = provider.GetRequiredService>().Value; + + Assert.Equal(expectedPlainOutput, options.PlainOutput); + } + [Theory] [InlineData(LogLevel.Warning)] [InlineData(LogLevel.Error)] diff --git a/DevProxy.Tests/ProxyConsoleFormatterTests.cs b/DevProxy.Tests/ProxyConsoleFormatterTests.cs index 7948b9ef..0285cd6a 100644 --- a/DevProxy.Tests/ProxyConsoleFormatterTests.cs +++ b/DevProxy.Tests/ProxyConsoleFormatterTests.cs @@ -35,6 +35,22 @@ public void FinishedProcessingRequest_WriterThrows_ReleasesBufferedLines() Assert.DoesNotContain("https://first", output, StringComparison.Ordinal); } + [Theory] + [InlineData(LogLevel.Information, "Base URL: http://127.0.0.1:8897")] + [InlineData(LogLevel.Warning, "warning: Base URL: http://127.0.0.1:8897")] + [InlineData(LogLevel.Error, "error: Base URL: http://127.0.0.1:8897")] + [InlineData(LogLevel.Critical, "error: Base URL: http://127.0.0.1:8897")] + public void PlainOutput_WritesMessageWithoutLevelLabel(LogLevel level, string expected) + { + var formatter = new ProxyConsoleFormatter(Options.Create(new ProxyConsoleFormatterOptions { PlainOutput = true })); + using var writer = new StringWriter(CultureInfo.InvariantCulture); + var entry = new LogEntry(level, "Tests", new EventId(0), "Base URL: http://127.0.0.1:8897", null, (state, _) => state); + + formatter.Write(entry, null, writer); + + Assert.Equal(expected + Environment.NewLine, writer.ToString()); + } + private static void Write(ProxyConsoleFormatter formatter, IExternalScopeProvider scopeProvider, TextWriter writer, string message, MessageType type) { var log = new RequestLog(message, type, context: null); diff --git a/DevProxy/Commands/ConfigCommand.cs b/DevProxy/Commands/ConfigCommand.cs index f0e7b602..ed3e898d 100644 --- a/DevProxy/Commands/ConfigCommand.cs +++ b/DevProxy/Commands/ConfigCommand.cs @@ -111,6 +111,7 @@ internal static async Task RunValidateStandaloneAsync(string[] args) formatterOptions.IncludeScopes = false; formatterOptions.ShowSkipMessages = true; formatterOptions.ShowTimestamps = false; + formatterOptions.PlainOutput = true; }) .AddConsoleFormatter(formatterOptions => { diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 5ff34d65..4963e588 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -102,46 +102,11 @@ public static bool IsStdioCommand } } - // Detects the stdio subcommand rather than any argument equal to "stdio" - // (e.g. `jwt create --name stdio`). Tokens before the subcommand may only be - // options or their values. args excludes the program name. - internal static bool IsStdioSubcommand(string[] args) - { - var inMultiValueOption = false; - for (var i = 0; i < args.Length; i++) - { - if (string.Equals(args[i], "stdio", StringComparison.Ordinal)) - { - return true; - } - - if (args[i].StartsWith('-', StringComparison.Ordinal)) - { - inMultiValueOption = _multiValueRootOptions.Contains(args[i]); - continue; - } - - var isOptionValue = inMultiValueOption || (i > 0 && args[i - 1].StartsWith('-', StringComparison.Ordinal)); - if (!isOptionValue) - { - return false; - } - } - - return false; - } - - // Root options that accept multiple values per token, so every value - // following them precedes the subcommand. - private static readonly HashSet _multiValueRootOptions = - [ - EnvOptionName, - "-e", - UrlsToWatchOptionName, - "-u", - WatchPidsOptionName, - WatchProcessNamesOptionName - ]; + // Subcommands must be the first argument (see GetLeadingOptionsError), so an + // argument equal to "stdio" elsewhere (e.g. `jwt create --name stdio`) isn't + // the subcommand. args excludes the program name. + internal static bool IsStdioSubcommand(string[] args) => + args.Length > 0 && string.Equals(args[0], "stdio", StringComparison.Ordinal); public static bool IsJwtCommand { @@ -176,9 +141,8 @@ public static bool IsConfigValidateCommand } /// - /// Returns true when args invoke 'validate' or 'config validate', allowing - /// global options (like --output) before the command. Help is excluded so - /// it's rendered by the full command tree. + /// Returns true when args invoke 'validate' or 'config validate'. Help is + /// excluded so it's rendered by the full command tree. /// internal static bool IsValidateInvocation(string[] args) { @@ -187,38 +151,14 @@ internal static bool IsValidateInvocation(string[] args) return false; } - var commandTokens = new List(2); - for (var i = 0; i < args.Length && commandTokens.Count < 2; i++) + return args switch { - var arg = args[i]; - if (string.Equals(arg, OutputOptionName, StringComparison.OrdinalIgnoreCase) || - string.Equals(arg, LogLevelOptionName, StringComparison.OrdinalIgnoreCase)) - { - i++; - continue; - } - if (arg.StartsWith(OutputOptionName + "=", StringComparison.OrdinalIgnoreCase) || - arg.StartsWith(OutputOptionName + ":", StringComparison.OrdinalIgnoreCase) || - arg.StartsWith(LogLevelOptionName + "=", StringComparison.OrdinalIgnoreCase) || - arg.StartsWith(LogLevelOptionName + ":", StringComparison.OrdinalIgnoreCase) || - string.Equals(arg, NoColorOptionName, StringComparison.OrdinalIgnoreCase) || - (commandTokens.Count > 0 && arg.StartsWith('-', StringComparison.Ordinal))) - { - continue; - } - if (arg.StartsWith('-', StringComparison.Ordinal)) - { - // other root options may take values, so we can't tell what follows - break; - } - commandTokens.Add(arg); - } - - return commandTokens.Count > 0 && - (string.Equals(commandTokens[0], "validate", StringComparison.OrdinalIgnoreCase) || - (commandTokens.Count > 1 && - string.Equals(commandTokens[0], "config", StringComparison.OrdinalIgnoreCase) && - string.Equals(commandTokens[1], "validate", StringComparison.OrdinalIgnoreCase))); + [var command, ..] when string.Equals(command, "validate", StringComparison.OrdinalIgnoreCase) => true, + [var command, var subcommand, ..] => + string.Equals(command, "config", StringComparison.OrdinalIgnoreCase) && + string.Equals(subcommand, "validate", StringComparison.OrdinalIgnoreCase), + _ => false + }; } public static bool IsPluginCommand @@ -231,30 +171,7 @@ public static bool IsPluginCommand } var args = Environment.GetCommandLineArgs(); - // skip global options supported by the standalone plugin command - // so that e.g. `devproxy --output json plugin list` is detected too - var i = 1; - while (i < args.Length) - { - if (string.Equals(args[i], OutputOptionName, StringComparison.OrdinalIgnoreCase) || - string.Equals(args[i], LogLevelOptionName, StringComparison.OrdinalIgnoreCase)) - { - i += 2; - } - else if (args[i].StartsWith($"{OutputOptionName}=", StringComparison.OrdinalIgnoreCase) || - args[i].StartsWith($"{OutputOptionName}:", StringComparison.OrdinalIgnoreCase) || - args[i].StartsWith($"{LogLevelOptionName}=", StringComparison.OrdinalIgnoreCase) || - args[i].StartsWith($"{LogLevelOptionName}:", StringComparison.OrdinalIgnoreCase) || - string.Equals(args[i], NoColorOptionName, StringComparison.OrdinalIgnoreCase)) - { - i++; - } - else - { - break; - } - } - field = i < args.Length && string.Equals(args[i], "plugin", StringComparison.OrdinalIgnoreCase); + field = args.Length > 1 && string.Equals(args[1], "plugin", StringComparison.OrdinalIgnoreCase); _isPluginCommandResolved = true; return field; } @@ -278,8 +195,8 @@ public static bool IsDetachedMode /// /// Determines if the root command (proxy itself) is being invoked. - /// Returns true when no subcommand is specified (only options or no args). - /// A subcommand is detected when the first non-program argument doesn't start with '-'. + /// Subcommands must be the first argument (enforced by GetLeadingOptionsError), + /// so it's the root command when there are no arguments or the first one is an option. /// public static bool IsRootCommand { @@ -412,6 +329,19 @@ public async Task InvokeAsync(string[] args, WebApplication app) ? StdioCommand.ParseStdioArgs(this, args) : Parse(args); + if (GetLeadingOptionsError(parseResult, args) is { } leadingOptionsError) + { + if (IsJsonOutputRequested(parseResult)) + { + WriteJsonErrors([leadingOptionsError]); + } + else + { + _logger.LogError("{ParseError}", leadingOptionsError); + } + return 2; + } + if (parseResult.Action is ParseErrorAction parseErrorAction) { if (IsJsonOutputRequested(parseResult)) @@ -468,7 +398,33 @@ internal static bool IsJsonOutputRequested(ParseResult parseResult) => parseResult.GetResult(OutputOptionName) is OptionResult { Tokens: [var token, ..] } && string.Equals(token.Value, nameof(OutputFormat.Json), StringComparison.OrdinalIgnoreCase); - internal static void WriteJsonParseErrors(ParseResult parseResult) + // Subcommands must be the first argument. This lets the root command be + // detected from the first argument (see IsRootCommand) before plugins, + // which can contribute their own subcommands, are loaded. + internal static string? GetLeadingOptionsError(ParseResult parseResult, string[] args) + { + if (args.Length == 0 || + !args[0].StartsWith('-', StringComparison.Ordinal) || + parseResult.CommandResult.Command is RootCommand) + { + return null; + } + + var commandPath = new List(); + for (SymbolResult? result = parseResult.CommandResult; + result is CommandResult { Command: not RootCommand } commandResult; + result = result.Parent) + { + commandPath.Insert(0, commandResult.Command.Name); + } + + return $"Options must follow the subcommand. Use: devproxy {string.Join(' ', commandPath)} [options]"; + } + + internal static void WriteJsonParseErrors(ParseResult parseResult) => + WriteJsonErrors(parseResult.Errors.Select(e => e.Message)); + + private static void WriteJsonErrors(IEnumerable errors) { // Usage errors must still be visible when normal logging is disabled, // for example by the jwt command or --log-level None. @@ -482,9 +438,9 @@ internal static void WriteJsonParseErrors(ParseResult parseResult) .AddConsoleFormatter()); var logger = loggerFactory.CreateLogger(); - foreach (var error in parseResult.Errors) + foreach (var error in errors) { - logger.LogError("{ParseError}", error.Message); + logger.LogError("{ParseError}", error); } } diff --git a/DevProxy/Commands/PluginCommand.cs b/DevProxy/Commands/PluginCommand.cs index 0583f618..3f8a3110 100644 --- a/DevProxy/Commands/PluginCommand.cs +++ b/DevProxy/Commands/PluginCommand.cs @@ -75,6 +75,7 @@ internal static async Task RunStandaloneAsync(string[] args) .AddConsoleFormatter(formatterOptions => { formatterOptions.ShowTimestamps = false; + formatterOptions.PlainOutput = true; }) .AddConsoleFormatter(formatterOptions => { diff --git a/DevProxy/Extensions/ILoggingBuilderExtensions.cs b/DevProxy/Extensions/ILoggingBuilderExtensions.cs index f3017194..5b2f3917 100644 --- a/DevProxy/Extensions/ILoggingBuilderExtensions.cs +++ b/DevProxy/Extensions/ILoggingBuilderExtensions.cs @@ -110,8 +110,8 @@ internal static ILoggingBuilder ConfigureDevProxyLogging( return builder; } - // For other subcommands (cert, config, outdated, msgraphdb), use rich logging - // but with plugin messages filtered out + // For other subcommands (cert, config, outdated, msgraphdb), use plain + // logging without level labels, with plugin messages filtered out // Structured results are logged at Information. When JSON output is // requested with a higher log level, let Information through the @@ -138,6 +138,7 @@ internal static ILoggingBuilder ConfigureDevProxyLogging( formatterOptions.IncludeScopes = true; formatterOptions.ShowSkipMessages = showSkipMessages; formatterOptions.ShowTimestamps = showTimestamps; + formatterOptions.PlainOutput = true; } ) .AddConsoleFormatter(formatterOptions => diff --git a/DevProxy/Logging/ProxyConsoleFormatter.cs b/DevProxy/Logging/ProxyConsoleFormatter.cs index e74cc844..57a6343b 100644 --- a/DevProxy/Logging/ProxyConsoleFormatter.cs +++ b/DevProxy/Logging/ProxyConsoleFormatter.cs @@ -196,11 +196,18 @@ private void WriteMessageWithLabel(string? message, string category, LogLevel lo return; } - var label = GetLogLevelString(logLevel); - var (bgColor, fgColor) = GetLogLevelColor(logLevel); + if (_options.PlainOutput) + { + textWriter.Write(GetPlainPrefix(logLevel)); + } + else + { + var label = GetLogLevelString(logLevel); + var (bgColor, fgColor) = GetLogLevelColor(logLevel); - WriteLabel(textWriter, label, bgColor, fgColor); - textWriter.Write($"{_labelSpacing}{_boxSpacing}"); + WriteLabel(textWriter, label, bgColor, fgColor); + textWriter.Write($"{_labelSpacing}{_boxSpacing}"); + } if (_options.IncludeFullTimestamps) { @@ -297,6 +304,15 @@ private void WriteScopes(IExternalScopeProvider? scopeProvider, TextWriter textW private static string GetLogLevelString(LogLevel logLevel) => _logLevelStrings.TryGetValue(logLevel, out var str) ? str : throw new ArgumentOutOfRangeException(nameof(logLevel)); + private static string GetPlainPrefix(LogLevel logLevel) => logLevel switch + { + LogLevel.Trace => "trace: ", + LogLevel.Debug => "debug: ", + LogLevel.Warning => "warning: ", + LogLevel.Error or LogLevel.Critical => "error: ", + _ => "" + }; + private static (ConsoleColor bg, ConsoleColor fg) GetLogLevelColor(LogLevel logLevel) => _logLevelColors.TryGetValue(logLevel, out var color) ? color : (Console.BackgroundColor, Console.ForegroundColor); diff --git a/DevProxy/Logging/ProxyConsoleFormatterOptions.cs b/DevProxy/Logging/ProxyConsoleFormatterOptions.cs index 161b1f38..630aa4f4 100644 --- a/DevProxy/Logging/ProxyConsoleFormatterOptions.cs +++ b/DevProxy/Logging/ProxyConsoleFormatterOptions.cs @@ -15,6 +15,10 @@ sealed class ProxyConsoleFormatterOptions : ConsoleFormatterOptions public bool IncludeFullTimestamps { get; set; } + // Writes regular messages without level labels, for commands other than + // the root command. Messages other than information get a short prefix. + public bool PlainOutput { get; set; } + // Minimum level for diagnostic messages. Structured output (command // results) is always written regardless of this level. public LogLevel MinimumLogLevel { get; set; } = LogLevel.Trace; From 58384bb17cc8f043221ef2369993358f2621bdc2 Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 28 Nov 2026 09:31:55 +0100 Subject: [PATCH 2/8] Address review feedback - Allow recursive options between 'config' and 'validate' for standalone validation - Show the options-order error regardless of the configured log level Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/ConfigValidateTests.cs | 4 ++ DevProxy/Commands/DevProxyCommand.cs | 70 +++++++++++++++++---------- 2 files changed, 49 insertions(+), 25 deletions(-) diff --git a/DevProxy.Tests/ConfigValidateTests.cs b/DevProxy.Tests/ConfigValidateTests.cs index 05d992b6..887b585a 100644 --- a/DevProxy.Tests/ConfigValidateTests.cs +++ b/DevProxy.Tests/ConfigValidateTests.cs @@ -389,12 +389,16 @@ public async Task AcceptsCaseInsensitiveKeyCollisionsInYaml() [InlineData(new[] { "validate", "--help" }, false)] [InlineData(new[] { "config", "get", "validate" }, false)] [InlineData(new[] { "--config-file", "validate" }, false)] + [InlineData(new[] { "config", "--output", "json", "validate" }, true)] + [InlineData(new[] { "config", "--no-color", "--log-level:Warning", "validate" }, true)] + [InlineData(new[] { "config", "--output", "validate" }, false)] public void DetectsValidateInvocation(string[] args, bool expected) => Assert.Equal(expected, DevProxyCommand.IsValidateInvocation(args)); [Theory] [InlineData(new[] { "validate", "--config-file=my.json" }, "my.json")] [InlineData(new[] { "config", "validate", "--output", "json", "-c", "my.json" }, "my.json")] + [InlineData(new[] { "config", "--output", "json", "validate", "-c", "my.json" }, "my.json")] public void ParsesValidateArgs(string[] args, string expectedConfigFile) { var parseResult = ConfigCommand.ParseValidateArgs(args, out var configFileOptions, out _); diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 4963e588..75c897e3 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -151,14 +151,36 @@ internal static bool IsValidateInvocation(string[] args) return false; } - return args switch + if (args.Length == 0) { - [var command, ..] when string.Equals(command, "validate", StringComparison.OrdinalIgnoreCase) => true, - [var command, var subcommand, ..] => - string.Equals(command, "config", StringComparison.OrdinalIgnoreCase) && - string.Equals(subcommand, "validate", StringComparison.OrdinalIgnoreCase), - _ => false - }; + return false; + } + if (string.Equals(args[0], "validate", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + if (!string.Equals(args[0], "config", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + // Recursive options are allowed between 'config' and 'validate' + for (var i = 1; i < args.Length; i++) + { + var arg = args[i]; + if (string.Equals(arg, OutputOptionName, StringComparison.OrdinalIgnoreCase) || + string.Equals(arg, LogLevelOptionName, StringComparison.OrdinalIgnoreCase)) + { + i++; + continue; + } + if (arg.StartsWith('-', StringComparison.Ordinal)) + { + continue; + } + return string.Equals(arg, "validate", StringComparison.OrdinalIgnoreCase); + } + return false; } public static bool IsPluginCommand @@ -331,14 +353,7 @@ public async Task InvokeAsync(string[] args, WebApplication app) if (GetLeadingOptionsError(parseResult, args) is { } leadingOptionsError) { - if (IsJsonOutputRequested(parseResult)) - { - WriteJsonErrors([leadingOptionsError]); - } - else - { - _logger.LogError("{ParseError}", leadingOptionsError); - } + WriteErrors([leadingOptionsError], IsJsonOutputRequested(parseResult)); return 2; } @@ -422,20 +437,25 @@ internal static bool IsJsonOutputRequested(ParseResult parseResult) => } internal static void WriteJsonParseErrors(ParseResult parseResult) => - WriteJsonErrors(parseResult.Errors.Select(e => e.Message)); + WriteErrors(parseResult.Errors.Select(e => e.Message), json: true); - private static void WriteJsonErrors(IEnumerable errors) + private static void WriteErrors(IEnumerable errors, bool json) { // Usage errors must still be visible when normal logging is disabled, // for example by the jwt command or --log-level None. - using var loggerFactory = LoggerFactory.Create(builder => builder - .SetMinimumLevel(LogLevel.Error) - .AddConsole(options => - { - options.FormatterName = JsonConsoleFormatter.FormatterName; - options.LogToStandardErrorThreshold = LogLevel.Error; - }) - .AddConsoleFormatter()); + using var loggerFactory = LoggerFactory.Create(builder => + { + _ = builder + .SetMinimumLevel(LogLevel.Error) + .AddConsole(options => + { + options.FormatterName = json ? JsonConsoleFormatter.FormatterName : ProxyConsoleFormatter.DefaultCategoryName; + options.LogToStandardErrorThreshold = LogLevel.Error; + }); + _ = json + ? builder.AddConsoleFormatter() + : builder.AddConsoleFormatter(options => options.PlainOutput = true); + }); var logger = loggerFactory.CreateLogger(); foreach (var error in errors) From 96202dbf4f5e6ed53b30a2a2195d78d6131909e9 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 13:37:11 +0100 Subject: [PATCH 3/8] Accept --config-file after plugin-provided subcommands Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/DevProxyCommandTests.cs | 25 + DevProxy.Tests/DevProxyConfigOptionsTests.cs | 9 + DevProxy/Commands/DevProxyCommand.cs | 2194 +++++++++--------- 3 files changed, 1145 insertions(+), 1083 deletions(-) diff --git a/DevProxy.Tests/DevProxyCommandTests.cs b/DevProxy.Tests/DevProxyCommandTests.cs index 0f8e3e99..2d13a539 100644 --- a/DevProxy.Tests/DevProxyCommandTests.cs +++ b/DevProxy.Tests/DevProxyCommandTests.cs @@ -90,4 +90,29 @@ public void GetLeadingOptionsError_RejectsOptionsBeforeSubcommand(string? expect Assert.Contains($"devproxy {expectedCommandPath} [options]", error, StringComparison.Ordinal); } } + + [Theory] + [InlineData("mocks", "from-http-responses", "r.http", "-c", "mocks.json")] + [InlineData("mocks", "--config-file", "mocks.json", "from-http-responses", "r.http")] + public void AddConfigFileOption_AcceptsConfigFileAfterPluginSubcommand(params string[] args) + { + var mocksCommand = new Command("mocks") { new Command("from-http-responses") { new Argument("files") } }; + DevProxyCommand.AddConfigFileOption(mocksCommand, _ => { }); + var rootCommand = new RootCommand { mocksCommand }; + + var parseResult = rootCommand.Parse(args); + + Assert.Empty(parseResult.Errors); + Assert.Equal("mocks.json", parseResult.GetValue(DevProxyCommand.ConfigFileOptionName)); + } + + [Fact] + public void AddConfigFileOption_KeepsPluginDeclaredOption() + { + var pluginOption = new Option("--count", "-c"); + var mocksCommand = new Command("mocks") { new Command("from-http-responses") { pluginOption } }; + DevProxyCommand.AddConfigFileOption(mocksCommand, _ => { }); + + Assert.Empty(mocksCommand.Options); + } } diff --git a/DevProxy.Tests/DevProxyConfigOptionsTests.cs b/DevProxy.Tests/DevProxyConfigOptionsTests.cs index b4a17313..d01c376f 100644 --- a/DevProxy.Tests/DevProxyConfigOptionsTests.cs +++ b/DevProxy.Tests/DevProxyConfigOptionsTests.cs @@ -23,4 +23,13 @@ public void Discover_ParsesOptionalValue(string[] args, bool expected) Assert.Equal(expected, options.Discover); } + + [Fact] + public void ParseOptions_ReadsConfigFileAfterPluginSubcommand() + { + var options = new DevProxyConfigOptions(); + options.ParseOptions(["mocks", "from-http-responses", "r.http", "--mocks-file", "out.json", "-c", "mocks.json"]); + + Assert.Equal(Path.GetFullPath("mocks.json"), options.ConfigFile); + } } diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 56c69840..5c9a0e34 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -1,1083 +1,1111 @@ -using DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Abstractions.Utils; -using DevProxy.Logging; -using DevProxy.Proxy; -using DevProxy.Proxy.Kestrel; -using DevProxy.State; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.AspNetCore.Hosting.Server.Features; -using System.CommandLine; -using System.CommandLine.Help; -using System.CommandLine.Invocation; -using System.CommandLine.Parsing; -using System.Globalization; - -namespace DevProxy.Commands; - -sealed class DevProxyCommand : RootCommand -{ - private readonly IServiceProvider _serviceProvider; - private readonly IEnumerable _plugins; - private readonly ILogger _logger; - private readonly IProxyConfiguration _proxyConfiguration; - private readonly ISet _urlsToWatch; - private readonly UpdateNotification _updateNotification; - private WebApplication? _app; - - internal static readonly TimeSpan NewVersionCheckTimeout = TimeSpan.FromSeconds(5); - - internal const string PortOptionName = "--port"; - internal const string ApiPortOptionName = "--api-port"; - internal const string ApiIpAddressOptionName = "--api-ip-address"; - internal const string IpAddressOptionName = "--ip-address"; - internal const string LogLevelOptionName = "--log-level"; - internal const string RecordOptionName = "--record"; - internal const string ReportDirOptionName = "--report-dir"; - internal const string WatchPidsOptionName = "--watch-pids"; - internal const string WatchProcessNamesOptionName = "--watch-process-names"; - internal const string WatchProcessTreeOptionName = "--watch-process-tree"; - internal const string ConfigFileOptionName = "--config-file"; - internal static readonly Option ConfigFileOption = new(ConfigFileOptionName, "-c") - { - HelpName = "config-file", - Description = "Path to config file. If not specified, Dev Proxy searches for devproxyrc.jsonc or devproxyrc.json in the current directory, then in a .devproxy/ directory, then under the ~appFolder location. Supports ~appFolder and ~dataFolder tokens, and a leading ~/ for the home directory." - }; - internal const string NoFirstRunOptionName = "--no-first-run"; - internal const string NoWatchOptionName = "--no-watch"; - internal const string AsSystemProxyOptionName = "--as-system-proxy"; - internal const string InstallCertOptionName = "--install-cert"; - internal const string UrlsToWatchOptionName = "--urls-to-watch"; - internal const string TimeoutOptionName = "--timeout"; - internal const string DiscoverOptionName = "--discover"; - internal const string EnvOptionName = "--env"; - internal const string OutputOptionName = "--output"; - internal const string DetachedOptionName = "--detach"; - internal const string InternalDaemonOptionName = "--_internal-daemon"; - internal const string NoColorOptionName = "--no-color"; - - private static readonly string[] globalOptions = ["--version"]; - private static readonly string[] helpOptions = ["--help", "-h", "/h", "-?", "/?"]; - - private static bool _hasGlobalOptionsResolved; - private static bool _isStdioCommandResolved; - private static bool _isJwtCommandResolved; - private static bool _isRootCommandResolved; - private static bool _isConfigValidateCommandResolved; - private static bool _isPluginCommandResolved; - private static bool _isDetachedModeResolved; - private static bool _isInternalDaemonResolved; - private static bool _stdioLogFilePathResolved; - private static bool _detachedLogFilePathResolved; - - public static bool HasGlobalOptions - { - get - { - if (_hasGlobalOptionsResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Any(arg => globalOptions.Contains(arg)) || - args.Any(arg => helpOptions.Contains(arg)); - _hasGlobalOptionsResolved = true; - return field; - } - } - - public static bool IsStdioCommand - { - get - { - if (_isStdioCommandResolved) - { - return field; - } - - field = IsStdioSubcommand(Environment.GetCommandLineArgs()[1..]); - _isStdioCommandResolved = true; - return field; - } - } - - // Subcommands must be the first argument (see GetLeadingOptionsError), so an - // argument equal to "stdio" elsewhere (e.g. `jwt create --name stdio`) isn't - // the subcommand. args excludes the program name. - internal static bool IsStdioSubcommand(string[] args) => - args.Length > 0 && string.Equals(args[0], "stdio", StringComparison.Ordinal); - - public static bool IsJwtCommand - { - get - { - if (_isJwtCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Length > 1 && string.Equals(args[1], "jwt", StringComparison.OrdinalIgnoreCase); - _isJwtCommandResolved = true; - return field; - } - } - - public static bool IsConfigValidateCommand - { - get - { - if (_isConfigValidateCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = IsValidateInvocation(args.Skip(1).ToArray()); - _isConfigValidateCommandResolved = true; - return field; - } - } - - /// - /// Returns true when args invoke 'validate' or 'config validate'. Help is - /// excluded so it's rendered by the full command tree. - /// - internal static bool IsValidateInvocation(string[] args) - { - if (args.Any(arg => helpOptions.Contains(arg))) - { - return false; - } - - if (args.Length == 0) - { - return false; - } - if (string.Equals(args[0], "validate", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - if (!string.Equals(args[0], "config", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - // Recursive options are allowed between 'config' and 'validate' - for (var i = 1; i < args.Length; i++) - { - var arg = args[i]; - if (string.Equals(arg, OutputOptionName, StringComparison.OrdinalIgnoreCase) || - string.Equals(arg, LogLevelOptionName, StringComparison.OrdinalIgnoreCase)) - { - i++; - continue; - } - if (arg.StartsWith('-', StringComparison.Ordinal)) - { - continue; - } - return string.Equals(arg, "validate", StringComparison.OrdinalIgnoreCase); - } - return false; - } - - public static bool IsPluginCommand - { - get - { - if (_isPluginCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Length > 1 && string.Equals(args[1], "plugin", StringComparison.OrdinalIgnoreCase); - _isPluginCommandResolved = true; - return field; - } - } - - public static bool IsDetachedMode - { - get - { - if (_isDetachedModeResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Contains("--detach") || args.Contains("-d"); - _isDetachedModeResolved = true; - return field; - } - } - - /// - /// Determines if the root command (proxy itself) is being invoked. - /// Subcommands must be the first argument (enforced by GetLeadingOptionsError), - /// so it's the root command when there are no arguments or the first one is an option. - /// - public static bool IsRootCommand - { - get - { - if (_isRootCommandResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - // Skip the first argument which is the program name - // If there are no more arguments, it's the root command - // If the first argument starts with '-', it's an option (root command) - // Otherwise, it's a subcommand name - field = args.Length <= 1 || args[1].StartsWith('-', StringComparison.Ordinal); - _isRootCommandResolved = true; - return field; - } - } - - public static bool IsInternalDaemon - { - get - { - if (_isInternalDaemonResolved) - { - return field; - } - - var args = Environment.GetCommandLineArgs(); - field = args.Contains("--_internal-daemon"); - _isInternalDaemonResolved = true; - return field; - } - } - - public static string StdioLogFilePath - { - get - { - if (_stdioLogFilePathResolved) - { - return field ?? string.Empty; - } - - field = Path.Combine( - Directory.GetCurrentDirectory(), - $"devproxy-stdio-{DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)}.log"); - _stdioLogFilePathResolved = true; - return field; - } - } - - public static string DetachedLogFilePath - { - get - { - if (_detachedLogFilePathResolved) - { - return field ?? string.Empty; - } - - field = State.StateManager.GenerateLogFilePath(); - _detachedLogFilePathResolved = true; - return field; - } - } - - public static bool NoColor => ShouldDisableColor( - Environment.GetCommandLineArgs(), - Environment.GetEnvironmentVariable("NO_COLOR"), - Environment.GetEnvironmentVariable("TERM")); - - internal static string ResolveReportDirOption(string value) => - Path.GetFullPath(ProxyUtils.ReplacePathTokens(value)); - - internal static void ValidateReportDir(OptionResult input) - { - if (input.Tokens.Count == 0) - { - input.AddError("The report directory path is missing. Specify a folder."); - return; - } - - var value = input.Tokens[0].Value; - if (string.IsNullOrWhiteSpace(value)) - { - input.AddError("The report directory path can't be empty."); - return; - } - - if (File.Exists(ResolveReportDirOption(value))) - { - input.AddError($"The report directory path '{value}' points to a file. Specify a folder."); - } - } - - // Per https://no-color.org, NO_COLOR disables color only when present and not empty. - internal static bool ShouldDisableColor(string[] args, string? noColorEnv, string? termEnv) => - args.Contains(NoColorOptionName) || - !string.IsNullOrEmpty(noColorEnv) || - string.Equals(termEnv, "dumb", StringComparison.OrdinalIgnoreCase); - - public DevProxyCommand( - IEnumerable plugins, - ISet urlsToWatch, - IProxyConfiguration proxyConfiguration, - IServiceProvider serviceProvider, - UpdateNotification updateNotification, - DevProxyConfigOptions options, - ILogger logger) : base($"Start Dev Proxy\n\nAPI:\n Dev Proxy exposes an authenticated REST API for runtime management.\n Use --api-port (default: {proxyConfiguration.ApiPort}) and --api-ip-address (default: 127.0.0.1).\n The API bind address is independent of --ip-address.\n Run 'devproxy status' for the API URL and token, or 'devproxy api show' for endpoints\n ('devproxy api show --output json' includes request and response schemas).\n Set the DEV_PROXY_API_TOKEN environment variable (at least 32 characters) to use a fixed API token instead of a generated one.") - { - _serviceProvider = serviceProvider; - _plugins = plugins; - _urlsToWatch = urlsToWatch; - _proxyConfiguration = proxyConfiguration; - _updateNotification = updateNotification; - _logger = logger; - - ConfigureCommand(options); - } - - public async Task InvokeAsync(string[] args, WebApplication app) - { - _app = app; - // Use special parsing for stdio command to disable response file expansion (@file) - // This allows npm package names like @devproxy/mcp to be passed through literally - var parseResult = IsStdioCommand - ? StdioCommand.ParseStdioArgs(this, args) - : Parse(args); - - if (GetLeadingOptionsError(parseResult, args) is { } leadingOptionsError) - { - WriteErrors([leadingOptionsError], IsJsonOutputRequested(parseResult)); - return 2; - } - - if (parseResult.Action is ParseErrorAction parseErrorAction) - { - if (IsJsonOutputRequested(parseResult)) - { - WriteJsonParseErrors(parseResult); - return 2; - } - - parseErrorAction.ShowHelp = false; - } - - var exitCode = await parseResult.InvokeAsync(null, app.Lifetime.ApplicationStopping); - - // Return exit code 2 for input validation and parse errors to distinguish - // them from runtime errors (exit code 1), following conventions from - // curl, git, and others - if (exitCode != 0 && parseResult.Errors.Count > 0) - { - return 2; - } - - return exitCode; - } - - internal static Option CreateInstallCertOption(Option asSystemProxyOption, IProxyConfiguration proxyConfiguration) - { - var installCertOption = new Option(InstallCertOptionName) - { - Description = "Install and trust the root certificate (default: true, false when CI is set). On Linux, trust it manually", - HelpName = "true|false" - }; - installCertOption.Validators.Add(input => - { - try - { - var asSystemProxy = input.GetValue(asSystemProxyOption) ?? proxyConfiguration.AsSystemProxy; - var installCert = input.GetValue(installCertOption) ?? proxyConfiguration.InstallCert; - if (asSystemProxy && !installCert) - { - input.AddError($"Requires option '{AsSystemProxyOptionName}' to be 'false'"); - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - return installCertOption; - } - - // Reads the raw token rather than the parsed value, because the parsed - // value isn't available when the parse result has errors - internal static bool IsJsonOutputRequested(ParseResult parseResult) => - parseResult.GetResult(OutputOptionName) is OptionResult { Tokens: [var token, ..] } && - string.Equals(token.Value, nameof(OutputFormat.Json), StringComparison.OrdinalIgnoreCase); - - // Subcommands must be the first argument. This lets the root command be - // detected from the first argument (see IsRootCommand) before plugins, - // which can contribute their own subcommands, are loaded. - internal static string? GetLeadingOptionsError(ParseResult parseResult, string[] args) - { - if (args.Length == 0 || - !args[0].StartsWith('-', StringComparison.Ordinal) || - parseResult.CommandResult.Command is RootCommand) - { - return null; - } - - var commandPath = new List(); - for (SymbolResult? result = parseResult.CommandResult; - result is CommandResult { Command: not RootCommand } commandResult; - result = result.Parent) - { - commandPath.Insert(0, commandResult.Command.Name); - } - - return $"Options must follow the subcommand. Use: devproxy {string.Join(' ', commandPath)} [options]"; - } - - internal static void WriteJsonParseErrors(ParseResult parseResult) => - WriteErrors(parseResult.Errors.Select(e => e.Message), json: true); - - private static void WriteErrors(IEnumerable errors, bool json) - { - // Usage errors must still be visible when normal logging is disabled, - // for example by the jwt command or --log-level None. - using var loggerFactory = LoggerFactory.Create(builder => - { - _ = builder - .SetMinimumLevel(LogLevel.Error) - .AddConsole(options => - { - options.FormatterName = json ? JsonConsoleFormatter.FormatterName : ProxyConsoleFormatter.DefaultCategoryName; - options.LogToStandardErrorThreshold = LogLevel.Error; - }); - _ = json - ? builder.AddConsoleFormatter() - : builder.AddConsoleFormatter(options => options.PlainOutput = true); - }); - var logger = loggerFactory.CreateLogger(); - - foreach (var error in errors) - { - logger.LogError("{ParseError}", error); - } - } - - internal static void ValidatePort(OptionResult input) - { - var value = input.Tokens.Count > 0 ? input.Tokens[0].Value : null; - if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var port) || port > System.Net.IPEndPoint.MaxPort) - { - input.AddError($"'{value}' is not a valid port. Specify a number between 0 and {System.Net.IPEndPoint.MaxPort}."); - } - } - - private async Task InvokeAsync(ParseResult parseResult, CancellationToken cancellationToken) - { - if (_app is null) - { - throw new InvalidOperationException("WebApplication instance is not set. Please provide it when invoking the command."); - } - // Environment overrides from config and --env are applied by now, so this - // validates and pins the effective token before anything reads it. - if (!ApiSecurity.TryInitializeToken(out var tokenError)) - { - _logger.LogError("{TokenError}", tokenError); - return 1; - } - if (!_plugins.Any()) - { - _logger.LogError("You haven't configured any plugins. Please add plugins to your configuration file. Dev Proxy will exit."); - return 1; - } - if (_urlsToWatch.Count == 0) - { - _logger.LogError("You haven't configured any URLs to watch. Please add URLs to your configuration file or use the --urls-to-watch option. Dev Proxy will exit."); - return 1; - } - - ConfigureFromOptions(parseResult); - - var portConflict = - await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, cancellationToken) ?? - await PortConflict.CheckAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, cancellationToken); - if (portConflict is not null) - { - _logger.LogError("{PortConflict}", portConflict); - return 1; - } - - var optionsLoadedArgs = new OptionsLoadedArgs(parseResult); - foreach (var plugin in _plugins.Where(p => p.Enabled)) - { - plugin.OptionsLoaded(optionsLoadedArgs); - } - - // Check for a new version in the background so that startup doesn't wait - // for the network. Linking to the command's token (the host's - // ApplicationStopping) cancels the check on shutdown and hot reload. - using var newVersionCheckCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - newVersionCheckCts.CancelAfter(NewVersionCheckTimeout); - var newVersionCheck = CheckForNewVersionInBackgroundAsync(_updateNotification, _proxyConfiguration.NewVersionNotification, _logger, newVersionCheckCts.Token); - - try - { - await ApiSecurity.SaveTokenAsync(cancellationToken); - await _app.StartAsync(cancellationToken); - - // The proxy binds in a background service, so wait for it before - // publishing readiness. Otherwise a detached launcher could report a - // successful start for a proxy that failed to bind. Don't pass the - // cancellation token: a bind failure stops the host, which would cancel - // the wait before the failure is reported. The engine always completes - // Started once the host stops. - var proxyEngines = _app.Services.GetServices().OfType().ToArray(); - var proxyStarted = (await Task.WhenAll(proxyEngines.Select(e => e.Started))).All(started => started); - if (!proxyStarted) - { - await _app.WaitForShutdownAsync(cancellationToken); - if (proxyEngines.Any(e => e.PortInUse)) - { - _logger.LogError("{PortConflict}", - await PortConflict.GetMessageAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, CancellationToken.None)); - } - return 1; - } - - var serverAddresses = _app.Services.GetRequiredService().Features.Get(); - var serverAddress = serverAddresses?.Addresses.FirstOrDefault(); - var address = ApiSecurity.GetApiUrl(serverAddress ?? - new UriBuilder(Uri.UriSchemeHttp, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort).Uri.AbsoluteUri); - _logger.LogInformation("Dev Proxy API listening on {Address}...", address); - - if (_proxyConfiguration.Output != OutputFormat.Json) - { - ApiSecurity.LogTokenOnce(_logger); - } - - if (!System.Net.IPAddress.IsLoopback(System.Net.IPAddress.Parse(_proxyConfiguration.ApiIpAddress))) - { - _logger.LogWarning("The Dev Proxy API is bound to {ApiIpAddress} off-loopback. Bearer tokens are sent over HTTP; use only on trusted networks or through a secure tunnel.", _proxyConfiguration.ApiIpAddress); - } - - await WriteInstanceStateAsync(address); - // Hotkeys write directly to the console, so release them after startup logging is complete. - _app.Services.GetRequiredService().CompleteStartupMessages(); - - await _app.WaitForShutdownAsync(cancellationToken); - - return 0; - } - catch (TaskCanceledException) - { - throw; - } - catch (Exception ex) when (PortConflict.IsAddressInUse(ex)) - { - // The API port was taken between the pre-flight check and binding. - _logger.LogError("{PortConflict}", - await PortConflict.GetMessageAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, CancellationToken.None)); - return 1; - } - catch (Exception ex) - { - _logger.LogError(ex, "An error occurred while running Dev Proxy"); - var inner = ex.InnerException; - - while (inner is not null) - { - _logger.LogError(inner, "============ Inner exception ============"); - inner = inner.InnerException; - } -#if DEBUG - throw; // so debug tools go straight to the source of the exception when attached -#else - return 1; -#endif - } - finally - { - // Stop the check before the host is disposed so that it doesn't use - // the disposed logger or HttpClient. The check never throws. - await newVersionCheckCts.CancelAsync(); - await newVersionCheck; - } - } - - private void ConfigureCommand(DevProxyConfigOptions configOptions) - { - ConfigFileOption.Validators.Clear(); - ConfigFileOption.Validators.Add(input => - { - var filePath = configOptions.ConfigFile ?? ProxyUtils.ReplacePathTokens(input.Tokens[0].Value); - if (string.IsNullOrEmpty(filePath)) - { - return; - } - - if (!File.Exists(filePath)) - { - input.AddError($"Configuration file '{filePath}' does not exist. Check the file path and try again."); - } - }); - - var ipAddressOption = new Option(IpAddressOptionName) - { - Description = "The IP address for the proxy to bind to", - HelpName = "ip-address" - }; - ipAddressOption.Validators.Add(input => - { - if (!System.Net.IPAddress.TryParse(input.Tokens[0].Value, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid IP address. Example: 127.0.0.1"); - } - }); - - var urlsToWatchOption = new Option?>(UrlsToWatchOptionName, "-u") - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore, - Description = "The list of URLs to watch for requests", - HelpName = "urls-to-watch", - }; - - var logLevelOption = new Option(LogLevelOptionName) - { - Description = $"Level of messages to log. Allowed values: {string.Join(", ", Enum.GetNames())}", - HelpName = "log-level", - Recursive = true - }; - logLevelOption.Validators.Add(input => - { - if (!Enum.TryParse(input.Tokens[0].Value, true, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid log level. Allowed values: {string.Join(", ", Enum.GetNames())}"); - } - }); - - var portOption = new Option(PortOptionName, "-p") - { - Description = "The port for the proxy to listen on", - HelpName = "port" - }; - portOption.Validators.Add(ValidatePort); - - var apiPortOption = new Option(ApiPortOptionName) - { - Description = "The port for the Dev Proxy API to listen on", - HelpName = "api-port" - }; - apiPortOption.Validators.Add(ValidatePort); - var apiIpAddressOption = new Option(ApiIpAddressOptionName) - { - Description = "The API bind address (default: 127.0.0.1). Use ::1 for IPv6 loopback. Non-loopback binding requires a trusted network", - HelpName = "api-ip-address" - }; - apiIpAddressOption.Validators.Add(input => - { - if (!System.Net.IPAddress.TryParse(input.Tokens[0].Value, out _)) - { - input.AddError("The API address must be an IP address, for example 127.0.0.1 or ::1."); - } - }); - - var recordOption = new Option(RecordOptionName) - { - Description = "Use this option to record all request logs" - }; - - var reportDirOption = new Option(ReportDirOptionName) - { - Description = "Folder where reporters write report files. Overrides reportsFolder from the config file. Relative paths resolve against the current working directory. Default: the current working directory", - HelpName = "path", - Arity = ArgumentArity.ExactlyOne - }; - reportDirOption.Validators.Add(ValidateReportDir); - - var watchPidsOption = new Option>(WatchPidsOptionName) - { - AllowMultipleArgumentsPerToken = true, - Description = "The IDs of processes to watch for requests", - HelpName = "pids" - }; - - var watchProcessNamesOption = new Option>(WatchProcessNamesOptionName) - { - AllowMultipleArgumentsPerToken = true, - Description = "The names of processes to watch for requests", - HelpName = "process-names", - }; - - var watchProcessTreeOption = new Option(WatchProcessTreeOptionName) - { - Description = "Also watch descendants of processes selected by --watch-pids or --watch-process-names" - }; - - var noFirstRunOption = new Option(NoFirstRunOptionName) - { - Description = "Skip the first run experience" - }; - - var noWatchOption = new Option(NoWatchOptionName) - { - Description = "Disable automatic restart on configuration file changes" - }; - - var discoverOption = new Option(DiscoverOptionName) - { - Description = "Run Dev Proxy in discovery mode" - }; - - var asSystemProxyOption = new Option(AsSystemProxyOptionName) - { - Description = "Register Dev Proxy as the system proxy (default: true, false when CI is set). See https://go.devproxy.net?go=system-proxy", - HelpName = "true|false" - }; - - var installCertOption = CreateInstallCertOption(asSystemProxyOption, _proxyConfiguration); - - var timeoutOption = new Option(TimeoutOptionName, "-t") - { - Description = "Time in seconds after which Dev Proxy exits. Resets when Dev Proxy intercepts a request.", - HelpName = "timeout" - }; - timeoutOption.Validators.Add(input => - { - try - { - if (!long.TryParse(input.Tokens[0].Value, out var timeoutInput) || timeoutInput < 1) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid timeout value. Specify a positive integer (in seconds)."); - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var envOption = new Option(EnvOptionName, "-e") - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore, - Description = "Environment variables to set for the Dev Proxy process, in name=value format. Also used to replace {name} placeholders in API spec files used by the MinimalPermissions plugins. Changes to HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, or NO_PROXY (including lowercase variants) require a full stop/start; hot reload cannot refresh cached HTTP proxy settings", - HelpName = "env", - }; - envOption.Validators.Add(input => - { - try - { - var envVars = input.GetValue(envOption); - if (envVars is null || envVars.Length == 0) - { - return; - } - - foreach (var envVar in envVars) - { - // Split on first '=' only - var parts = envVar.Split('=', 2); - if (parts.Length != 2 || parts[0].Length == 0) - { - input.AddError($"Invalid environment variable format: '{envVar}'. Expected format is 'name=value'."); - return; - } - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var outputOption = new Option(OutputOptionName) - { - Description = $"Output format. Allowed values: {string.Join(", ", Enum.GetNames())}", - HelpName = "format", - Recursive = true - }; - outputOption.Validators.Add(input => - { - if (input.Tokens.Count == 0) - { - return; - } - if (!Enum.TryParse(input.Tokens[0].Value, true, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid output format. Allowed values: {string.Join(", ", Enum.GetNames())}"); - } - }); - - var detachedOption = new Option(DetachedOptionName, "-d") - { - Description = "Run Dev Proxy in the background" - }; - - var internalDaemonOption = new Option(InternalDaemonOptionName) - { - Description = "Internal use only - do not use directly", - Hidden = true - }; - - var noColorOption = new Option(NoColorOptionName) - { - Description = "Disable colored output", - Arity = ArgumentArity.Zero, - Recursive = true - }; - - var options = new List