diff --git a/eng/Signing.props b/eng/Signing.props
index ece76bd27a7f..6e824aa724cd 100644
--- a/eng/Signing.props
+++ b/eng/Signing.props
@@ -45,7 +45,8 @@
-
+
+
diff --git a/src/Dotnet.Watch/AGENTS.md b/src/Dotnet.Watch/AGENTS.md
index c37caa661699..35b52969aa88 100644
--- a/src/Dotnet.Watch/AGENTS.md
+++ b/src/Dotnet.Watch/AGENTS.md
@@ -10,7 +10,7 @@ Reload).
| `dotnet-watch` | The tool executable and CLI surface. Its command/options are defined in `CommandLine/DotnetWatchCommandDefinition.cs`. |
| `Watch` (`Microsoft.DotNet.HotReload.Watch`) | Core watcher library: file-set computation, process launching, Hot Reload, app models. |
| `DotNetWatchTasks` | MSBuild task bundled into the tool for design-time file collection. |
-| `DotNetDeltaApplier`, `Web.Middleware`, `BrowserRefresh` | Assemblies **injected into the running app** via `DOTNET_STARTUP_HOOKS`. |
+| `DotNetDeltaApplier`, `Web.Middleware`, `BrowserRefresh` | Assemblies injected into compatible app models through the hosting-startup path. |
| `HotReloadAgent.*`, `HotReloadClient`, `AspireService` | Shared code consumed via `.projitems`.|
## Conventions & gotchas
@@ -26,6 +26,142 @@ Reload).
named-pipe protocol; Blazor WASM uses JSON over WebSocket. Each protocol has its
own `HotReloadClient` subclass (e.g. `DefaultHotReloadClient`,
`WebAssemblyHotReloadClient`); a new app model may need its own implementation.
+- **The browser-tools provider owns the browser protocol and replay
+ state.** Its fixed `/_framework/dotnet-browser-tools` endpoints live under
+ [`HotReloadClient/Web`](HotReloadClient/Web) and are reduced to `connect` (WebSocket)
+ `clear-cache`, and the non-executable `hot-reload-settings.json`; the provider serves no
+ JavaScript, no session descriptor, no protocol version, and no HTTP replay. Most
+ application hosts reach it through the
+ shared-framework-only [`BrowserToolsForwarder`](Web.Middleware/BrowserToolsForwarder.cs)
+ installed by the hosting-startup path. Standalone Blazor WebAssembly is the exception:
+ it is served by the Blazor Gateway, a separate YARP host that does not activate ASP.NET
+ Core hosting startups, so
+ [`BlazorWebAssemblyAppModel`](Watch/AppModels/BlazorWebAssemblyAppModel.cs) configures a
+ gateway reverse-proxy route through `ReverseProxy__*` environment variables instead. Keep
+ destinations fixed to the trusted loopback provider address, the route root-relative, and
+ the encrypted shared-secret WebSocket subprotocol intact. Do not add YARP to arbitrary
+ applications.
+- **The browser authenticates the provider, so the provider must not serve code.** The
+ *build* owns the browser-tools RSA keypair:
+ [`EnsureDotNetWatchBrowserToolsKey`](../StaticWebAssetsSdk/Tasks/EnsureDotNetWatchBrowserToolsKey.cs)
+ writes both halves to deterministic paths under the browser-facing project's intermediate
+ output, and
+ only the public half is pinned into an application-hosted configuration module. There is
+ no watch-to-MSBuild property flow: `dotnet watch` reads the private half back through
+ [`BrowserToolsBuildOutputs`](Watch/Browser/BrowserToolsBuildOutputs.cs) when each browser
+ connects. This lets the per-project provider bind before `dotnet run` builds the
+ application, avoids a separate watcher build, and observes key rotation after `Clean`.
+ The provider validates and imports the current matching pair only long enough to decrypt
+ that connection's credential, so a provider can never supply the key that authenticates
+ it. The existing `EnableHotReloadInRuntimeConfigDevFile` SDK property controls whether
+ the build generates the browser-tools assets and defaults to `true` for Debug builds.
+ When present, the initializer fetches the provider-owned
+ `/_framework/dotnet-browser-tools/hot-reload-settings.json` route and starts the client
+ only for `{ "hotReload": true }`; the response is non-executable, contains no key
+ material, and is served with `Cache-Control: no-store`. The ASP.NET Core disabled
+ fallback for non-watch launches is supplied by the runtime/host, not by the SDK or
+ `dotnet watch`. Watch never activates the client by mutating an application file. Hosted
+ WebAssembly uses the client as the browser-tools project even though the server remains
+ the launching project.
+ See
+ [`Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets`](../StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets).
+ Never move executable browser-tools code back into the provider, never let the private
+ key or the browser's shared secret reach a build property, an application asset or a log,
+ and keep the generated assets build only.
+- **Replay lives in the WebSocket handshake.** The provider sends the current snapshot as
+ the first message on an accepted connection and releases live messages for that
+ connection only after the browser acknowledges it, so there is no wire-level generation
+ id. The internal epoch in
+ [`AbstractBrowserRefreshServer`](HotReloadClient/Web/AbstractBrowserRefreshServer.cs)
+ exists only to drop work produced by a superseded client; do not surface it on the wire.
+- **Activation is app-model-specific, but the browser client is shared.** MVC and Razor
+ Pages use
+ [`BrowserRefreshTagHelperComponent`](Web.Middleware/BrowserRefreshTagHelperComponent.cs)
+ through the built-in body TagHelper; it never runs for `.razor` root components, so
+ Blazor apps rendered on the server rely on the Web SDK's build-only `afterWebStarted`
+ initializer instead. Standalone and hosted Blazor WASM use a build-only watch activation
+ initializer added by the WASM SDK for every supported target
+ framework; from `onRuntimeConfigLoaded` it sets the watch-private activation variable
+ `__DOTNET_WATCH_BROWSER_TOOLS` and `DOTNET_MODIFIABLE_ASSEMBLIES`, and from
+ `onRuntimeReady` it imports the application-hosted configuration module. Blazor guarantees
+ every `onRuntimeConfigLoaded`
+ callback runs before any `onRuntimeReady` callback and passes the same config object to
+ all initializers, so pass *activation state* between initializer modules through that
+ config rather
+ than through `globalThis` or a cross-module import: initializer load order is unspecified
+ and each module's URL is subject to fingerprinting. Do not use
+ `__ASPNETCORE_BROWSER_TOOLS` as that handshake, because .NET 8 interprets it as a request
+ to load the removed application-hosted `blazor-hotreload.js`. On .NET 10+ the
+ same WebAssembly watch initializer loads the SDK Hot Reload agent assembly and applies managed
+ updates; older target frameworks fall back to the runtime's own
+ `window.Blazor._internal.applyHotReload`. The configuration module may also be imported
+ by a host activation path; duplicate activation is absorbed by module caching and the
+ client's injection sentinel.
+ Static/custom HTML that has no supported
+ initializer requires user-provided activation; do not add build-time `index.html`
+ rewriting. Apps that disable `StaticWebAssetsEnabled` or `JSModulesEnabled` cannot host
+ the client and therefore cannot receive browser tools.
+- **The replay handshake waits for the Hot Reload agent through a `globalThis`
+ rendezvous.** The provider sends the replay snapshot exactly once, so applying it before
+ the agent is ready would drop those updates while the browser still acknowledged success.
+ The WebAssembly watch initializer publishes
+ `globalThis.__DOTNET_WATCH_HOT_RELOAD_AGENT = { ready, setReady }` before its first
+ `await`, attaches the SDK agent's apply functions directly to that shared object, and
+ resolves readiness in a `finally`; the browser tools client awaits it before replaying.
+ This is the one case that cannot use the runtime config object, because the value is a
+ promise that only exists once `onRuntimeReady` has started. Keep the rendezvous helpers in
+ the [WebAssembly initializer](../WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template)
+ and the Static Web Assets SDK's `dotnet-watch-browser-tools.js` in sync. The wait is
+ bounded and best effort for older runtimes that install the apply API through their own
+ bootstrap, or pages that never boot WebAssembly, so they degrade to a logged warning
+ instead of a reload loop.
+- **A browser that cannot apply an update must fail the acknowledgement.** `dotnet watch`
+ treats an acknowledged update as applied, so any path that answers with an empty log is
+ indistinguishable from a successful apply and produces "C# and Razor changes applied"
+ while nothing changed. [`WebAssemblyHotReload`](HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs)
+ therefore records why the agent was not created and throws that reason from
+ `ApplyHotReloadDeltas` instead of returning an empty log; the throw surfaces through
+ `[JSExport]`, the client reports `success: false`, and
+ [`RunningProjectsManager`](Watch/HotReload/RunningProjectsManager.cs) suppresses both the
+ applied message and the Aspire notification when any client's apply task failed. Replay is
+ the deliberate exception: an apply failure while initializing is logged as an error but
+ does not fail initialization, because the provider disposes a connection whose
+ initialization reported failure and the client reloads on close, which would loop.
+- **.NET 9 WebAssembly is the one target framework that needs
+ `__ASPNETCORE_BROWSER_TOOLS`.** Its `WebAssemblyHotReload` creates the Hot Reload agent
+ only inside `InitializeAsync`, which the runtime calls only when that variable is set, so
+ without it nothing is applied. The
+ [initializer template](../WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template)
+ therefore has a `__RUNTIME_HOT_RELOAD_AGENT__` placeholder that
+ [`Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets`](../StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets)
+ substitutes with `true` only when `TargetFrameworkVersion` equals `9.0`. .NET 8 must not
+ get it (it would import the removed `blazor-hotreload.js`) and .NET 10+ must not get it
+ (the SDK ships its own agent). That initialization path also fetches
+ `/_framework/blazor-hotreload` for previously applied deltas, so
+ [`HostingStartup`](Web.Middleware/HostingStartup.cs) answers that route locally with an
+ empty update array: replay belongs to the authenticated WebSocket, and serving deltas over
+ an unauthenticated route would be a security regression. The route is not forwarded to the
+ provider, and its only consumer is the .NET 9 WebAssembly runtime.
+- **The forwarder preserves the provider's pre-upgrade rejection.** The provider answers an
+ invalid encrypted subprotocol with a status-only HTTP 400 *before* accepting the
+ WebSocket. [`BrowserToolsForwarder`](Web.Middleware/BrowserToolsForwarder.cs) opts into
+ `ClientWebSocketOptions.CollectHttpResponseDetails` and, on a failed upgrade, relays
+ `ClientWebSocket.HttpStatusCode` only when it is an error status, falling back to 502
+ otherwise. The narrowing matters: that property is recorded before the upgrade response is
+ validated, so a handshake that failed *after* the provider switched protocols reports 101,
+ and relaying it would make the application announce an upgrade it never performed. Both
+ members are .NET 7+ while the
+ assembly targets `net6.0`, so they are reached through cached reflection. Do not widen this
+ into a blanket status mapping and do not swallow genuine transport failures.
+- **Server hosting startup is intentionally thin.**
+ [`HostingStartup.cs`](Web.Middleware/HostingStartup.cs) registers only the MVC/Razor
+ TagHelper component and the reserved forwarder for the modern path. The BrowserRefresh
+ assembly still appears in `DOTNET_STARTUP_HOOKS` so the out-of-application hosting
+ startup assembly can be resolved, but its
+ [`StartupHook`](Web.Middleware/StartupHook.cs) is a no-op. Managed server updates
+ continue to use the separate `Microsoft.Extensions.DotNetDeltaApplier` startup hook.
+ Do not restore response rewriting, application-hosted browser scripts, or parallel
+ legacy endpoints.
- **`CompilationHandler` drives Roslyn** via
`Microsoft.CodeAnalysis.ExternalAccess.HotReload`; unsupported edits fall
back to a full rebuild + restart.
diff --git a/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj b/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj
index 83bd8a6714d8..84f27d533080 100644
--- a/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj
+++ b/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj
@@ -13,7 +13,6 @@
-
diff --git a/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs b/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs
index c13a8f68b186..6547ef667a1e 100644
--- a/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs
+++ b/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs
@@ -34,15 +34,6 @@ public readonly struct LogEntry
public int Severity { get; init; }
}
- ///
- /// For framework use only.
- ///
- internal sealed class Update
- {
- public int Id { get; set; }
- public Delta[] Deltas { get; set; } = default!;
- }
-
///
/// For framework use only.
///
@@ -55,20 +46,34 @@ public readonly struct Delta
public int[] UpdatedTypes { get; init; }
}
- private static readonly JsonSerializerOptions s_jsonSerializerOptions = new(JsonSerializerDefaults.Web);
-
- private static bool s_initialized;
private static HotReloadAgent? s_hotReloadAgent;
+ ///
+ /// Why is null, so that a caller that asks for a managed code update
+ /// gets an actionable error instead of an update that is acknowledged but silently not applied.
+ ///
+ private static string? s_unavailableReason;
+
[JSExport]
[SupportedOSPlatform("browser")]
- public static async Task InitializeAsync(string baseUri)
+ public static Task InitializeAsync(string baseUri)
{
- if (MetadataUpdater.IsSupported && Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") == "true" &&
- OperatingSystem.IsBrowser())
+ if (!OperatingSystem.IsBrowser())
+ {
+ s_unavailableReason = "the runtime is not running in a browser";
+ }
+ else if (Environment.GetEnvironmentVariable("__DOTNET_WATCH_BROWSER_TOOLS") != "true")
+ {
+ s_unavailableReason = "the app was not started by 'dotnet watch'";
+ }
+ else if (!MetadataUpdater.IsSupported)
+ {
+ // Reached when the app was built without the runtime assets that support metadata updates,
+ // which happens with stale or mismatched build output. Applying an update would be a no-op.
+ s_unavailableReason = "this build of the app does not support runtime metadata updates (System.Reflection.Metadata.MetadataUpdater.IsSupported is false). Rebuild the app and reload the browser";
+ }
+ else
{
- s_initialized = true;
-
// TODO: Implement hotReloadExceptionCreateHandler: https://github.com/dotnet/sdk/issues/51056
var agent = new HotReloadAgent(assemblyResolvingHandler: null, hotReloadExceptionCreateHandler: null);
@@ -77,67 +82,24 @@ public static async Task InitializeAsync(string baseUri)
{
throw new InvalidOperationException("Hot Reload agent already initialized");
}
-
- await ApplyPreviousDeltasAsync(agent, baseUri);
}
- }
-
- private static async ValueTask ApplyPreviousDeltasAsync(HotReloadAgent agent, string baseUri)
- {
- string errorMessage;
-
- using var client = new HttpClient()
- {
- BaseAddress = new Uri(baseUri, UriKind.Absolute)
- };
-
- try
- {
- var response = await client.GetAsync("/_framework/blazor-hotreload");
- if (response.IsSuccessStatusCode)
- {
- var deltasJson = await response.Content.ReadAsStringAsync();
- var updates = deltasJson != "" ? JsonSerializer.Deserialize(deltasJson, s_jsonSerializerOptions) : null;
- if (updates == null)
- {
- agent.Reporter.Report($"No previous updates to apply.", AgentMessageSeverity.Verbose);
- return;
- }
-
- var i = 1;
- foreach (var update in updates)
- {
- agent.Reporter.Report($"Reapplying update {i}/{updates.Length}.", AgentMessageSeverity.Verbose);
-
- agent.ApplyManagedCodeUpdates(
- update.Deltas.Select(d => new RuntimeManagedCodeUpdate(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes)));
-
- i++;
- }
-
- return;
- }
- errorMessage = $"HTTP GET '/_framework/blazor-hotreload' returned {response.StatusCode}";
- }
- catch (Exception e)
- {
- errorMessage = e.ToString();
- }
-
- agent.Reporter.Report($"Failed to retrieve and apply previous deltas from the server: {errorMessage}", AgentMessageSeverity.Error);
+ // Updates applied before the browser connected are replayed by the browser tools client.
+ return Task.CompletedTask;
}
- private static HotReloadAgent? GetAgent()
- => s_hotReloadAgent ?? (s_initialized ? throw new InvalidOperationException("Hot Reload agent not initialized") : null);
+ ///
+ /// The agent, or an exception explaining why managed code updates cannot be applied. Never reports
+ /// success without applying, because dotnet-watch reports an update as applied when the browser
+ /// acknowledges it without an error.
+ ///
+ private static HotReloadAgent GetRequiredAgent()
+ => s_hotReloadAgent ?? throw new InvalidOperationException(
+ $"Unable to apply managed code updates because {s_unavailableReason ?? "the Hot Reload agent has not been initialized"}.");
private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel)
{
- var agent = GetAgent();
- if (agent == null)
- {
- return [];
- }
+ var agent = GetRequiredAgent();
agent.ApplyManagedCodeUpdates(
deltas.Select(d => new RuntimeManagedCodeUpdate(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes)));
@@ -152,7 +114,7 @@ private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel)
[SupportedOSPlatform("browser")]
public static string GetApplyUpdateCapabilities()
{
- return GetAgent()?.Capabilities ?? "";
+ return s_hotReloadAgent?.Capabilities ?? "";
}
[JSExport]
diff --git a/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/wwwroot/Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js b/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/wwwroot/Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js
deleted file mode 100644
index 54e496f01536..000000000000
--- a/src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/wwwroot/Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js
+++ /dev/null
@@ -1,44 +0,0 @@
-let isHotReloadEnabled = false;
-
-export async function onRuntimeConfigLoaded(config) {
- // If we have 'aspnetcore-browser-refresh', configure mono runtime for HotReload.
- if (config.debugLevel !== 0 && globalThis.window?.document?.querySelector("script[src*='aspnetcore-browser-refresh']")) {
- isHotReloadEnabled = true;
-
- if (!config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"]) {
- config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"] = "debug";
- }
- if (!config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"]) {
- config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"] = "true";
- }
- }
-
- // Disable HotReload built-into the Blazor WebAssembly runtime
- config.environmentVariables["__BLAZOR_WEBASSEMBLY_LEGACY_HOTRELOAD"] = "false";
-}
-
-export async function onRuntimeReady({ getAssemblyExports }) {
- if (!isHotReloadEnabled) {
- return;
- }
-
- const exports = await getAssemblyExports("Microsoft.DotNet.HotReload.WebAssembly.Browser");
- await exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.InitializeAsync(document.baseURI);
-
- if (!window.Blazor) {
- window.Blazor = {};
-
- if (!window.Blazor._internal) {
- window.Blazor._internal = {};
- }
- }
-
- window.Blazor._internal.applyHotReloadDeltas = (deltas, loggingLevel) => {
- const result = exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.ApplyHotReloadDeltas(JSON.stringify(deltas), loggingLevel);
- return result ? JSON.parse(result) : [];
- };
-
- window.Blazor._internal.getApplyUpdateCapabilities = () => {
- return exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.GetApplyUpdateCapabilities() ?? '';
- };
-}
diff --git a/src/Dotnet.Watch/HotReloadClient/HotReloadClients.cs b/src/Dotnet.Watch/HotReloadClient/HotReloadClients.cs
index 513783494c79..b662a5f94624 100644
--- a/src/Dotnet.Watch/HotReloadClient/HotReloadClients.cs
+++ b/src/Dotnet.Watch/HotReloadClient/HotReloadClients.cs
@@ -90,7 +90,7 @@ internal void ConfigureLaunchEnvironment(IDictionary environment
client.ConfigureLaunchEnvironment(environmentBuilder);
}
- browserRefreshServer?.ConfigureLaunchEnvironment(environmentBuilder, enableHotReload: true);
+ browserRefreshServer?.ConfigureLaunchEnvironment(environmentBuilder);
}
/// Environment variable to be set by the agent in the target process.
@@ -132,7 +132,7 @@ public async ValueTask> GetConnectedAgentsInf
/// Cancellation token for the apply operation that starts but not necessarily completes when this method returns.
/// Cancellation token. The cancellation should trigger on process terminatation.
///
- public async Task ApplyManagedCodeUpdatesAsync(ImmutableArray> updates, CancellationToken applyOperationCancellationToken, CancellationToken cancellationToken)
+ public async Task> ApplyManagedCodeUpdatesAsync(ImmutableArray> updates, CancellationToken applyOperationCancellationToken, CancellationToken cancellationToken)
{
// shouldn't be called if there are no clients
Debug.Assert(IsManagedAgentSupported);
@@ -149,13 +149,16 @@ public async Task ApplyManagedCodeUpdatesAsync(ImmutableArray CompleteApplyOperationAsync()
{
var results = await Task.WhenAll(applyTasks);
- if (browserRefreshServer != null && results.All(isSuccess => isSuccess))
+ var success = results.All(isSuccess => isSuccess);
+ if (browserRefreshServer != null && success)
{
await browserRefreshServer.RefreshBrowserAsync(cancellationToken);
}
+
+ return success;
}
}
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/AbstractBrowserRefreshServer.cs b/src/Dotnet.Watch/HotReloadClient/Web/AbstractBrowserRefreshServer.cs
index f240c5b48164..fc91ae429f10 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/AbstractBrowserRefreshServer.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/AbstractBrowserRefreshServer.cs
@@ -13,17 +13,21 @@
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+#if NET
+using Microsoft.AspNetCore.Http;
+#endif
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
namespace Microsoft.DotNet.HotReload;
///
-/// Communicates with aspnetcore-browser-refresh.js loaded in the browser.
+/// Hosts the browser tools provider and communicates with browser tools clients.
/// Associated with a project instance.
///
internal abstract class AbstractBrowserRefreshServer(
- string middlewareAssemblyPath,
+ Action, AbstractBrowserRefreshServer> configureLaunchEnvironment,
+ Func sessionKeyFactory,
ILogger logger,
Func connectionServerLoggerFactory,
Func connectionAgentLoggerFactory) : IDisposable
@@ -32,10 +36,21 @@ internal abstract class AbstractBrowserRefreshServer(
private static int s_lastConnectionId;
+ private Func _sessionKeyFactory = sessionKeyFactory;
+
+ ///
+ /// Guards the connection list, the retained updates and the baseline epoch together.
+ /// Publishing a connection with its replay snapshot and appending an update batch with the list
+ /// of connections that receive it live must be mutually atomic, otherwise a browser connecting
+ /// concurrently would either apply a batch twice or miss it entirely.
+ ///
+ private readonly object _stateGuard = new();
+
private readonly List _activeConnections = [];
- private readonly TaskCompletionSource _browserConnected = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ private ImmutableArray _retainedUpdates = [];
+ private int _epoch;
- private readonly SharedSecretProvider _sharedSecretProvider = new();
+ private readonly TaskCompletionSource _browserConnected = new(TaskCreationOptions.RunContinuationsAsynchronously);
// initialized by StartAsync
private WebServerHost? _lazyHost;
@@ -43,7 +58,7 @@ internal abstract class AbstractBrowserRefreshServer(
public virtual void Dispose()
{
BrowserConnection[] connectionsToDispose;
- lock (_activeConnections)
+ lock (_stateGuard)
{
connectionsToDispose = [.. _activeConnections];
_activeConnections.Clear();
@@ -55,7 +70,7 @@ public virtual void Dispose()
}
_lazyHost?.Dispose();
- _sharedSecretProvider.Dispose();
+
}
protected abstract ValueTask CreateAndStartHostAsync(CancellationToken cancellationToken);
@@ -64,65 +79,85 @@ public virtual void Dispose()
public ILogger Logger
=> logger;
- public async ValueTask StartAsync(CancellationToken cancellationToken)
- {
- if (_lazyHost != null)
- {
- throw new InvalidOperationException("Server already started");
- }
+ internal Uri ProviderAddress
+ => new((_lazyHost ?? throw new InvalidOperationException("Server not started")).HttpEndPoints.First(
+ static endpoint => endpoint.StartsWith("http:", StringComparison.OrdinalIgnoreCase)));
- _lazyHost = await CreateAndStartHostAsync(cancellationToken);
- logger.Log(LogEvents.RefreshServerRunningAt, string.Join(",", _lazyHost.EndPoints));
- }
+ ///
+ /// Discards the updates retained for the previous application baseline and closes the browser
+ /// connections bound to it, so that browsers connecting afterwards only observe the new
+ /// baseline. Returns the epoch that identifies the new baseline; update batches produced by a
+ /// client of an earlier baseline are dropped.
+ ///
+ internal int ResetUpdates() {
+ BrowserConnection[] connectionsToDispose;
+ int epoch;
- public void ConfigureLaunchEnvironment(IDictionary builder, bool enableHotReload)
- {
- if (_lazyHost == null)
+ lock (_stateGuard)
{
- throw new InvalidOperationException("Server not started");
+ _retainedUpdates = [];
+ epoch = ++_epoch;
+ connectionsToDispose = [.. _activeConnections];
+ _activeConnections.Clear();
}
- builder[MiddlewareEnvironmentVariables.AspNetCoreAutoReloadWSEndPoint] = string.Join(",", _lazyHost.EndPoints);
- builder[MiddlewareEnvironmentVariables.AspNetCoreAutoReloadWSKey] = _sharedSecretProvider.GetPublicKey();
- builder[MiddlewareEnvironmentVariables.AspNetCoreAutoReloadVirtualDirectory] = _lazyHost.VirtualDirectory;
+ foreach (var connection in connectionsToDispose)
+ {
+ connection.Dispose();
+ }
- builder.InsertListItem(MiddlewareEnvironmentVariables.DotNetStartupHooks, middlewareAssemblyPath, Path.PathSeparator);
- builder.InsertListItem(MiddlewareEnvironmentVariables.AspNetCoreHostingStartupAssemblies, Path.GetFileNameWithoutExtension(middlewareAssemblyPath), MiddlewareEnvironmentVariables.AspNetCoreHostingStartupAssembliesSeparator);
+ return epoch;
+ }
- if (enableHotReload)
+ ///
+ /// The updates a browser connecting right now would replay before observing any live message.
+ ///
+ internal ImmutableArray GetRetainedUpdates()
+ {
+ lock (_stateGuard)
{
- // Note:
- // Microsoft.AspNetCore.Components.WebAssembly.Server.ComponentWebAssemblyConventions and Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware
- // expect DOTNET_MODIFIABLE_ASSEMBLIES to be set in the blazor-devserver process, even though we are not performing Hot Reload in this process.
- // The value is converted to DOTNET-MODIFIABLE-ASSEMBLIES header, which is in turn converted back to environment variable in Mono browser runtime loader:
- // https://github.com/dotnet/runtime/blob/342936c5a88653f0f622e9d6cb727a0e59279b31/src/mono/browser/runtime/loader/config.ts#L330
- builder[MiddlewareEnvironmentVariables.DotNetModifiableAssemblies] = "debug";
+ return _retainedUpdates;
}
+ }
- if (logger.IsEnabled(LogLevel.Trace))
+ public async ValueTask StartAsync(CancellationToken cancellationToken)
+ {
+ if (_lazyHost != null)
{
- // enable debug logging from middleware:
- builder[MiddlewareEnvironmentVariables.LoggingLevel] = "Debug";
+ throw new InvalidOperationException("Server already started");
}
+
+ _lazyHost = await CreateAndStartHostAsync(cancellationToken);
+ logger.Log(LogEvents.RefreshServerRunningAt, string.Join(",", _lazyHost.EndPoints));
}
+ ///
+ /// Configures the application process to expose the browser tools provider on its own origin.
+ /// How that is done depends on the host, so the app model supplies the implementation.
+ ///
+ public void ConfigureLaunchEnvironment(IDictionary builder)
+ => configureLaunchEnvironment(builder, this);
+
+ internal void SetSessionKeyFactory(Func value)
+ => Volatile.Write(ref _sessionKeyFactory, value);
+
///
/// Takes ownership of the .
+ /// Publishes the connection and captures the updates it has to replay atomically.
///
- protected BrowserConnection OnBrowserConnected(WebSocket clientSocket, string? subProtocol)
+ protected BrowserConnection OnBrowserConnected(WebSocket clientSocket, string? sharedSecret)
{
bool connectionPublished = false;
try
{
- var sharedSecret = (subProtocol != null) ? _sharedSecretProvider.DecryptSecret(WebUtility.UrlDecode(subProtocol)) : null;
-
var connectionId = Interlocked.Increment(ref s_lastConnectionId);
var serverLogger = connectionServerLoggerFactory(connectionId);
var agentLogger = connectionAgentLoggerFactory(connectionId);
- var connection = new BrowserConnection(clientSocket, sharedSecret, connectionId, serverLogger, agentLogger);
- lock (_activeConnections)
+ BrowserConnection connection;
+ lock (_stateGuard)
{
+ connection = new BrowserConnection(clientSocket, sharedSecret, connectionId, serverLogger, agentLogger, _retainedUpdates);
_activeConnections.Add(connection);
}
@@ -141,6 +176,105 @@ protected BrowserConnection OnBrowserConnected(WebSocket clientSocket, string? s
}
}
+ ///
+ /// Sends the session initialization message, which carries the updates the browser has to apply
+ /// before it observes any live message, and waits for the browser to acknowledge it. Live
+ /// messages queued for the connection in the meantime are released once this completes.
+ ///
+ protected async ValueTask InitializeBrowserConnectionAsync(BrowserConnection connection, CancellationToken cancellationToken)
+ {
+ var message = SerializeJson(new JsonInitializeSessionRequest
+ {
+ SharedSecret = connection.SharedSecret,
+ Updates = connection.PendingReplayUpdates,
+ });
+
+ bool? initialized = null;
+ if (await connection.TrySendMessageAsync(message, cancellationToken))
+ {
+ initialized = await connection.TryReceiveMessageAsync(
+ new ResponseFunc(static (value, logger) => ReceiveUpdateApplyResponse(value, logger)),
+ cancellationToken);
+ }
+
+ if (initialized != true)
+ {
+ connection.ServerLogger.LogDebug("Failed to initialize the browser tools session.");
+ connection.Dispose();
+ return;
+ }
+
+ connection.Initialized.TrySetResult(true);
+ }
+
+ internal static bool ReceiveUpdateApplyResponse(ReadOnlySpan value, ILogger logger)
+ {
+ var data = DeserializeJson(value);
+
+ foreach (var entry in data.Log)
+ {
+ HotReloadClient.ReportLogEntry(logger, entry.Message, (AgentMessageSeverity)entry.Severity);
+ }
+
+ return data.Success;
+ }
+
+#if NET
+ internal async Task AcceptBrowserConnectionAsync(HttpContext context)
+ {
+ if (!context.WebSockets.IsWebSocketRequest)
+ {
+ context.Response.StatusCode = StatusCodes.Status400BadRequest;
+ return;
+ }
+
+ var subProtocol = context.WebSockets.WebSocketRequestedProtocols is [var requestedSubProtocol]
+ ? requestedSubProtocol
+ : null;
+ if (subProtocol == null)
+ {
+ context.Response.StatusCode = StatusCodes.Status400BadRequest;
+ return;
+ }
+
+ SharedSecretProvider sessionKey;
+ try
+ {
+ sessionKey = Volatile.Read(ref _sessionKeyFactory)();
+ }
+ catch (Exception e)
+ {
+ logger.LogError(e, "Unable to load the browser tools session key.");
+ context.Response.StatusCode = StatusCodes.Status500InternalServerError;
+ return;
+ }
+
+ string sharedSecret;
+ using (sessionKey)
+ {
+ // The browser generated secret, encrypted with the build-pinned public key, is the only
+ // credential. Reject before upgrading the connection so an unauthenticated peer never gets
+ // a socket.
+ try
+ {
+ sharedSecret = sessionKey.DecryptSecret(WebUtility.UrlDecode(subProtocol));
+ }
+ catch (Exception e)
+ {
+ logger.LogDebug("Rejecting a browser connection with an invalid encrypted secret: {Message}", e.Message);
+ context.Response.StatusCode = StatusCodes.Status400BadRequest;
+ return;
+ }
+ }
+
+ var clientSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol);
+
+ var connection = OnBrowserConnected(clientSocket, sharedSecret);
+ await InitializeBrowserConnectionAsync(connection, context.RequestAborted);
+ await connection.Disconnected.Task;
+ }
+#endif
+
///
/// For testing.
///
@@ -200,17 +334,72 @@ public async Task WaitForClientConnectionAsync(CancellationToken cancellationTok
private IReadOnlyCollection GetOpenBrowserConnections()
{
- lock (_activeConnections)
+ lock (_stateGuard)
{
return [.. _activeConnections.Where(b => b.ClientSocket.State == WebSocketState.Open)];
}
}
+ ///
+ /// Retains for browsers that connect later and captures the connections
+ /// that have to receive it live. Both happen under a single lock: a browser that registers before
+ /// the append receives the batch live and not in its replay snapshot, and a browser that registers
+ /// after it receives it in the snapshot and is not in the captured list. Hence every browser
+ /// applies every batch exactly once, in order, without any wire level update identity.
+ ///
+ /// Returns false if is stale, which means the batch was produced by a
+ /// client of a previous application baseline and must be dropped.
+ ///
+ private bool TryAppendUpdate(int epoch, BrowserToolsUpdateBatch batch, out IReadOnlyCollection liveConnections)
+ {
+ lock (_stateGuard)
+ {
+ if (epoch != _epoch)
+ {
+ liveConnections = [];
+ return false;
+ }
+
+ _retainedUpdates = _retainedUpdates.Add(batch);
+ liveConnections = [.. _activeConnections.Where(b => b.ClientSocket.State == WebSocketState.Open)];
+ return true;
+ }
+ }
+
+ ///
+ /// Retains a managed code update batch and delivers it to the browsers connected at that moment.
+ ///
+ ///
+ /// True unless a browser reported that it failed to apply the update, or if the batch belongs to
+ /// a superseded baseline and was dropped. When several browsers are connected the result is the
+ /// last reported one, which matches the pre-existing behavior of this path.
+ ///
+ internal async ValueTask SendManagedCodeUpdateAsync(
+ int epoch,
+ BrowserToolsUpdateBatch batch,
+ Func request,
+ CancellationToken cancellationToken)
+ {
+ if (!TryAppendUpdate(epoch, batch, out var liveConnections))
+ {
+ logger.LogDebug("Discarding an update batch produced for a superseded application baseline.");
+ return true;
+ }
+
+ var result = await SendAndReceiveAsync(
+ liveConnections,
+ request,
+ new ResponseFunc(static (value, logger) => ReceiveUpdateApplyResponse(value, logger)),
+ cancellationToken);
+
+ return result ?? true;
+ }
+
private void DisposeClosedBrowserConnections()
{
List? lazyConnectionsToDispose = null;
- lock (_activeConnections)
+ lock (_stateGuard)
{
var j = 0;
for (var i = 0; i < _activeConnections.Count; i++)
@@ -265,35 +454,41 @@ private async ValueTask SendAsync(ReadOnlyMemory messageBytes, Cancellatio
await SendAndReceiveAsync, None>(request: _ => messageBytes, response: null, cancellationToken);
}
+ internal ValueTask SendAndReceiveAsync(
+ Func? request,
+ ResponseFunc? response,
+ CancellationToken cancellationToken)
+ where TResult : struct
+ => SendAndReceiveAsync(GetOpenBrowserConnections(), request, response, cancellationToken);
+
internal virtual async ValueTask SendAndReceiveAsync(
+ IReadOnlyCollection openConnections,
Func? request,
ResponseFunc? response,
CancellationToken cancellationToken)
where TResult : struct
{
var responded = false;
- var openConnections = GetOpenBrowserConnections();
var result = default(TResult?);
+ // Each connection owns its socket, so run them concurrently. Sequential delivery would let a
+ // browser that has not acknowledged its session initialization yet hold up every other
+ // browser, since the wait below has no timeout by design.
+ var exchanges = new List>(openConnections.Count);
foreach (var connection in openConnections)
{
- if (request != null)
- {
- var requestValue = request(connection.SharedSecret);
- var requestBytes = requestValue is ReadOnlyMemory bytes ? bytes : SerializeJson(requestValue);
-
- if (!await connection.TrySendMessageAsync(requestBytes, cancellationToken))
- {
- continue;
- }
- }
+ exchanges.Add(ExchangeAsync(connection));
+ }
- if (response != null && (result = await connection.TryReceiveMessageAsync(response, cancellationToken)) == null)
+ // Fold in connection order so the observable outcome matches a sequential exchange.
+ foreach (var (received, connectionResult, connectionResponded) in await Task.WhenAll(exchanges))
+ {
+ if (received)
{
- continue;
+ result = connectionResult;
}
- responded = true;
+ responded |= connectionResponded;
}
if (openConnections.Count == 0)
@@ -307,6 +502,35 @@ private async ValueTask SendAsync(ReadOnlyMemory messageBytes, Cancellatio
DisposeClosedBrowserConnections();
return result;
+
+ async Task<(bool received, TResult? result, bool responded)> ExchangeAsync(BrowserConnection connection)
+ {
+ // Live messages must not overtake the session initialization message, which carries the
+ // updates produced before the connection was established.
+ if (!await connection.WaitForInitializationAsync(cancellationToken))
+ {
+ return (false, null, false);
+ }
+
+ if (request != null)
+ {
+ var requestValue = request(connection.SharedSecret);
+ var requestBytes = requestValue is ReadOnlyMemory bytes ? bytes : SerializeJson(requestValue);
+
+ if (!await connection.TrySendMessageAsync(requestBytes, cancellationToken))
+ {
+ return (false, null, false);
+ }
+ }
+
+ if (response == null)
+ {
+ return (false, null, true);
+ }
+
+ var connectionResult = await connection.TryReceiveMessageAsync(response, cancellationToken);
+ return (true, connectionResult, connectionResult != null);
+ }
}
public ValueTask RefreshBrowserAsync(CancellationToken cancellationToken)
@@ -362,4 +586,29 @@ private readonly struct JasonUpdateStaticFileRequest
public string Type => "UpdateStaticFile";
public string Path { get; init; }
}
+
+ ///
+ /// The first message sent on an accepted connection. It echoes the browser generated secret back
+ /// so that the browser can authenticate the provider, and carries the updates produced before the
+ /// connection was established. The browser applies them and acknowledges with
+ /// before it starts observing live messages.
+ ///
+ private readonly struct JsonInitializeSessionRequest
+ {
+ public string Type => "InitializeSession";
+ public string? SharedSecret { get; init; }
+ public ImmutableArray Updates { get; init; }
+ }
+
+ internal readonly struct JsonApplyDeltasResponse
+ {
+ public bool Success { get; init; }
+ public IEnumerable Log { get; init; }
+ }
+
+ internal readonly struct JsonLogEntry
+ {
+ public string Message { get; init; }
+ public int Severity { get; init; }
+ }
}
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/BrowserConnection.cs b/src/Dotnet.Watch/HotReloadClient/Web/BrowserConnection.cs
index 9ce005c0a679..07868ce0eb1a 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/BrowserConnection.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/BrowserConnection.cs
@@ -5,6 +5,7 @@
using System;
using System.Buffers;
+using System.Collections.Immutable;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
@@ -15,14 +16,29 @@ namespace Microsoft.DotNet.HotReload;
///
/// Represents a connection to a browser that facilitates Hot Reload operations.
///
-internal readonly struct BrowserConnection(WebSocket clientSocket, string? sharedSecret, int id, ILogger serverLogger, ILogger agentLogger) : IDisposable
+internal readonly struct BrowserConnection(
+ WebSocket clientSocket,
+ string? sharedSecret,
+ int id,
+ ILogger serverLogger,
+ ILogger agentLogger,
+ ImmutableArray pendingReplayUpdates) : IDisposable
{
public readonly TaskCompletionSource Disconnected = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ ///
+ /// Completes with true once the browser acknowledged the session initialization message, which
+ /// carries the updates produced before this connection was established. Live messages must not
+ /// be sent to the connection before that, otherwise they could be applied out of order or twice.
+ /// Completes with false if the connection is torn down before it is initialized.
+ ///
+ public readonly TaskCompletionSource Initialized = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
public void Dispose()
{
ClientSocket.Dispose();
+ Initialized.TrySetResult(false);
Disconnected.TrySetResult(default);
ServerLogger.LogDebug("Disconnected.");
}
@@ -33,6 +49,28 @@ public void Dispose()
public ILogger ServerLogger => serverLogger;
public ILogger AgentLogger => agentLogger;
+ ///
+ /// Updates that were produced before this connection was established, captured atomically with
+ /// the publication of the connection.
+ ///
+ public ImmutableArray PendingReplayUpdates => pendingReplayUpdates;
+
+ internal async ValueTask WaitForInitializationAsync(CancellationToken cancellationToken)
+ {
+ var initialized = Initialized.Task;
+ if (initialized.IsCompleted)
+ {
+ return initialized.Status == TaskStatus.RanToCompletion && initialized.Result;
+ }
+
+ // Work around lack of Task.WaitAsync(CancellationToken) on .NET Framework:
+ var cancellation = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var registration = cancellationToken.Register(static state => ((TaskCompletionSource)state!).TrySetResult(false), cancellation);
+
+ var completed = await Task.WhenAny(initialized, cancellation.Task);
+ return completed == initialized && initialized.Result;
+ }
+
internal async ValueTask TrySendMessageAsync(ReadOnlyMemory messageBytes, CancellationToken cancellationToken)
{
#if NET
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/BrowserRefreshServer.cs b/src/Dotnet.Watch/HotReloadClient/Web/BrowserRefreshServer.cs
index b5979bfbac98..351f1d95f2a9 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/BrowserRefreshServer.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/BrowserRefreshServer.cs
@@ -6,15 +6,13 @@
#if NET
using System;
+using System.Collections.Generic;
using System.Collections.Immutable;
-using System.Diagnostics;
using System.Linq;
-using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Primitives;
namespace Microsoft.DotNet.HotReload;
@@ -26,15 +24,19 @@ internal sealed class BrowserRefreshServer(
ILogger logger,
Func connectionServerLoggerFactory,
Func connectionAgentLoggerFactory,
- string middlewareAssemblyPath,
+ Action, AbstractBrowserRefreshServer> configureLaunchEnvironment,
string dotnetPath,
+ Func sessionKeyFactory,
WebSocketConfig webSocketConfig,
bool suppressTimeouts)
- : AbstractBrowserRefreshServer(middlewareAssemblyPath, logger, connectionServerLoggerFactory, connectionAgentLoggerFactory)
+ : AbstractBrowserRefreshServer(configureLaunchEnvironment, sessionKeyFactory, logger, connectionServerLoggerFactory, connectionAgentLoggerFactory)
{
protected override bool SuppressTimeouts
=> suppressTimeouts;
+ internal void UpdateSessionKeyFactory(Func value)
+ => SetSessionKeyFactory(value);
+
protected override async ValueTask CreateAndStartHostAsync(CancellationToken cancellationToken)
{
var supportsTls = await KestrelWebSocketServer.IsTlsSupportedAsync(dotnetPath, suppressTimeouts, cancellationToken);
@@ -43,38 +45,29 @@ protected override async ValueTask CreateAndStartHostAsync(Cancel
webSocketConfig = webSocketConfig.WithSecurePort(null);
}
- var server = await KestrelWebSocketServer.StartServerAsync(webSocketConfig, WebSocketRequestAsync, cancellationToken);
+ // The browser reaches the provider through the application's own origin, so the provider only
+ // listens on loopback. DOTNET_WATCH_AUTO_RELOAD_WS_HOSTNAME no longer applies to this hop.
+ var router = new BrowserToolsEndpointRouter(this);
+ var server = await KestrelWebSocketServer.StartServerAsync(
+ webSocketConfig.WithHostName(null),
+ context => HandleRequestAsync(context, router),
+ cancellationToken);
// URLs are only available after the server has started.
- return new WebServerHost(server, server.ServerUrls, virtualDirectory: "/");
+ return new WebServerHost(server, server.ServerUrls, server.HttpServerUrls);
}
- private async Task WebSocketRequestAsync(HttpContext context)
+ private Task HandleRequestAsync(HttpContext context, BrowserToolsEndpointRouter router)
{
- if (!context.WebSockets.IsWebSocketRequest)
- {
- context.Response.StatusCode = StatusCodes.Status400BadRequest;
- return;
- }
-
- // check the domain of the Origin header:
- if (!Uri.TryCreate(context.Request.Headers.Origin.FirstOrDefault(), UriKind.Absolute, out var originUri) ||
- !webSocketConfig.GetAllowedOriginDomains().Contains(originUri.Host, StringComparer.OrdinalIgnoreCase))
+ if (context.WebSockets.IsWebSocketRequest &&
+ (!Uri.TryCreate(context.Request.Headers.Origin.FirstOrDefault(), UriKind.Absolute, out var originUri) ||
+ !webSocketConfig.GetAllowedOriginDomains().Contains(originUri.Host, StringComparer.OrdinalIgnoreCase)))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
- return;
+ return Task.CompletedTask;
}
- if (context.WebSockets.WebSocketRequestedProtocols is not [var subProtocol])
- {
- subProtocol = null;
- }
-
- var clientSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol);
-
- // client socket ownership is transferred to the connection:
- var connection = OnBrowserConnected(clientSocket, subProtocol);
- await connection.Disconnected.Task;
+ return router.HandleAsync(context);
}
}
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsEndpointRouter.cs b/src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsEndpointRouter.cs
new file mode 100644
index 000000000000..ba8b96d775d6
--- /dev/null
+++ b/src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsEndpointRouter.cs
@@ -0,0 +1,58 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+#if NET
+
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+
+namespace Microsoft.DotNet.HotReload;
+
+///
+/// The complete HTTP surface of the browser tools provider.
+///
+/// The provider serves no executable content: the browser tools client and its configuration are
+/// part of the application build output, which is what makes authenticating the provider with the
+/// build pinned public key meaningful. Its settings response only reports provider availability.
+///
+internal sealed class BrowserToolsEndpointRouter(AbstractBrowserRefreshServer browserServer)
+{
+ public async Task HandleAsync(HttpContext context)
+ {
+ context.Response.Headers.CacheControl = "no-store";
+
+ if (!HttpMethods.IsGet(context.Request.Method))
+ {
+ context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
+ return;
+ }
+
+ var path = context.Request.Path.Value;
+
+ if (path == BrowserToolsProtocol.RoutePrefix + BrowserToolsProtocol.ClearCachePath)
+ {
+ context.Response.Headers.Append("Clear-Site-Data", "\"cache\"");
+ context.Response.StatusCode = StatusCodes.Status204NoContent;
+ return;
+ }
+
+ if (path == BrowserToolsProtocol.RoutePrefix + BrowserToolsProtocol.HotReloadSettingsPath)
+ {
+ context.Response.ContentType = "application/json";
+ await context.Response.WriteAsync("{ \"hotReload\": true }", context.RequestAborted);
+ return;
+ }
+
+ if (path == BrowserToolsProtocol.RoutePrefix + BrowserToolsProtocol.ConnectPath)
+ {
+ await browserServer.AcceptBrowserConnectionAsync(context);
+ return;
+ }
+
+ context.Response.StatusCode = StatusCodes.Status404NotFound;
+ }
+}
+
+#endif
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsProtocol.cs b/src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsProtocol.cs
new file mode 100644
index 000000000000..91becabc4337
--- /dev/null
+++ b/src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsProtocol.cs
@@ -0,0 +1,39 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using System;
+using System.Collections.Immutable;
+
+namespace Microsoft.DotNet.HotReload;
+
+///
+/// The contract between the dotnet-watch browser tools provider and the browser tools client.
+///
+/// The client is generated into the application build output together with the public half of the
+/// provider's session key, so the two always ship together and there is no version negotiation.
+/// must be kept in sync with the DotNetWatchBrowserToolsRoutePrefix
+/// property in Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets.
+///
+internal static class BrowserToolsProtocol
+{
+ public const string RoutePrefix = "/_framework/dotnet-browser-tools";
+ public const string ClearCachePath = "/clear-cache";
+ public const string ConnectPath = "/connect";
+ public const string HotReloadSettingsPath = "/hot-reload-settings.json";
+}
+
+internal sealed record BrowserToolsManagedCodeUpdate(
+ Guid ModuleId,
+ byte[] MetadataDelta,
+ byte[] ILDelta,
+ byte[] PdbDelta,
+ int[] UpdatedTypes);
+
+///
+/// A batch of managed code updates. Batches are retained for the current application baseline so
+/// that browsers connecting later can replay them before they receive any live message.
+///
+internal sealed record BrowserToolsUpdateBatch(
+ ImmutableArray Deltas);
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/KestrelWebSocketServer.cs b/src/Dotnet.Watch/HotReloadClient/Web/KestrelWebSocketServer.cs
index bfcceeb50a9b..5f2c1f6b6f16 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/KestrelWebSocketServer.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/KestrelWebSocketServer.cs
@@ -26,7 +26,7 @@ namespace Microsoft.DotNet.HotReload;
/// Sealed WebSocket server using Kestrel.
/// Uses a request handler delegate for all WebSocket handling.
///
-internal sealed class KestrelWebSocketServer(IHost host, ImmutableArray serverUrls) : IDisposable
+internal sealed class KestrelWebSocketServer(IHost host, ImmutableArray serverUrls, ImmutableArray httpServerUrls) : IDisposable
{
private static bool? s_lazyTlsSupported;
@@ -36,6 +36,9 @@ public void Dispose()
public ImmutableArray ServerUrls
=> serverUrls;
+ public ImmutableArray HttpServerUrls
+ => httpServerUrls;
+
///
/// Starts the Kestrel WebSocket server.
///
@@ -64,7 +67,7 @@ public static async ValueTask StartServerAsync(WebSocket
.Get()?
.Addresses ?? [];
- return new KestrelWebSocketServer(host, serverUrls: [.. addresses.Select(GetWebSocketUrl)]);
+ return new KestrelWebSocketServer(host, serverUrls: [.. addresses.Select(GetWebSocketUrl)], httpServerUrls: [.. addresses]);
}
///
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/MiddlewareEnvironmentVariables.cs b/src/Dotnet.Watch/HotReloadClient/Web/MiddlewareEnvironmentVariables.cs
index ea4754a54e0d..e512a483a472 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/MiddlewareEnvironmentVariables.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/MiddlewareEnvironmentVariables.cs
@@ -13,28 +13,13 @@ internal static class MiddlewareEnvironmentVariables
///
public const string DotNetStartupHooks = "DOTNET_STARTUP_HOOKS";
- ///
- /// dotnet runtime environment variable.
- ///
- public const string DotNetModifiableAssemblies = "DOTNET_MODIFIABLE_ASSEMBLIES";
-
///
/// Simple names of assemblies that implement middleware components to be added to the web server.
///
public const string AspNetCoreHostingStartupAssemblies = "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES";
public const char AspNetCoreHostingStartupAssembliesSeparator = ';';
- ///
- /// Comma-separated list of WebSocket end points to communicate with browser refresh client.
- ///
- public const string AspNetCoreAutoReloadWSEndPoint = "ASPNETCORE_AUTO_RELOAD_WS_ENDPOINT";
-
- public const string AspNetCoreAutoReloadVirtualDirectory = "ASPNETCORE_AUTO_RELOAD_VDIR";
-
- ///
- /// Public key to use to communicate with browser refresh client.
- ///
- public const string AspNetCoreAutoReloadWSKey = "ASPNETCORE_AUTO_RELOAD_WS_KEY";
+ public const string AspNetCoreAutoReloadProviderAddress = "ASPNETCORE_AUTO_RELOAD_PROVIDER_ADDRESS";
///
/// Variable used to set the logging level of the middleware logger.
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/SharedSecretProvider.cs b/src/Dotnet.Watch/HotReloadClient/Web/SharedSecretProvider.cs
index 548afbe082ed..b0d5ea0b6c74 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/SharedSecretProvider.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/SharedSecretProvider.cs
@@ -11,7 +11,35 @@ namespace Microsoft.DotNet.HotReload;
internal sealed class SharedSecretProvider : IDisposable
{
- private readonly RSA _rsa = RSA.Create(2048);
+ private readonly RSA _rsa;
+
+ ///
+ /// Creates a provider with a fresh key pair. Only used where no application pins a key, such as
+ /// in tests; a provider that has to authenticate against an application is created from the key
+ /// pair the application's build produced.
+ ///
+ public SharedSecretProvider()
+ => _rsa = RSA.Create(2048);
+
+ ///
+ /// Creates a provider from an existing key pair, which is how dotnet watch keys a
+ /// provider from the private key half the build wrote next to the application's build outputs.
+ ///
+ public SharedSecretProvider(RSAParameters parameters)
+ {
+ var rsa = RSA.Create();
+ try
+ {
+ rsa.ImportParameters(parameters);
+ }
+ catch
+ {
+ rsa.Dispose();
+ throw;
+ }
+
+ _rsa = rsa;
+ }
public void Dispose()
=> _rsa.Dispose();
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAsset.cs b/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAsset.cs
index 8ccfa362f912..6c6ca1b71451 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAsset.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAsset.cs
@@ -50,6 +50,28 @@ public static bool IsCompressedAssetFile(string filePath)
=> filePath.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".br", StringComparison.OrdinalIgnoreCase);
+ ///
+ /// The browser tools activation initializer, the browser tools client and its generated
+ /// configuration are build outputs that Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets
+ /// writes to '$(IntermediateOutputPath)dotnet-watch'. They are stable for the lifetime of the
+ /// watch invocation, so watching them would only add noise and cannot produce a useful update.
+ ///
+ public static bool IsBrowserToolsAssetFile(string filePath)
+ => Path.GetFileName(filePath).IndexOf(".DotNetWatch.", StringComparison.Ordinal) >= 0 &&
+ string.Equals(Path.GetFileName(Path.GetDirectoryName(filePath)), "dotnet-watch", OSSpecificPathComparison);
+
+ ///
+ /// The JS initializer manifest is regenerated by the build from the set of JS module assets.
+ /// It is not editable, so watching it would only report the build's own output back to itself.
+ ///
+ public static bool IsGeneratedJSModuleManifestFile(string filePath)
+ {
+ var fileName = Path.GetFileName(filePath);
+
+ return fileName.StartsWith("jsmodules.", StringComparison.OrdinalIgnoreCase) &&
+ fileName.EndsWith(".manifest.json", StringComparison.OrdinalIgnoreCase);
+ }
+
public static string? GetRelativeUrl(string applicationProjectFilePath, string containingProjectFilePath, string assetFilePath)
=> IsScopedCssFile(assetFilePath)
? GetScopedCssRelativeUrl(applicationProjectFilePath, containingProjectFilePath)
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAssetsManifest.cs b/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAssetsManifest.cs
index 988340b3b921..a27451d130bb 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAssetsManifest.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/StaticWebAssetsManifest.cs
@@ -69,8 +69,11 @@ private sealed class PatternJson
// Exclude bundle files as they are regenarated when scoped CSS files are updated.
// Exclude compressed asset files as they are not directly editable.
// Exclude external content URLs as they are not directly included in the project.
+ // Exclude generated build outputs of the watcher itself and the JS initializer manifest.
if (!StaticWebAsset.IsCompressedAssetFile(filePath) &&
!StaticWebAsset.IsScopedCssBundleFile(filePath) &&
+ !StaticWebAsset.IsBrowserToolsAssetFile(filePath) &&
+ !StaticWebAsset.IsGeneratedJSModuleManifestFile(filePath) &&
!StaticWebAsset.IsExternalContentUrl(url))
{
yield return (filePath, url);
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/WebAssemblyHotReloadClient.cs b/src/Dotnet.Watch/HotReloadClient/Web/WebAssemblyHotReloadClient.cs
index d86dbf705554..365bd442e5c5 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/WebAssemblyHotReloadClient.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/WebAssemblyHotReloadClient.cs
@@ -19,6 +19,7 @@ internal sealed class WebAssemblyHotReloadClient(
ILogger logger,
ILogger agentLogger,
AbstractBrowserRefreshServer browserRefreshServer,
+ int baselineEpoch,
ImmutableArray projectHotReloadCapabilities,
Version projectTargetFrameworkVersion,
bool suppressBrowserRequestsForTesting)
@@ -79,7 +80,14 @@ public override void Dispose()
public override void ConfigureLaunchEnvironment(IDictionary environmentBuilder)
{
- // the environment is configued via browser refesh server
+ // Note:
+ // Microsoft.AspNetCore.Components.WebAssembly.Server.ComponentWebAssemblyConventions expects
+ // DOTNET_MODIFIABLE_ASSEMBLIES to be set in the blazor-devserver process, even though we are not performing
+ // Hot Reload in this process. The value is converted to the DOTNET-MODIFIABLE-ASSEMBLIES header, which is in
+ // turn converted back to an environment variable in the Mono browser runtime loader:
+ // https://github.com/dotnet/runtime/blob/342936c5a88653f0f622e9d6cb727a0e59279b31/src/mono/browser/runtime/loader/config.ts#L330
+ // .NET 10+ apps set the variable from the Hot Reload agent JS module instead.
+ environmentBuilder[AgentEnvironmentVariables.DotNetModifiableAssemblies] = "debug";
}
public override void InitiateConnection(IReadOnlyCollection<(string name, string value)> environmentVariables, CancellationToken cancellationToken)
@@ -105,51 +113,38 @@ public override async Task> ApplyManagedCodeUpdatesAsync(ImmutableArr
return Task.FromResult(true);
}
- // When testing abstract away the browser and pretend all changes have been applied:
- if (suppressBrowserRequestsForTesting)
- {
- return Task.FromResult(true);
- }
-
// Make sure to send the same update to all browsers, the only difference is the shared secret.
- var deltas = updates.Select(static update => new JsonDelta
- {
- ModuleId = update.ModuleId,
- MetadataDelta = ImmutableCollectionsMarshal.AsArray(update.MetadataDelta)!,
- ILDelta = ImmutableCollectionsMarshal.AsArray(update.ILDelta)!,
- PdbDelta = ImmutableCollectionsMarshal.AsArray(update.PdbDelta)!,
- UpdatedTypes = ImmutableCollectionsMarshal.AsArray(update.UpdatedTypes)!,
- }).ToArray();
+ var deltas = applicableUpdates.Select(static update => new BrowserToolsManagedCodeUpdate(
+ update.ModuleId,
+ ImmutableCollectionsMarshal.AsArray(update.MetadataDelta)!,
+ ImmutableCollectionsMarshal.AsArray(update.ILDelta)!,
+ ImmutableCollectionsMarshal.AsArray(update.PdbDelta)!,
+ ImmutableCollectionsMarshal.AsArray(update.UpdatedTypes)!)).ToArray();
var loggingLevel = Logger.IsEnabled(LogLevel.Debug) ? ResponseLoggingLevel.Verbose : ResponseLoggingLevel.WarningsAndErrors;
- // If no browser is connected we assume the changes have been applied.
- // If at least one browser suceeds we consider the changes successfully applied.
- // TODO:
- // The refresh server should remember the deltas and apply them to browsers connected in future.
- // Currently the changes are remembered on the dev server and sent over there from the browser.
- // If no browser is connected the changes are not sent though.
-
return QueueUpdateBatch(
sendAndReceive: async batchId =>
{
- var result = await browserRefreshServer.SendAndReceiveAsync(
+ // When testing abstract away the browser and pretend all changes have been applied:
+ if (suppressBrowserRequestsForTesting)
+ {
+ return true;
+ }
+
+ var success = await browserRefreshServer.SendManagedCodeUpdateAsync(
+ baselineEpoch,
+ new BrowserToolsUpdateBatch([.. deltas]),
request: sharedSecret => new JsonApplyManagedCodeUpdatesRequest
{
SharedSecret = sharedSecret,
- UpdateId = batchId,
Deltas = deltas,
ResponseLoggingLevel = (int)loggingLevel
},
- response: new ResponseFunc((value, logger) =>
- {
- var success = ReceiveUpdateResponse(value, logger);
- Logger.Log(success ? LogEvents.UpdateBatchCompleted : LogEvents.UpdateBatchFailed, batchId);
- return success;
- }),
applyOperationCancellationToken);
- return result ?? false;
+ Logger.Log(success ? LogEvents.UpdateBatchCompleted : LogEvents.UpdateBatchFailed, batchId);
+ return success;
},
applyOperationCancellationToken);
}
@@ -158,18 +153,6 @@ public override Task> ApplyStaticAssetUpdatesAsync(ImmutableArray Task.FromResult(Task.FromResult(true));
- private static bool ReceiveUpdateResponse(ReadOnlySpan value, ILogger logger)
- {
- var data = AbstractBrowserRefreshServer.DeserializeJson(value);
-
- foreach (var entry in data.Log)
- {
- ReportLogEntry(logger, entry.Message, (AgentMessageSeverity)entry.Severity);
- }
-
- return data.Success;
- }
-
public override Task InitialUpdatesAppliedAsync(CancellationToken cancellationToken)
=> Task.CompletedTask;
@@ -178,34 +161,7 @@ private readonly struct JsonApplyManagedCodeUpdatesRequest
public string Type => "ApplyManagedCodeUpdates";
public string? SharedSecret { get; init; }
- public int UpdateId { get; init; }
- public JsonDelta[] Deltas { get; init; }
+ public BrowserToolsManagedCodeUpdate[] Deltas { get; init; }
public int ResponseLoggingLevel { get; init; }
}
-
- private readonly struct JsonDelta
- {
- public Guid ModuleId { get; init; }
- public byte[] MetadataDelta { get; init; }
- public byte[] ILDelta { get; init; }
- public byte[] PdbDelta { get; init; }
- public int[] UpdatedTypes { get; init; }
- }
-
- private readonly struct JsonApplyDeltasResponse
- {
- public bool Success { get; init; }
- public IEnumerable Log { get; init; }
- }
-
- private readonly struct JsonLogEntry
- {
- public string Message { get; init; }
- public int Severity { get; init; }
- }
-
- private readonly struct JsonGetApplyUpdateCapabilitiesRequest
- {
- public string Type => "GetApplyUpdateCapabilities";
- }
}
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/WebServerHost.cs b/src/Dotnet.Watch/HotReloadClient/Web/WebServerHost.cs
index e89a00c65135..35169cccc64c 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/WebServerHost.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/WebServerHost.cs
@@ -8,13 +8,16 @@
namespace Microsoft.DotNet.HotReload;
-internal sealed class WebServerHost(IDisposable listener, ImmutableArray endPoints, string virtualDirectory) : IDisposable
+internal sealed class WebServerHost(IDisposable listener, ImmutableArray endPoints, ImmutableArray httpEndPoints) : IDisposable
{
public ImmutableArray EndPoints
=> endPoints;
- public string VirtualDirectory
- => virtualDirectory;
+ ///
+ /// Loopback HTTP addresses the browser tools provider listens on.
+ ///
+ public ImmutableArray HttpEndPoints
+ => httpEndPoints;
public void Dispose()
=> listener.Dispose();
diff --git a/src/Dotnet.Watch/HotReloadClient/Web/WebSocketConfig.cs b/src/Dotnet.Watch/HotReloadClient/Web/WebSocketConfig.cs
index 5d4f6eba0a8f..ef1709795701 100644
--- a/src/Dotnet.Watch/HotReloadClient/Web/WebSocketConfig.cs
+++ b/src/Dotnet.Watch/HotReloadClient/Web/WebSocketConfig.cs
@@ -54,4 +54,7 @@ public IEnumerable GetAllowedOriginDomains()
public WebSocketConfig WithSecurePort(int? value)
=> new(port, value, hostName, additionalAllowedOrigins);
+
+ public WebSocketConfig WithHostName(string? value)
+ => new(port, securePort, value, additionalAllowedOrigins);
}
diff --git a/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyAppModel.cs b/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyAppModel.cs
index 5b51a5dcd22c..24906d8a64b1 100644
--- a/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyAppModel.cs
+++ b/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyAppModel.cs
@@ -24,4 +24,27 @@ protected override ImmutableArray CreateManagedClients(ILogger
Debug.Assert(browserRefreshServer != null);
return [CreateWebAssemblyClient(clientLogger, agentLogger, browserRefreshServer, clientProject)];
}
+
+ ///
+ /// A standalone WebAssembly app is served by the Blazor Gateway (blazor-gateway), a YARP based
+ /// host that does not activate ASP.NET Core hosting startups. Reserve a proxy route on it that
+ /// forwards to the provider. The hosting startup
+ /// configuration from the base implementation is still applied because older target frameworks
+ /// are served by blazor-devserver, which is a regular ASP.NET Core host.
+ ///
+ internal override void ConfigureBrowserToolsLaunchEnvironment(IDictionary environment, AbstractBrowserRefreshServer browserRefreshServer)
+ {
+ base.ConfigureBrowserToolsLaunchEnvironment(environment, browserRefreshServer);
+ AddGatewayProxyEnvironment(environment, browserRefreshServer);
+ }
+
+ internal static void AddGatewayProxyEnvironment(IDictionary environment, AbstractBrowserRefreshServer browserRefreshServer)
+ {
+ const string routeAndClusterName = "dotnet-browser-tools";
+
+ environment[$"ReverseProxy__Routes__{routeAndClusterName}__ClusterId"] = routeAndClusterName;
+ environment[$"ReverseProxy__Routes__{routeAndClusterName}__Order"] = "-1000";
+ environment[$"ReverseProxy__Routes__{routeAndClusterName}__Match__Path"] = BrowserToolsProtocol.RoutePrefix + "/{**catch-all}";
+ environment[$"ReverseProxy__Clusters__{routeAndClusterName}__Destinations__provider__Address"] = browserRefreshServer.ProviderAddress.AbsoluteUri;
+ }
}
diff --git a/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyHostedAppModel.cs b/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyHostedAppModel.cs
index 437f5e367104..687241ea86fc 100644
--- a/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyHostedAppModel.cs
+++ b/src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyHostedAppModel.cs
@@ -12,13 +12,15 @@ namespace Microsoft.DotNet.Watch;
///
/// Blazor WebAssembly app hosted by an ASP.NET Core app.
/// App has a client and server projects and deltas are applied to both processes.
-/// Agent is injected into the server process. The client process is updated via WebSocketScriptInjection.js injected into the browser.
+/// Agent is injected into the server process. The client process is updated through the browser tools provider.
///
internal sealed class BlazorWebAssemblyHostedAppModel(DotNetWatchContext context, ProjectGraphNode clientProject, ProjectGraphNode serverProject)
: WebApplicationAppModel(context)
{
public override ProjectGraphNode LaunchingProject => serverProject;
+ public override ProjectGraphNode BrowserToolsProject => clientProject;
+
public override bool ManagedHotReloadRequiresBrowserRefresh => true;
protected override ImmutableArray CreateManagedClients(ILogger clientLogger, ILogger agentLogger, BrowserRefreshServer? browserRefreshServer)
diff --git a/src/Dotnet.Watch/Watch/AppModels/WebApplicationAppModel.cs b/src/Dotnet.Watch/Watch/AppModels/WebApplicationAppModel.cs
index 4116312c4d87..9c327d0451f7 100644
--- a/src/Dotnet.Watch/Watch/AppModels/WebApplicationAppModel.cs
+++ b/src/Dotnet.Watch/Watch/AppModels/WebApplicationAppModel.cs
@@ -14,7 +14,7 @@ internal abstract class WebApplicationAppModel(DotNetWatchContext context) : Hot
public const string ConnectionServerLogComponentName = "BrowserConnection:Server";
public const string ConnectionAgentLogComponentName = "BrowserConnection:Agent";
- // This needs to be in sync with the version BrowserRefreshMiddleware is compiled against.
+ // This needs to be in sync with the version the browser tools hosting startup is compiled against.
private static readonly Version s_minimumSupportedVersion = Versions.Version6_0;
private const string MiddlewareTargetFramework = "net6.0";
@@ -27,6 +27,12 @@ internal abstract class WebApplicationAppModel(DotNetWatchContext context) : Hot
///
public abstract ProjectGraphNode LaunchingProject { get; }
+ ///
+ /// Project whose browser initializer, settings document and pinned public key are served to the
+ /// browser. Usually the launching project; for hosted WebAssembly it is the client project.
+ ///
+ public virtual ProjectGraphNode BrowserToolsProject => LaunchingProject;
+
protected abstract ImmutableArray CreateManagedClients(ILogger clientLogger, ILogger agentLogger, BrowserRefreshServer? browserRefreshServer);
public async sealed override ValueTask CreateClientsAsync(ILogger clientLogger, ILogger agentLogger, CancellationToken cancellationToken)
@@ -45,29 +51,68 @@ protected WebAssemblyHotReloadClient CreateWebAssemblyClient(ILogger clientLogge
var capabilities = clientProject.GetWebAssemblyCapabilities().ToImmutableArray();
var targetFramework = clientProject.GetTargetFrameworkVersion() ?? throw new InvalidOperationException($"Project doesn't define {PropertyNames.TargetFrameworkMoniker}");
- return new WebAssemblyHotReloadClient(clientLogger, agentLogger, browserRefreshServer, capabilities, targetFramework, context.EnvironmentOptions.TestFlags.HasFlag(TestFlags.MockBrowser));
+ return new WebAssemblyHotReloadClient(clientLogger, agentLogger, browserRefreshServer, browserRefreshServer.ResetUpdates(), capabilities, targetFramework, context.EnvironmentOptions.TestFlags.HasFlag(TestFlags.MockBrowser));
}
private static string GetMiddlewareAssemblyPath()
=> GetInjectedAssemblyPath(MiddlewareTargetFramework, "Microsoft.AspNetCore.Watch.BrowserRefresh");
+ ///
+ /// Configures the application process to expose the browser tools provider on its own origin.
+ /// The default forwards the provider routes from a hosting startup injected into the app.
+ ///
+ internal virtual void ConfigureBrowserToolsLaunchEnvironment(IDictionary environment, AbstractBrowserRefreshServer browserRefreshServer)
+ => AddHostingStartupEnvironment(environment, browserRefreshServer, GetMiddlewareAssemblyPath());
+
+ internal static void AddHostingStartupEnvironment(IDictionary environment, AbstractBrowserRefreshServer browserRefreshServer, string middlewareAssemblyPath)
+ {
+ environment[MiddlewareEnvironmentVariables.AspNetCoreAutoReloadProviderAddress] = browserRefreshServer.ProviderAddress.AbsoluteUri;
+
+ // Loading the assembly as a startup hook makes the out-of-application BrowserRefresh
+ // assembly resolvable when ASP.NET Core activates its hosting startup by simple name.
+ environment.InsertListItem(MiddlewareEnvironmentVariables.DotNetStartupHooks, middlewareAssemblyPath, Path.PathSeparator);
+ environment.InsertListItem(MiddlewareEnvironmentVariables.AspNetCoreHostingStartupAssemblies, Path.GetFileNameWithoutExtension(middlewareAssemblyPath), MiddlewareEnvironmentVariables.AspNetCoreHostingStartupAssembliesSeparator);
+
+ if (browserRefreshServer.Logger.IsEnabled(LogLevel.Trace))
+ {
+ // enable debug logging from the hosting startup:
+ environment[MiddlewareEnvironmentVariables.LoggingLevel] = "Debug";
+ }
+ }
+
+ ///
+ /// Creates the browser tools provider for the project. The application host is configured by
+ /// to expose it on the app's own origin.
+ ///
+ /// Each connection is authenticated with the private half of the key pair the project's build
+ /// produced. The key is loaded when the browser connects, after dotnet run has built and
+ /// launched the application that serves the matching public half.
+ ///
public BrowserRefreshServer? TryCreateRefreshServer(ProjectGraphNode projectNode)
{
var logger = context.LoggerFactory.CreateLogger(ServerLogComponentName, projectNode.GetDisplayName());
- if (IsServerSupported(projectNode, logger))
+ if (!IsServerSupported(projectNode, logger))
+ {
+ return null;
+ }
+
+ if (BrowserToolsBuildOutputs.TryGetFor(projectNode, logger) is not { } browserToolsOutputs)
{
- return new BrowserRefreshServer(
- logger,
- connectionServerLoggerFactory: connectionId => context.LoggerFactory.CreateLogger(ConnectionServerLogComponentName, GetBrowserLoggerName(connectionId)),
- connectionAgentLoggerFactory: connectionId => context.LoggerFactory.CreateLogger(ConnectionAgentLogComponentName, GetBrowserLoggerName(connectionId)),
- middlewareAssemblyPath: GetMiddlewareAssemblyPath(),
- dotnetPath: context.EnvironmentOptions.GetMuxerPath(),
- webSocketConfig: context.EnvironmentOptions.BrowserWebSocketConfig,
- suppressTimeouts: context.EnvironmentOptions.TestFlags != TestFlags.None);
+ // The application has no pinned key, so nothing in the browser would ever connect to a
+ // provider. This is not an error: the project simply does not opt into browser tools.
+ return null;
}
- return null;
+ return new BrowserRefreshServer(
+ logger,
+ connectionServerLoggerFactory: connectionId => context.LoggerFactory.CreateLogger(ConnectionServerLogComponentName, GetBrowserLoggerName(connectionId)),
+ connectionAgentLoggerFactory: connectionId => context.LoggerFactory.CreateLogger(ConnectionAgentLogComponentName, GetBrowserLoggerName(connectionId)),
+ configureLaunchEnvironment: ConfigureBrowserToolsLaunchEnvironment,
+ dotnetPath: context.EnvironmentOptions.GetMuxerPath(),
+ sessionKeyFactory: browserToolsOutputs.CreateSessionKey,
+ webSocketConfig: context.EnvironmentOptions.BrowserWebSocketConfig,
+ suppressTimeouts: context.EnvironmentOptions.TestFlags != TestFlags.None);
}
private static string GetBrowserLoggerName(int connectionId)
diff --git a/src/Dotnet.Watch/Watch/Browser/BrowserRefreshServerFactory.cs b/src/Dotnet.Watch/Watch/Browser/BrowserRefreshServerFactory.cs
index 62e446b014f8..8f86e23b50d6 100644
--- a/src/Dotnet.Watch/Watch/Browser/BrowserRefreshServerFactory.cs
+++ b/src/Dotnet.Watch/Watch/Browser/BrowserRefreshServerFactory.cs
@@ -15,6 +15,10 @@ namespace Microsoft.DotNet.Watch;
/// Reload message is sent to the browser in that case.
///
/// The instances are also reused if the project file is updated or the project graph is reloaded.
+///
+/// Each connection loads the current browser tools session key from the key pair the project's
+/// build wrote to its intermediate output. Loading on connect allows the server to start before
+/// dotnet run builds the application and naturally observes key rotation after a clean.
///
internal sealed class BrowserRefreshServerFactory : IDisposable
{
@@ -45,13 +49,30 @@ public void Dispose()
bool hasExistingServer;
var key = projectNode.ProjectInstance.GetId();
+ var browserToolsProject = appModel.BrowserToolsProject;
lock (_serversGuard)
{
hasExistingServer = _servers.TryGetValue(key, out server);
+
+ if (server != null)
+ {
+ if (BrowserToolsBuildOutputs.TryGetFor(browserToolsProject, server.Logger) is not { } outputs)
+ {
+ server.Dispose();
+ _servers.Remove(key);
+ server = null;
+ hasExistingServer = false;
+ }
+ else
+ {
+ server.UpdateSessionKeyFactory(outputs.CreateSessionKey);
+ }
+ }
+
if (!hasExistingServer)
{
- server = appModel.TryCreateRefreshServer(projectNode);
+ server = appModel.TryCreateRefreshServer(browserToolsProject);
_servers.Add(key, server);
}
}
diff --git a/src/Dotnet.Watch/Watch/Browser/BrowserToolsBuildOutputs.cs b/src/Dotnet.Watch/Watch/Browser/BrowserToolsBuildOutputs.cs
new file mode 100644
index 000000000000..7f4ba05d86d9
--- /dev/null
+++ b/src/Dotnet.Watch/Watch/Browser/BrowserToolsBuildOutputs.cs
@@ -0,0 +1,271 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Security.Cryptography;
+using System.Text.Json;
+using Microsoft.Build.Execution;
+using Microsoft.Build.Graph;
+using Microsoft.DotNet.HotReload;
+using Microsoft.Extensions.Logging;
+
+namespace Microsoft.DotNet.Watch;
+
+///
+/// Thrown when a project produced browser tools build outputs that dotnet watch cannot use.
+/// The launch fails instead of silently continuing without browser tools, because a provider whose
+/// key the application does not pin can never be authenticated by the browser and every browser
+/// tools feature would appear to be broken for no visible reason.
+///
+internal sealed class BrowserToolsBuildOutputsException(string message) : Exception(message);
+
+///
+/// The build outputs the Static Web Assets SDK produces for the dotnet watch browser tools,
+/// and the only channel between the build and dotnet watch for them.
+///
+/// The direction of this channel is deliberate. The browser authenticates the provider with a key
+/// the application pins at build time, so the key has to be created by the build; a key that the
+/// watcher pushed into the build through a global property would let the provider authenticate
+/// itself, and a global property could not be scoped to a project anyway. The build therefore owns
+/// the key pair, and the watcher reads it back per project instance.
+///
+/// The paths are derived from evaluated MSBuild properties, the same way the static web assets
+/// manifest is located in , rather than by searching the file system.
+/// They must stay in sync with Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets.
+///
+internal sealed class BrowserToolsBuildOutputs
+{
+ ///
+ /// Subdirectory of the project's intermediate output that holds the browser tools build outputs.
+ ///
+ public const string DirectoryName = "dotnet-watch";
+
+ public const string PublicKeyFileName = "browser-tools-key.public.json";
+ public const string PrivateKeyFileName = "browser-tools-key.private.json";
+
+ private const int SupportedKeyDocumentVersion = 1;
+ private const string SupportedKeyAlgorithm = "RSA-OAEP-SHA256";
+ private const string PublicKeyFormat = "SubjectPublicKeyInfo";
+ private const string PrivateKeyFormat = "RSAParameters";
+
+ private readonly ILogger _logger;
+
+ public string ProjectPath { get; }
+ public string PublicKeyPath { get; }
+ public string PrivateKeyPath { get; }
+
+ private BrowserToolsBuildOutputs(string projectPath, string directory, ILogger logger)
+ {
+ _logger = logger;
+ ProjectPath = projectPath;
+ PublicKeyPath = Path.Combine(directory, PublicKeyFileName);
+ PrivateKeyPath = Path.Combine(directory, PrivateKeyFileName);
+ }
+
+ ///
+ /// Returns the build outputs of , or null when the project does
+ /// not produce browser tools assets at all. Whether it does is decided by evaluated properties
+ /// that mirror the condition on the target that produces them, so a project that opted out - or
+ /// an SDK that has no browser tools initializer - is recognized without touching the file
+ /// system.
+ ///
+ public static BrowserToolsBuildOutputs? TryGetFor(ProjectGraphNode projectNode, ILogger logger)
+ => TryGetFor(projectNode.ProjectInstance, logger);
+
+ public static BrowserToolsBuildOutputs? TryGetFor(ProjectInstance projectInstance, ILogger logger)
+ {
+ var enableHotReload = projectInstance.GetBooleanPropertyValue(
+ PropertyNames.EnableHotReloadInRuntimeConfigDevFile,
+ defaultValue: string.Equals(
+ projectInstance.GetPropertyValue(PropertyNames.Configuration),
+ "Debug",
+ StringComparison.OrdinalIgnoreCase));
+
+ if (!enableHotReload ||
+ projectInstance.GetPropertyValue(PropertyNames.DotNetWatchBrowserToolsAssetPrefix) is not { Length: > 0 } ||
+ !projectInstance.GetBooleanPropertyValue(PropertyNames.StaticWebAssetsEnabled) ||
+ !projectInstance.GetBooleanPropertyValue(PropertyNames.JSModulesEnabled))
+ {
+ logger.Log(MessageDescriptor.BrowserToolsAssetsNotProducedByProject);
+ return null;
+ }
+
+ if (projectInstance.GetIntermediateOutputDirectory() is not { } intermediateOutputDirectory)
+ {
+ logger.Log(MessageDescriptor.BrowserToolsAssetsNotProducedByProject);
+ return null;
+ }
+
+ return new BrowserToolsBuildOutputs(
+ projectInstance.FullPath,
+ Path.Combine(intermediateOutputDirectory, DirectoryName),
+ logger);
+ }
+
+ ///
+ /// Creates the outputs for a directory directly, bypassing project evaluation. Only used by
+ /// tests: production code always derives the directory from the project instance so that the
+ /// paths cannot drift from what the build wrote.
+ ///
+ internal static BrowserToolsBuildOutputs CreateForTesting(string projectPath, string directory, ILogger logger)
+ => new(projectPath, directory, logger);
+
+ ///
+ /// Creates the provider's session key from the private half the build produced, after checking
+ /// that it is the key the application pinned. Never logs key material.
+ ///
+ ///
+ /// The key documents are missing, malformed, or describe different keys.
+ ///
+ public SharedSecretProvider CreateSessionKey()
+ {
+ var pinnedPublicKey = ReadPinnedPublicKey();
+ var parameters = ReadPrivateKey(out var recordedPublicKey);
+
+ if (!string.Equals(pinnedPublicKey, recordedPublicKey, StringComparison.Ordinal))
+ {
+ throw Fail("the public and private key documents describe different keys");
+ }
+
+ SharedSecretProvider sessionKey;
+ try
+ {
+ sessionKey = new SharedSecretProvider(parameters);
+ }
+ catch (CryptographicException)
+ {
+ throw Fail("the private key could not be imported");
+ }
+
+ // The recorded value is not trusted on its own: the key that the provider will actually use
+ // has to be the key the application pinned, otherwise the browser rejects the provider.
+ if (!string.Equals(sessionKey.GetPublicKey(), pinnedPublicKey, StringComparison.Ordinal))
+ {
+ sessionKey.Dispose();
+ throw Fail("the private key does not match the public key the application pinned");
+ }
+
+ _logger.Log(MessageDescriptor.BrowserToolsUsingKeyFromBuild);
+ return sessionKey;
+ }
+
+ private string ReadPinnedPublicKey()
+ {
+ using var document = ReadDocument(PublicKeyPath);
+ ValidateHeader(document.RootElement, PublicKeyFormat, PublicKeyPath);
+ return ReadRequiredBase64(document.RootElement, "publicKey", PublicKeyPath);
+ }
+
+ private RSAParameters ReadPrivateKey(out string recordedPublicKey)
+ {
+ using var document = ReadDocument(PrivateKeyPath);
+ var root = document.RootElement;
+ ValidateHeader(root, PrivateKeyFormat, PrivateKeyPath);
+ recordedPublicKey = ReadRequiredBase64(root, "publicKey", PrivateKeyPath);
+
+ if (!root.TryGetProperty("parameters", out var parameters) || parameters.ValueKind != JsonValueKind.Object)
+ {
+ throw Fail($"'{Path.GetFileName(PrivateKeyPath)}' does not contain the private key components");
+ }
+
+ return new RSAParameters
+ {
+ Modulus = ReadRequiredBase64Bytes(parameters, "modulus", PrivateKeyPath),
+ Exponent = ReadRequiredBase64Bytes(parameters, "exponent", PrivateKeyPath),
+ D = ReadRequiredBase64Bytes(parameters, "d", PrivateKeyPath),
+ P = ReadRequiredBase64Bytes(parameters, "p", PrivateKeyPath),
+ Q = ReadRequiredBase64Bytes(parameters, "q", PrivateKeyPath),
+ DP = ReadRequiredBase64Bytes(parameters, "dp", PrivateKeyPath),
+ DQ = ReadRequiredBase64Bytes(parameters, "dq", PrivateKeyPath),
+ InverseQ = ReadRequiredBase64Bytes(parameters, "inverseQ", PrivateKeyPath),
+ };
+ }
+
+ private JsonDocument ReadDocument(string path)
+ {
+ byte[] content;
+ try
+ {
+ content = File.ReadAllBytes(path);
+ }
+ catch (FileNotFoundException)
+ {
+ throw Fail($"'{Path.GetFileName(path)}' was not produced by the build");
+ }
+ catch (DirectoryNotFoundException)
+ {
+ throw Fail($"'{Path.GetFileName(path)}' was not produced by the build");
+ }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException)
+ {
+ throw Fail($"'{Path.GetFileName(path)}' could not be read ({e.GetType().Name})");
+ }
+
+ try
+ {
+ return JsonDocument.Parse(content);
+ }
+ catch (JsonException)
+ {
+ throw Fail($"'{Path.GetFileName(path)}' is not a valid JSON document");
+ }
+ }
+
+ private void ValidateHeader(JsonElement root, string expectedFormat, string path)
+ {
+ var name = Path.GetFileName(path);
+
+ if (root.ValueKind != JsonValueKind.Object)
+ {
+ throw Fail($"'{name}' is not a JSON object");
+ }
+
+ if (!root.TryGetProperty("version", out var version) ||
+ version.ValueKind != JsonValueKind.Number ||
+ !version.TryGetInt32(out var versionValue) ||
+ versionValue != SupportedKeyDocumentVersion)
+ {
+ throw Fail($"'{name}' does not have the supported document version {SupportedKeyDocumentVersion}");
+ }
+
+ if (!root.TryGetProperty("algorithm", out var algorithm) ||
+ algorithm.ValueKind != JsonValueKind.String ||
+ algorithm.GetString() != SupportedKeyAlgorithm)
+ {
+ throw Fail($"'{name}' does not use the supported key algorithm");
+ }
+
+ if (!root.TryGetProperty("format", out var format) ||
+ format.ValueKind != JsonValueKind.String ||
+ format.GetString() != expectedFormat)
+ {
+ throw Fail($"'{name}' does not use the expected key format '{expectedFormat}'");
+ }
+ }
+
+ private string ReadRequiredBase64(JsonElement element, string propertyName, string path)
+ {
+ if (!element.TryGetProperty(propertyName, out var property) ||
+ property.ValueKind != JsonValueKind.String ||
+ property.GetString() is not { Length: > 0 } value)
+ {
+ throw Fail($"'{Path.GetFileName(path)}' does not contain '{propertyName}'");
+ }
+
+ try
+ {
+ _ = Convert.FromBase64String(value);
+ }
+ catch (FormatException)
+ {
+ throw Fail($"'{propertyName}' in '{Path.GetFileName(path)}' is not base64");
+ }
+
+ return value;
+ }
+
+ private byte[] ReadRequiredBase64Bytes(JsonElement element, string propertyName, string path)
+ => Convert.FromBase64String(ReadRequiredBase64(element, propertyName, path));
+
+ private BrowserToolsBuildOutputsException Fail(string reason)
+ => new($"Unable to start the dotnet-watch browser tools for '{ProjectPath}' because {reason}. Rebuild the project to regenerate the browser tools build outputs.");
+}
diff --git a/src/Dotnet.Watch/Watch/Build/BuildNames.cs b/src/Dotnet.Watch/Watch/Build/BuildNames.cs
index c909ea412dd1..2c667415436d 100644
--- a/src/Dotnet.Watch/Watch/Build/BuildNames.cs
+++ b/src/Dotnet.Watch/Watch/Build/BuildNames.cs
@@ -5,6 +5,7 @@ namespace Microsoft.DotNet.Watch;
internal static class PropertyNames
{
+ public const string Configuration = nameof(Configuration);
public const string TargetFramework = nameof(TargetFramework);
public const string TargetFrameworkIdentifier = nameof(TargetFrameworkIdentifier);
public const string TargetFrameworkMoniker = nameof(TargetFrameworkMoniker);
@@ -22,6 +23,12 @@ internal static class PropertyNames
public const string SkipCompilerExecution = nameof(SkipCompilerExecution);
public const string ProvideCommandLineArgs = nameof(ProvideCommandLineArgs);
public const string NonExistentFile = nameof(NonExistentFile);
+ // Evaluated properties that mirror the condition guarding the target which produces the browser
+ // tools build outputs. They are read, never set: the build owns the browser tools key pair and
+ // dotnet-watch discovers its outputs. See BrowserToolsBuildOutputs.
+ public const string DotNetWatchBrowserToolsAssetPrefix = nameof(DotNetWatchBrowserToolsAssetPrefix);
+ public const string StaticWebAssetsEnabled = nameof(StaticWebAssetsEnabled);
+ public const string JSModulesEnabled = nameof(JSModulesEnabled);
public const string StartupHookSupport = nameof(StartupHookSupport);
public const string MetadataUpdaterSupport = nameof(MetadataUpdaterSupport);
public const string Optimize = nameof(Optimize);
diff --git a/src/Dotnet.Watch/Watch/Build/BuildUtilities.cs b/src/Dotnet.Watch/Watch/Build/BuildUtilities.cs
index 1a336530697e..660956bfbbc5 100644
--- a/src/Dotnet.Watch/Watch/Build/BuildUtilities.cs
+++ b/src/Dotnet.Watch/Watch/Build/BuildUtilities.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Collections.Immutable;
+
namespace Microsoft.DotNet.Watch;
internal static class BuildUtilities
@@ -16,4 +18,15 @@ internal static class BuildUtilities
let value = argument[(eq + 1)..]
where name is not []
select (name, value);
+
+ public static ImmutableDictionary ParseBuildPropertiesToImmutableDictionary(IEnumerable arguments)
+ {
+ var properties = ImmutableDictionary.CreateBuilder(StringComparer.OrdinalIgnoreCase);
+ foreach (var (key, value) in ParseBuildProperties(arguments))
+ {
+ properties[key] = value;
+ }
+
+ return properties.ToImmutable();
+ }
}
diff --git a/src/Dotnet.Watch/Watch/Build/EvaluationResult.cs b/src/Dotnet.Watch/Watch/Build/EvaluationResult.cs
index d6fd67eabbab..9259a08dfe8c 100644
--- a/src/Dotnet.Watch/Watch/Build/EvaluationResult.cs
+++ b/src/Dotnet.Watch/Watch/Build/EvaluationResult.cs
@@ -38,12 +38,11 @@ public void WatchFileItems(FileWatcher fileWatcher)
includeSubdirectories: true);
}
- public static ImmutableDictionary GetGlobalBuildProperties(IEnumerable buildArguments, EnvironmentOptions environmentOptions)
+ public static ImmutableDictionary GetGlobalBuildProperties(IEnumerable buildArguments)
{
// See https://github.com/dotnet/project-system/blob/main/docs/well-known-project-properties.md
- return BuildUtilities.ParseBuildProperties(buildArguments)
- .ToImmutableDictionary(keySelector: arg => arg.key, elementSelector: arg => arg.value)
+ return BuildUtilities.ParseBuildPropertiesToImmutableDictionary(buildArguments)
.SetItem(PropertyNames.DesignTimeBuild, "true")
.SetItem(PropertyNames.SkipCompilerExecution, "true")
.SetItem(PropertyNames.ProvideCommandLineArgs, "true")
diff --git a/src/Dotnet.Watch/Watch/HotReload/HotReloadDotNetWatcher.cs b/src/Dotnet.Watch/Watch/HotReload/HotReloadDotNetWatcher.cs
index 4acd404db551..e0416b7ec1bc 100644
--- a/src/Dotnet.Watch/Watch/HotReload/HotReloadDotNetWatcher.cs
+++ b/src/Dotnet.Watch/Watch/HotReload/HotReloadDotNetWatcher.cs
@@ -53,9 +53,7 @@ public HotReloadDotNetWatcher(
_designTimeBuildGraphFactory = new ProjectGraphFactory(
context.RootProjects,
- buildProperties: EvaluationResult.GetGlobalBuildProperties(
- context.BuildArguments,
- context.EnvironmentOptions),
+ buildProperties: EvaluationResult.GetGlobalBuildProperties(context.BuildArguments),
context.BuildLogger,
context.Options,
context.EnvironmentOptions);
@@ -1304,7 +1302,7 @@ private async Task BuildFileOrProjectOrSolutionAsync(string path, string?
}
: null,
- // pass user-specified build arguments last to override defaults:
+ // dotnet-watch reserved properties are added after user-specified build arguments to override defaults:
Arguments = arguments
};
diff --git a/src/Dotnet.Watch/Watch/HotReload/RunningProjectsManager.cs b/src/Dotnet.Watch/Watch/HotReload/RunningProjectsManager.cs
index c637494b71e6..5e4dc7875c53 100644
--- a/src/Dotnet.Watch/Watch/HotReload/RunningProjectsManager.cs
+++ b/src/Dotnet.Watch/Watch/HotReload/RunningProjectsManager.cs
@@ -249,6 +249,10 @@ public async ValueTask ApplyManagedCodeAndStaticAssetUpdatesAndRelaunchAsync(
CancellationToken cancellationToken)
{
var applyTasks = new List();
+
+ // Tracked separately so that a browser or target process that reports a failed apply
+ // prevents dotnet-watch from reporting the changes as applied.
+ var managedCodeApplyTasks = new List>();
ImmutableDictionary> projectsToUpdate = [];
IReadOnlyList relaunchOperations;
@@ -315,7 +319,9 @@ public async ValueTask ApplyManagedCodeAndStaticAssetUpdatesAndRelaunchAsync(
applyOperationCancellationToken: runningProject.Process.ExitedCancellationToken,
cancellationToken);
- applyTasks.Add(runningProject.CompleteApplyOperationAsync(applyTask));
+ var managedCodeApplyTask = runningProject.CompleteApplyOperationAsync(applyTask);
+ applyTasks.Add(managedCodeApplyTask);
+ managedCodeApplyTasks.Add(managedCodeApplyTask);
}
}
}
@@ -346,7 +352,12 @@ async Task CompleteApplyOperationAsync()
var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
- if (builder.ManagedCodeUpdates.Count > 0)
+ // A client that could not apply the updates fails its apply task. Reporting the changes as
+ // applied in that case is a false positive, both in the console and on the notification
+ // channel that Aspire surfaces as a successful Hot Reload.
+ var managedCodeApplied = managedCodeApplyTasks.TrueForAll(static task => task.Result);
+
+ if (builder.ManagedCodeUpdates.Count > 0 && managedCodeApplied)
{
logger.Log(MessageDescriptor.ManagedCodeChangesApplied, elapsedMilliseconds);
}
@@ -356,9 +367,15 @@ async Task CompleteApplyOperationAsync()
logger.Log(MessageDescriptor.StaticAssetsChangesApplied, elapsedMilliseconds);
}
- logger.Log(MessageDescriptor.ChangesAppliedToProjectsNotification,
- projectsToUpdate.Select(e => e.Value.First().Options.Representation).Concat(
- builder.StaticAssetUpdates.Select(e => e.Key.Options.Representation)).Distinct());
+ var updatedProjects = (managedCodeApplied ? projectsToUpdate.Select(e => e.Value.First().Options.Representation) : [])
+ .Concat(builder.StaticAssetUpdates.Select(e => e.Key.Options.Representation))
+ .Distinct()
+ .ToArray();
+
+ if (updatedProjects is not [])
+ {
+ logger.Log(MessageDescriptor.ChangesAppliedToProjectsNotification, updatedProjects);
+ }
}
catch (OperationCanceledException)
{
diff --git a/src/Dotnet.Watch/Watch/Process/ProjectLauncher.cs b/src/Dotnet.Watch/Watch/Process/ProjectLauncher.cs
index e4b80b217f47..9b33e935755b 100644
--- a/src/Dotnet.Watch/Watch/Process/ProjectLauncher.cs
+++ b/src/Dotnet.Watch/Watch/Process/ProjectLauncher.cs
@@ -49,6 +49,7 @@ public RunningProjectsManager RunningProjectsManager
var agentLogger = context.LoggerFactory.CreateLogger(HotReloadDotNetWatcher.AgentLogComponentName, projectDisplayName);
var appModel = HotReloadAppModel.InferFromProject(context, projectNode);
+
var clients = await appModel.CreateClientsAsync(clientLogger, agentLogger, cancellationToken);
var processSpec = new ProcessSpec
diff --git a/src/Dotnet.Watch/Watch/Process/RunningProject.cs b/src/Dotnet.Watch/Watch/Process/RunningProject.cs
index 7c8eedccef6a..81e92bf108a5 100644
--- a/src/Dotnet.Watch/Watch/Process/RunningProject.cs
+++ b/src/Dotnet.Watch/Watch/Process/RunningProject.cs
@@ -76,15 +76,16 @@ public Task TerminateForRestartAsync()
return process.TerminateAsync();
}
- public async Task CompleteApplyOperationAsync(Task applyTask)
+ public async Task CompleteApplyOperationAsync(Task applyTask)
{
try
{
- await applyTask;
+ return await applyTask;
}
catch (OperationCanceledException)
{
// Do not report error.
+ return false;
}
catch (Exception e)
{
@@ -92,6 +93,7 @@ public async Task CompleteApplyOperationAsync(Task applyTask)
// it shouldn't prevent applying updates to other processes.
ClientLogger.LogError("Failed to apply updates to process {Process}: {Exception}", process.Id, e.ToString());
+ return false;
}
}
diff --git a/src/Dotnet.Watch/Watch/UI/IReporter.cs b/src/Dotnet.Watch/Watch/UI/IReporter.cs
index b705bf5939b2..cc7339f0a8d2 100644
--- a/src/Dotnet.Watch/Watch/UI/IReporter.cs
+++ b/src/Dotnet.Watch/Watch/UI/IReporter.cs
@@ -224,6 +224,8 @@ public static MessageDescriptor GetDescriptor(EventId id)
public static readonly MessageDescriptor ApplyUpdate_ChangingEntryPoint = Create("{0} Press \"Ctrl + R\" to restart.", Emoji.Warning, LogLevel.Warning);
public static readonly MessageDescriptor ConfiguredToLaunchBrowser = Create("Configured to launch a browser on ASP.NET Core application startup.", Emoji.Watch, LogLevel.Debug);
public static readonly MessageDescriptor UsingBrowserRefreshMiddleware = Create("Using browser-refresh middleware", Emoji.Default, LogLevel.Debug);
+ public static readonly MessageDescriptor BrowserToolsAssetsNotProducedByProject = Create("The project does not produce dotnet-watch browser tools assets. Browser tools are disabled for it.", Emoji.Watch, LogLevel.Debug);
+ public static readonly MessageDescriptor BrowserToolsUsingKeyFromBuild = Create("Using the dotnet-watch browser tools key produced by the build.", Emoji.Watch, LogLevel.Debug);
public static readonly MessageDescriptor BrowserRefreshSuppressedViaEnvironmentVariable_ManualRefreshRequired = Create("Browser refresh is suppressed via environment variable '{0}'. To reload static assets after an update refresh browser manually.", Emoji.Watch, LogLevel.Debug);
public static readonly MessageDescriptor BrowserRefreshSuppressedViaEnvironmentVariable_ApplicationWillBeRestarted = Create("Browser refresh is suppressed via environment variable '{0}'. Application will be restarted when updated.", Emoji.Watch, LogLevel.Warning);
public static readonly MessageDescriptor BrowserRefreshNotSupportedByProjectTargetFramework_ManualRefreshRequired = Create("Browser refresh is not supported by the project target framework. To reload static assets after an update refresh browser manually. For more information see 'https://aka.ms/dotnet/watch/unsupported-tfm'.", Emoji.Watch, LogLevel.Warning);
diff --git a/src/Dotnet.Watch/Web.Middleware/ApplicationPaths.cs b/src/Dotnet.Watch/Web.Middleware/ApplicationPaths.cs
index 776d6542a61d..dae96b004cb9 100644
--- a/src/Dotnet.Watch/Web.Middleware/ApplicationPaths.cs
+++ b/src/Dotnet.Watch/Web.Middleware/ApplicationPaths.cs
@@ -15,28 +15,32 @@ internal static class ApplicationPaths
/// /_framework/
public static PathString FrameworkRoot { get; } = "/_framework";
- ///
- /// An endpoint that responds with cache-clearing headers. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data#directives.
- ///
- /// /_framework/clear-browser-cache
- public static PathString ClearSiteData { get; } = FrameworkRoot + "/clear-browser-cache";
+ public static PathString BrowserTools { get; } = FrameworkRoot + "/dotnet-browser-tools";
///
- /// Returns a JS file that handles browser refresh and showing notifications.
+ /// The provider exposes the WebSocket endpoint, cache clearing endpoint, and a non-executable
+ /// settings response that reports its availability. Everything executable lives in the
+ /// application's own build output.
///
- /// /_framework/aspnetcore-browser-refresh.js
- public static PathString BrowserRefreshJS { get; } = FrameworkRoot + "/aspnetcore-browser-refresh.js";
+ public static PathString BrowserToolsConnect { get; } = BrowserTools + "/connect";
+
+ public static PathString BrowserToolsClearCache { get; } = BrowserTools + "/clear-cache";
+
+ public static PathString BrowserToolsHotReloadSettings { get; } = BrowserTools + "/hot-reload-settings.json";
///
- /// Hosts a middleware that can cache deltas sent by dotnet-watch.
+ /// Legacy replay endpoint probed by the .NET 9 WebAssembly runtime.
+ ///
+ /// WebAssemblyHotReload.ApplyPreviousDeltasAsync issues an unauthenticated
+ /// GET /_framework/blazor-hotreload as soon as its Hot Reload agent is created and reports an
+ /// error when the response is not a successful JSON payload. dotnet-watch replays updates over the
+ /// authenticated WebSocket instead, so the application answers this probe with an empty update set.
///
- /// /_framework/blazor-hotreload
- public static PathString BlazorHotReloadMiddleware { get; } = FrameworkRoot + "/blazor-hotreload";
+ public static PathString LegacyPreviousDeltas { get; } = FrameworkRoot + "/blazor-hotreload";
///
- /// Returns a JS file imported by BlazorWebAssembly as part of it's initialization. Contains
- /// scripts to apply deltas on app start.
+ /// The application hosted browser tools configuration module generated by the Web SDK. It is a
+ /// static web asset of the application, not a provider resource.
///
- /// /_framework/blazor-hotreload.js
- public static PathString BlazorHotReloadJS { get; } = FrameworkRoot + "/blazor-hotreload.js";
+ public static PathString BrowserToolsConfigJS { get; } = FrameworkRoot + "/Microsoft.NET.Sdk.BlazorWeb.DotNetWatch.BrowserTools.Config.js";
}
diff --git a/src/Dotnet.Watch/Web.Middleware/BlazorHotReload.js b/src/Dotnet.Watch/Web.Middleware/BlazorHotReload.js
deleted file mode 100644
index 87a203450f01..000000000000
--- a/src/Dotnet.Watch/Web.Middleware/BlazorHotReload.js
+++ /dev/null
@@ -1,23 +0,0 @@
-// Used by older versions of Microsoft.AspNetCore.Components.WebAssembly.
-// For back compat only to support WASM packages older than the SDK.
-
-export function receiveHotReload() {
- return BINDING.js_to_mono_obj(new Promise((resolve) => receiveHotReloadAsync().then(resolve(0))));
-}
-
-export async function receiveHotReloadAsync() {
- const response = await fetch('/_framework/blazor-hotreload');
- if (response.status === 200) {
- const updates = await response.json();
- if (updates) {
- try {
- updates.forEach(u => {
- u.deltas.forEach(d => window.Blazor._internal.applyHotReload(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta, d.updatedTypes));
- })
- } catch (error) {
- console.warn(error);
- return;
- }
- }
- }
-}
diff --git a/src/Dotnet.Watch/Web.Middleware/BlazorWasmHotReloadMiddleware.cs b/src/Dotnet.Watch/Web.Middleware/BlazorWasmHotReloadMiddleware.cs
deleted file mode 100644
index 6fd5bbce55bf..000000000000
--- a/src/Dotnet.Watch/Web.Middleware/BlazorWasmHotReloadMiddleware.cs
+++ /dev/null
@@ -1,209 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-#nullable enable
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Text.Json;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Primitives;
-using Microsoft.Net.Http.Headers;
-
-namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
-
-///
-/// A middleware that manages receiving and sending deltas from a BlazorWebAssembly app.
-/// This assembly is shared between Visual Studio and dotnet-watch. By putting some of the complexity
-/// in here, we can avoid duplicating work in watch and VS.
-///
-/// Mapped to .
-///
-internal sealed class BlazorWasmHotReloadMiddleware
-{
- internal sealed class Update
- {
- public int Id { get; set; }
- public Delta[] Deltas { get; set; } = default!;
- }
-
- internal sealed class Delta
- {
- public string ModuleId { get; set; } = default!;
- public string MetadataDelta { get; set; } = default!;
- public string ILDelta { get; set; } = default!;
- public string PdbDelta { get; set; } = default!;
- public int[] UpdatedTypes { get; set; } = default!;
- }
-
- private static readonly JsonSerializerOptions s_jsonSerializerOptions = new()
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
- };
-
- private static readonly char[] s_urlSeparators = [';', ','];
-
- private readonly IReadOnlyList _allowedOrigins;
- private readonly ILogger _logger;
-
- public BlazorWasmHotReloadMiddleware(RequestDelegate next, ILogger logger, IConfiguration configuration)
- {
- _logger = logger;
- _allowedOrigins = ParseServerUrls(logger, configuration[WebHostDefaults.ServerUrlsKey]);
- logger.LogDebug($"Middleware loaded. Allowed origins: {string.Join(";", _allowedOrigins.Select(a => a.ToString()))}");
- }
-
- internal List Updates { get; } = [];
-
- public Task InvokeAsync(HttpContext context)
- {
- // Multiple instances of the BlazorWebAssembly app could be running (multiple tabs or multiple browsers).
- // We want to avoid serialize reads and writes between then
- lock (Updates)
- {
- if (HttpMethods.IsGet(context.Request.Method))
- {
- return OnGet(context);
- }
- else if (HttpMethods.IsPost(context.Request.Method))
- {
- return OnPost(context);
- }
- else
- {
- context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
- return Task.CompletedTask;
- }
- }
-
- // Don't call next(). This middleware is terminal.
- }
-
- private async Task OnGet(HttpContext context)
- {
- if (Updates.Count == 0)
- {
- context.Response.StatusCode = StatusCodes.Status204NoContent;
- return;
- }
-
- await JsonSerializer.SerializeAsync(context.Response.Body, Updates, s_jsonSerializerOptions);
- }
-
- private async Task OnPost(HttpContext context)
- {
- var origin = context.Request.Headers[HeaderNames.Origin];
-
- _logger.LogDebug($"WASM middleware request {context.Request.Method} from {origin}");
-
- if (!IsAllowedOrigin(origin, _allowedOrigins))
- {
- context.Response.StatusCode = StatusCodes.Status403Forbidden;
- return;
- }
-
- if (context.Request.ContentType != "application/json")
- {
- context.Response.StatusCode = StatusCodes.Status400BadRequest;
- return;
- }
-
- var update = await JsonSerializer.DeserializeAsync(context.Request.Body, s_jsonSerializerOptions);
- if (update == null)
- {
- context.Response.StatusCode = StatusCodes.Status400BadRequest;
- return;
- }
-
- // It's possible that multiple instances of the BlazorWasm are simultaneously executing and could be posting the same deltas
- // We'll use the sequence id to ensure that we're not recording duplicate entries. Replaying duplicated values would cause
- // ApplyDelta to fail.
- if (Updates is [] || Updates[^1].Id < update.Id)
- {
- Updates.Add(update);
- }
- }
-
- internal static IReadOnlyList ParseServerUrls(ILogger logger, string? urls)
- {
- var result = new List();
- if (urls is null)
- {
- return result;
- }
-
- foreach (var value in urls.Split(s_urlSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
- {
- BindingAddress address;
- try
- {
- address = BindingAddress.Parse(value);
- }
- catch (FormatException)
- {
- // Ignore invalid URLs.
- logger.LogDebug($"Invalid binding address '{value}'");
- continue;
- }
-
- if (address.IsUnixPipe)
- {
- continue;
- }
-
- if (IsWildcardHost(address.Host))
- {
- address = BindingAddress.Parse($"{address.Scheme}://localhost:{address.Port}");
- }
-
- result.Add(address);
- }
-
- return result;
- }
-
- internal static bool IsAllowedOrigin(StringValues originHeader, IReadOnlyList allowedAddresses)
- {
- if (originHeader.Count != 1 ||
- !Uri.TryCreate(originHeader[0], UriKind.Absolute, out var requestOrigin) ||
- (requestOrigin.Scheme != Uri.UriSchemeHttp && requestOrigin.Scheme != Uri.UriSchemeHttps))
- {
- return false;
- }
-
- if (allowedAddresses is [])
- {
- return IsLoopbackHost(requestOrigin.Host);
- }
-
- foreach (var allowedAddress in allowedAddresses)
- {
- if (!string.Equals(allowedAddress.Scheme, requestOrigin.Scheme, StringComparison.OrdinalIgnoreCase) ||
- allowedAddress.Port != requestOrigin.Port)
- {
- continue;
- }
-
- if (string.Equals(allowedAddress.Host, requestOrigin.Host, StringComparison.OrdinalIgnoreCase) ||
- (IsLoopbackHost(allowedAddress.Host) && IsLoopbackHost(requestOrigin.Host)))
- {
- return true;
- }
- }
-
- return false;
- }
-
- private static bool IsWildcardHost(string host)
- => host is "*" or "+" or "0.0.0.0" or "[::]";
-
- private static bool IsLoopbackHost(string host)
- => host.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
- host is "127.0.0.1" or "[::1]";
-}
diff --git a/src/Dotnet.Watch/Web.Middleware/BrowserRefreshMiddleware.cs b/src/Dotnet.Watch/Web.Middleware/BrowserRefreshMiddleware.cs
deleted file mode 100644
index 3eb3e8843900..000000000000
--- a/src/Dotnet.Watch/Web.Middleware/BrowserRefreshMiddleware.cs
+++ /dev/null
@@ -1,255 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-#nullable enable
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Http.Features;
-using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Primitives;
-using Microsoft.Net.Http.Headers;
-
-namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
-
-public sealed class BrowserRefreshMiddleware
-{
- private static readonly MediaTypeHeaderValue s_textHtmlMediaType = new("text/html");
- private static readonly MediaTypeHeaderValue s_applicationJsonMediaType = new("application/json");
- private readonly RequestDelegate _next;
- private readonly ILogger _logger;
- private string? _dotnetModifiableAssemblies = GetNonEmptyEnvironmentVariableValue("DOTNET_MODIFIABLE_ASSEMBLIES");
- private string? _aspnetcoreBrowserTools = GetNonEmptyEnvironmentVariableValue("__ASPNETCORE_BROWSER_TOOLS");
-
- public BrowserRefreshMiddleware(RequestDelegate next, ILogger logger)
- {
- _next = next;
- _logger = logger;
-
- logger.LogDebug("Middleware loaded: DOTNET_MODIFIABLE_ASSEMBLIES={ModifiableAssemblies}, __ASPNETCORE_BROWSER_TOOLS={BrowserTools}", _dotnetModifiableAssemblies, _aspnetcoreBrowserTools);
- }
-
- private static string? GetNonEmptyEnvironmentVariableValue(string name)
- => Environment.GetEnvironmentVariable(name) is { Length: > 0 } value ? value : null;
-
- public async Task InvokeAsync(HttpContext context)
- {
- if (IsWebAssemblyBootRequest(context))
- {
- AttachWebAssemblyHeaders(context);
- await _next(context);
- }
- else if (IsBrowserDocumentRequest(context))
- {
- // Use a custom StreamWrapper to rewrite output on Write/WriteAsync
- using var responseStreamWrapper = new ResponseStreamWrapper(context, _logger);
- var originalBodyFeature = context.Features.Get();
- context.Features.Set(new StreamResponseBodyFeature(responseStreamWrapper));
-
- try
- {
- await _next(context);
-
- // We complete the wrapper stream to ensure that any intermediate buffers
- // get fully flushed to the response stream. This is also required to
- // reliably determine whether script injection was performed.
- await responseStreamWrapper.CompleteAsync();
- }
- finally
- {
- context.Features.Set(originalBodyFeature);
- }
-
- if (responseStreamWrapper.IsHtmlResponse)
- {
- if (responseStreamWrapper.ScriptInjectionPerformed)
- {
- Log.BrowserConfiguredForRefreshes(_logger);
- }
- else if (context.Response.Headers.TryGetValue(HeaderNames.ContentEncoding, out var contentEncodings))
- {
- Log.ResponseCompressionDetected(_logger, contentEncodings);
- }
- else
- {
- Log.FailedToConfiguredForRefreshes(_logger);
- }
- }
- }
- else
- {
- await _next(context);
- }
- }
-
- private void AttachWebAssemblyHeaders(HttpContext context)
- {
- context.Response.OnStarting(() =>
- {
- if (!context.Response.Headers.ContainsKey("DOTNET-MODIFIABLE-ASSEMBLIES"))
- {
- if (_dotnetModifiableAssemblies != null)
- {
- context.Response.Headers.Append("DOTNET-MODIFIABLE-ASSEMBLIES", _dotnetModifiableAssemblies);
- }
- else
- {
- _logger.LogDebug("DOTNET_MODIFIABLE_ASSEMBLIES environment variable is not set, likely because hot reload is not enabled. The browser refresh feature may not work as expected.");
- }
- }
- else
- {
- _logger.LogDebug("DOTNET-MODIFIABLE-ASSEMBLIES header is already set.");
- }
-
- if (!context.Response.Headers.ContainsKey("ASPNETCORE-BROWSER-TOOLS"))
- {
- if (_aspnetcoreBrowserTools != null)
- {
- context.Response.Headers.Append("ASPNETCORE-BROWSER-TOOLS", _aspnetcoreBrowserTools);
- }
- else
- {
- _logger.LogDebug("__ASPNETCORE_BROWSER_TOOLS environment variable is not set. The browser refresh feature may not work as expected.");
- }
- }
- else
- {
- _logger.LogDebug("ASPNETCORE-BROWSER-TOOLS header is already set.");
- }
-
- return Task.CompletedTask;
- });
- }
-
- internal static bool IsWebAssemblyBootRequest(HttpContext context)
- {
- var request = context.Request;
- if (!HttpMethods.IsGet(request.Method))
- {
- return false;
- }
-
- if (request.Headers.TryGetValue("Sec-Fetch-Dest", out var values) &&
- !StringValues.IsNullOrEmpty(values) &&
- !string.Equals(values[0], "empty", StringComparison.OrdinalIgnoreCase))
- {
- // See https://github.com/dotnet/aspnetcore/issues/37326.
- // Only inject scripts that are destined for a browser page.
- return false;
- }
-
- if (!request.Path.HasValue ||
- !string.Equals(Path.GetFileName(request.Path.Value), "blazor.boot.json", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
-
- var typedHeaders = request.GetTypedHeaders();
- if (typedHeaders.Accept is not IList acceptHeaders)
- {
- return false;
- }
-
- for (var i = 0; i < acceptHeaders.Count; i++)
- {
- if (acceptHeaders[i].MatchesAllTypes || acceptHeaders[i].IsSubsetOf(s_applicationJsonMediaType))
- {
- return true;
- }
- }
-
- return false;
- }
-
- internal static bool IsBrowserDocumentRequest(HttpContext context)
- {
- var request = context.Request;
- if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsPost(request.Method))
- {
- return false;
- }
-
- if (request.Headers.TryGetValue("Sec-Fetch-Dest", out var values) &&
- !StringValues.IsNullOrEmpty(values) &&
- !string.Equals(values[0], "document", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(values[0], "frame", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(values[0], "iframe", StringComparison.OrdinalIgnoreCase) &&
- !IsProgressivelyEnhancedNavigation(context.Request))
- {
- // See https://github.com/dotnet/aspnetcore/issues/37326.
- // Only inject scripts that are destined for a browser page.
- return false;
- }
-
- var typedHeaders = request.GetTypedHeaders();
- if (typedHeaders.Accept is not IList acceptHeaders)
- {
- return false;
- }
-
- for (var i = 0; i < acceptHeaders.Count; i++)
- {
- if (acceptHeaders[i].IsSubsetOf(s_textHtmlMediaType))
- {
- return true;
- }
- }
-
- return false;
- }
-
- private static bool IsProgressivelyEnhancedNavigation(HttpRequest request)
- {
- // This is an exact copy from https://github.com/dotnet/aspnetcore/blob/bb2d778dc66aa998ea8e26db0e98e7e01423ff78/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Streaming.cs#L327-L332
- // For enhanced nav, the Blazor JS code controls the "accept" header precisely, so we can be very specific about the format
- var accept = request.Headers.Accept;
- return accept.Count == 1 && string.Equals(accept[0]!, "text/html; blazor-enhanced-nav=on", StringComparison.Ordinal);
- }
-
- internal void Test_SetEnvironment(string dotnetModifiableAssemblies, string aspnetcoreBrowserTools)
- {
- _dotnetModifiableAssemblies = dotnetModifiableAssemblies;
- _aspnetcoreBrowserTools = aspnetcoreBrowserTools;
- }
-
- internal static class Log
- {
- private static readonly Action _setupResponseForBrowserRefresh = LoggerMessage.Define(
- LogLevel.Debug,
- new EventId(1, "SetUpResponseForBrowserRefresh"),
- "Response markup is scheduled to include browser refresh script injection.");
-
- private static readonly Action _browserConfiguredForRefreshes = LoggerMessage.Define(
- LogLevel.Debug,
- new EventId(2, "BrowserConfiguredForRefreshes"),
- "Response markup was updated to include browser refresh script injection.");
-
- private static readonly Action _failedToConfigureForRefreshes = LoggerMessage.Define(
- LogLevel.Warning,
- new EventId(3, "FailedToConfiguredForRefreshes"),
- "Unable to configure browser refresh script injection on the response. " +
- $"Consider manually adding '{ScriptInjectingStream.InjectedScript}' to the body of the page.");
-
- private static readonly Action _responseCompressionDetected = LoggerMessage.Define(
- LogLevel.Warning,
- new EventId(4, "ResponseCompressionDetected"),
- "Unable to configure browser refresh script injection on the response. " +
- $"This may have been caused by the response's {HeaderNames.ContentEncoding}: '{{encoding}}'. " +
- "Consider disabling response compression.");
-
- private static readonly Action _scriptInjectionSkipped = LoggerMessage.Define(
- LogLevel.Debug,
- new EventId(6, "ScriptInjectionSkipped"),
- "Browser refresh script injection skipped. Status code: {StatusCode}, Content type: {ContentType}");
-
- public static void SetupResponseForBrowserRefresh(ILogger logger) => _setupResponseForBrowserRefresh(logger, null);
- public static void BrowserConfiguredForRefreshes(ILogger logger) => _browserConfiguredForRefreshes(logger, null);
- public static void FailedToConfiguredForRefreshes(ILogger logger) => _failedToConfigureForRefreshes(logger, null);
- public static void ResponseCompressionDetected(ILogger logger, StringValues encoding) => _responseCompressionDetected(logger, encoding, null);
- public static void ScriptInjectionSkipped(ILogger logger, int statusCode, string? contentType) => _scriptInjectionSkipped(logger, statusCode, contentType, null);
- }
-}
diff --git a/src/Dotnet.Watch/Web.Middleware/BrowserRefreshTagHelperComponent.cs b/src/Dotnet.Watch/Web.Middleware/BrowserRefreshTagHelperComponent.cs
new file mode 100644
index 000000000000..6942c7ca1f1d
--- /dev/null
+++ b/src/Dotnet.Watch/Web.Middleware/BrowserRefreshTagHelperComponent.cs
@@ -0,0 +1,38 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using System;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.Razor.TagHelpers;
+using Microsoft.AspNetCore.Razor.TagHelpers;
+
+namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
+
+///
+/// Appends the application hosted browser tools configuration module to MVC and Razor Pages
+/// responses. The module and the client it imports are part of the application's build output, so
+/// the browser never executes code obtained from the provider it authenticates.
+///
+internal sealed class BrowserRefreshTagHelperComponent(IHttpContextAccessor httpContextAccessor) : ITagHelperComponent
+{
+ public int Order => int.MaxValue;
+
+ public void Init(TagHelperContext context)
+ {
+ }
+
+ public Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
+ {
+ if (string.Equals(context.TagName, "body", StringComparison.OrdinalIgnoreCase))
+ {
+ // Static web assets are served under the application's path base.
+ var pathBase = httpContextAccessor.HttpContext?.Request.PathBase ?? default;
+ output.PostContent.AppendHtml($"");
+ }
+
+ return Task.CompletedTask;
+ }
+}
diff --git a/src/Dotnet.Watch/Web.Middleware/BrowserScriptMiddleware.cs b/src/Dotnet.Watch/Web.Middleware/BrowserScriptMiddleware.cs
deleted file mode 100644
index f8874807250d..000000000000
--- a/src/Dotnet.Watch/Web.Middleware/BrowserScriptMiddleware.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-#nullable enable
-
-using System;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Logging;
-
-namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
-
-///
-/// Responds with the contents of WebSocketScriptInjection.js with the stub WebSocket url replaced by the
-/// one specified by the launching app.
-///
-public sealed class BrowserScriptMiddleware
-{
- private readonly PathString _scriptPath;
- private readonly ReadOnlyMemory _scriptBytes;
- private readonly ILogger _logger;
- private readonly string _contentLength;
-
- public BrowserScriptMiddleware(RequestDelegate next, PathString scriptPath, ReadOnlyMemory scriptBytes, ILogger logger)
- {
- _scriptPath = scriptPath;
- _scriptBytes = scriptBytes;
- _logger = logger;
- _contentLength = _scriptBytes.Length.ToString(CultureInfo.InvariantCulture);
-
- logger.LogDebug("Middleware loaded. Script {scriptPath} ({size} B).", scriptPath, _contentLength);
- }
-
- public async Task InvokeAsync(HttpContext context)
- {
- context.Response.Headers["Cache-Control"] = "no-store";
- context.Response.Headers["Content-Length"] = _contentLength;
- context.Response.Headers["Content-Type"] = "application/javascript; charset=utf-8";
-
- await context.Response.Body.WriteAsync(_scriptBytes, context.RequestAborted);
-
- _logger.LogDebug("Script injected: {scriptPath}", _scriptPath);
- }
-
- // for backwards compat only
- internal static ReadOnlyMemory GetBlazorHotReloadJS()
- {
- var jsFileName = "BlazorHotReload.js";
- using var stream = new MemoryStream();
- var manifestStream = typeof(BrowserScriptMiddleware).Assembly.GetManifestResourceStream(jsFileName)!;
- manifestStream.CopyTo(stream);
-
- return stream.ToArray();
- }
-
- internal static ReadOnlyMemory GetBrowserRefreshJS()
- {
- var endpoint = Environment.GetEnvironmentVariable("ASPNETCORE_AUTO_RELOAD_WS_ENDPOINT")!;
- var serverKey = Environment.GetEnvironmentVariable("ASPNETCORE_AUTO_RELOAD_WS_KEY") ?? string.Empty;
-
- return GetWebSocketClientJavaScript(endpoint, serverKey);
- }
-
- internal static ReadOnlyMemory GetWebSocketClientJavaScript(string hostString, string serverKey)
- {
- var jsFileName = "WebSocketScriptInjection.js";
- using var reader = new StreamReader(typeof(BrowserScriptMiddleware).Assembly.GetManifestResourceStream(jsFileName)!);
- var script = reader.ReadToEnd()
- .Replace("{{hostString}}", hostString)
- .Replace("{{ServerKey}}", serverKey);
-
- return Encoding.UTF8.GetBytes(script);
- }
-}
diff --git a/src/Dotnet.Watch/Web.Middleware/BrowserToolsEnvironment.cs b/src/Dotnet.Watch/Web.Middleware/BrowserToolsEnvironment.cs
new file mode 100644
index 000000000000..0ec1d3e6eceb
--- /dev/null
+++ b/src/Dotnet.Watch/Web.Middleware/BrowserToolsEnvironment.cs
@@ -0,0 +1,36 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using System;
+using System.Net;
+
+namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
+
+internal static class BrowserToolsEnvironment
+{
+ public const string ProviderAddress = "ASPNETCORE_AUTO_RELOAD_PROVIDER_ADDRESS";
+
+ public static Uri GetProviderAddress()
+ {
+ var value = Environment.GetEnvironmentVariable(ProviderAddress);
+ if (string.IsNullOrEmpty(value))
+ {
+ throw new InvalidOperationException($"The required browser tools provider address is not configured in '{ProviderAddress}'.");
+ }
+
+ if (!Uri.TryCreate(value, UriKind.Absolute, out var address) ||
+ address.Scheme != Uri.UriSchemeHttp ||
+ !IsLoopbackHost(address))
+ {
+ throw new InvalidOperationException($"The configured browser tools provider address '{value}' is not a loopback HTTP address.");
+ }
+
+ return address;
+ }
+
+ private static bool IsLoopbackHost(Uri address)
+ => string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase) ||
+ (IPAddress.TryParse(address.Host, out var ipAddress) && IPAddress.IsLoopback(ipAddress));
+}
diff --git a/src/Dotnet.Watch/Web.Middleware/BrowserToolsForwarder.cs b/src/Dotnet.Watch/Web.Middleware/BrowserToolsForwarder.cs
new file mode 100644
index 000000000000..954f70537fcc
--- /dev/null
+++ b/src/Dotnet.Watch/Web.Middleware/BrowserToolsForwarder.cs
@@ -0,0 +1,290 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using System;
+using System.Buffers;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.WebSockets;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Primitives;
+
+namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
+
+internal sealed class BrowserToolsForwarder : IDisposable
+{
+ private static readonly HashSet s_hopByHopHeaders = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "Connection",
+ "Keep-Alive",
+ "Proxy-Authenticate",
+ "Proxy-Authorization",
+ "TE",
+ "Trailer",
+ "Transfer-Encoding",
+ "Upgrade",
+ };
+
+ private readonly Uri _providerAddress;
+ private readonly HttpClient _httpClient;
+ private readonly ILogger _logger;
+
+ // ClientWebSocketOptions.CollectHttpResponseDetails and ClientWebSocket.HttpStatusCode were added in
+ // .NET 7. This assembly targets the lowest runtime it can be injected into, but it executes on the
+ // application's runtime, which is newer in practice. Without them a failed upgrade only reports
+ // WebSocketError.NotAWebSocket, which says the provider answered with some HTTP status but not which
+ // one, so an older host keeps the previous gateway-error behavior rather than inventing a status.
+ private static readonly PropertyInfo? s_collectHttpResponseDetails =
+ typeof(ClientWebSocketOptions).GetProperty("CollectHttpResponseDetails", BindingFlags.Public | BindingFlags.Instance);
+
+ private static readonly PropertyInfo? s_httpStatusCode =
+ typeof(ClientWebSocket).GetProperty("HttpStatusCode", BindingFlags.Public | BindingFlags.Instance);
+
+ public BrowserToolsForwarder(Uri providerAddress, ILogger logger)
+ {
+ _providerAddress = providerAddress;
+ _logger = logger;
+ _httpClient = new HttpClient(new SocketsHttpHandler
+ {
+ AllowAutoRedirect = false,
+ AutomaticDecompression = DecompressionMethods.None,
+ UseCookies = false,
+ UseProxy = false,
+ });
+ }
+
+ public Task ForwardAsync(HttpContext context)
+ => context.WebSockets.IsWebSocketRequest
+ ? ForwardWebSocketAsync(context)
+ : ForwardHttpAsync(context);
+
+ public void Dispose()
+ => _httpClient.Dispose();
+
+ private async Task ForwardHttpAsync(HttpContext context)
+ {
+ using var request = new HttpRequestMessage(
+ new HttpMethod(context.Request.Method),
+ CreateProviderUri(context.Request.Path, context.Request.QueryString));
+
+ if (context.Request.ContentLength is not null || context.Request.Headers.ContainsKey("Transfer-Encoding"))
+ {
+ request.Content = new StreamContent(context.Request.Body);
+ }
+
+ CopyRequestHeaders(context.Request.Headers, request);
+
+ try
+ {
+ using var response = await _httpClient.SendAsync(
+ request,
+ HttpCompletionOption.ResponseHeadersRead,
+ context.RequestAborted);
+
+ context.Response.StatusCode = (int)response.StatusCode;
+ CopyResponseHeaders(response.Headers, context.Response.Headers);
+ CopyResponseHeaders(response.Content.Headers, context.Response.Headers);
+ await response.Content.CopyToAsync(context.Response.Body, context.RequestAborted);
+ }
+ catch (HttpRequestException exception)
+ {
+ _logger.LogError(exception, "Unable to forward a browser tools HTTP request to the provider.");
+ if (!context.Response.HasStarted)
+ {
+ context.Response.StatusCode = StatusCodes.Status502BadGateway;
+ }
+ }
+ }
+
+ private async Task ForwardWebSocketAsync(HttpContext context)
+ {
+ using var providerSocket = new ClientWebSocket();
+ providerSocket.Options.Proxy = null;
+ TryCollectHttpResponseDetails(providerSocket.Options);
+
+ foreach (var protocol in context.WebSockets.WebSocketRequestedProtocols)
+ {
+ providerSocket.Options.AddSubProtocol(protocol);
+ }
+
+ CopyWebSocketRequestHeader(context, providerSocket.Options, "Origin");
+ CopyWebSocketRequestHeader(context, providerSocket.Options, "User-Agent");
+
+ try
+ {
+ await providerSocket.ConnectAsync(
+ CreateProviderWebSocketUri(context.Request.Path, context.Request.QueryString),
+ context.RequestAborted);
+ }
+ catch (WebSocketException exception)
+ {
+ // The provider rejects an unauthenticated browser before upgrading the connection, so its
+ // deliberate pre-upgrade status is part of the contract and must survive the hop through the
+ // application origin. Only an error status the provider actually produced is forwarded; a
+ // genuine upstream or network failure, or a handshake that failed after the provider had
+ // already switched protocols, has none and stays a gateway error.
+ var providerStatus = TryGetProviderStatusCode(providerSocket);
+ if (providerStatus is int status)
+ {
+ _logger.LogDebug(
+ "The browser tools provider rejected a WebSocket handshake with status {StatusCode}.",
+ status);
+ context.Response.StatusCode = status;
+ return;
+ }
+
+ _logger.LogError(exception, "Unable to connect to the browser tools WebSocket provider.");
+ context.Response.StatusCode = StatusCodes.Status502BadGateway;
+ return;
+ }
+
+ using var browserSocket = await context.WebSockets.AcceptWebSocketAsync(providerSocket.SubProtocol);
+ using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
+
+ var browserToProvider = PumpWebSocketAsync(browserSocket, providerSocket, cancellationSource.Token);
+ var providerToBrowser = PumpWebSocketAsync(providerSocket, browserSocket, cancellationSource.Token);
+
+ try
+ {
+ await Task.WhenAll(browserToProvider, providerToBrowser);
+ }
+ catch
+ {
+ cancellationSource.Cancel();
+ providerSocket.Abort();
+ browserSocket.Abort();
+ throw;
+ }
+ }
+
+ // Enables the upstream response details on runtimes that support them. Best effort: when the property
+ // is missing the socket simply reports no status and the caller falls back to a gateway error.
+ private static void TryCollectHttpResponseDetails(ClientWebSocketOptions options)
+ => s_collectHttpResponseDetails?.SetValue(options, true);
+
+ // Returns the HTTP status the provider rejected the upgrade with, or null when it produced none or
+ // answered something other than a rejection. With CollectHttpResponseDetails the runtime records the
+ // status before it validates the upgrade response, so a 101 whose handshake later failed validation is
+ // also reported here; relaying that would make the application claim a protocol switch that never
+ // happened. Only an error status is a deliberate rejection; anything else is a gateway failure.
+ private static int? TryGetProviderStatusCode(ClientWebSocket socket)
+ {
+ if (s_httpStatusCode?.GetValue(socket) is HttpStatusCode statusCode && (int)statusCode >= 400)
+ {
+ return (int)statusCode;
+ }
+
+ return null;
+ }
+
+ private Uri CreateProviderUri(PathString path, QueryString query)
+ {
+ var builder = new UriBuilder(_providerAddress)
+ {
+ Path = path.Value,
+ Query = query.HasValue ? query.Value![1..] : string.Empty,
+ };
+ return builder.Uri;
+ }
+
+ private Uri CreateProviderWebSocketUri(PathString path, QueryString query)
+ {
+ var builder = new UriBuilder(CreateProviderUri(path, query))
+ {
+ Scheme = Uri.UriSchemeWs,
+ };
+ return builder.Uri;
+ }
+
+ private static void CopyRequestHeaders(IHeaderDictionary source, HttpRequestMessage destination)
+ {
+ foreach (var (name, values) in source)
+ {
+ if (string.Equals(name, "Host", StringComparison.OrdinalIgnoreCase) || s_hopByHopHeaders.Contains(name))
+ {
+ continue;
+ }
+
+ if (!destination.Headers.TryAddWithoutValidation(name, values.ToArray()) && destination.Content != null)
+ {
+ destination.Content.Headers.TryAddWithoutValidation(name, values.ToArray());
+ }
+ }
+ }
+
+ private static void CopyResponseHeaders(
+ IEnumerable>> source,
+ IHeaderDictionary destination)
+ {
+ foreach (var (name, values) in source)
+ {
+ if (!s_hopByHopHeaders.Contains(name))
+ {
+ destination[name] = new StringValues([.. values]);
+ }
+ }
+ }
+
+ private static void CopyWebSocketRequestHeader(
+ HttpContext context,
+ ClientWebSocketOptions options,
+ string headerName)
+ {
+ if (context.Request.Headers.TryGetValue(headerName, out var value) && !StringValues.IsNullOrEmpty(value))
+ {
+ options.SetRequestHeader(headerName, value.ToString());
+ }
+ }
+
+ internal static async Task PumpWebSocketAsync(
+ WebSocket source,
+ WebSocket destination,
+ CancellationToken cancellationToken)
+ {
+ var buffer = ArrayPool.Shared.Rent(16 * 1024);
+ try
+ {
+ while (source.State is WebSocketState.Open or WebSocketState.CloseSent)
+ {
+ var result = await source.ReceiveAsync(new ArraySegment(buffer), cancellationToken);
+ if (result.MessageType == WebSocketMessageType.Close)
+ {
+ if (destination.State is WebSocketState.Open or WebSocketState.CloseReceived)
+ {
+ try
+ {
+ await destination.CloseOutputAsync(
+ result.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
+ result.CloseStatusDescription,
+ cancellationToken);
+ }
+ catch (WebSocketException) when (destination.State is WebSocketState.Aborted or WebSocketState.Closed)
+ {
+ // The peer can disappear between the state check and close propagation.
+ }
+ }
+
+ return;
+ }
+
+ await destination.SendAsync(
+ new ArraySegment(buffer, 0, result.Count),
+ result.MessageType,
+ result.EndOfMessage,
+ cancellationToken);
+ }
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(buffer);
+ }
+ }
+}
diff --git a/src/Dotnet.Watch/Web.Middleware/HostingStartup.cs b/src/Dotnet.Watch/Web.Middleware/HostingStartup.cs
index ecd9a879a750..b864ddfb9230 100644
--- a/src/Dotnet.Watch/Web.Middleware/HostingStartup.cs
+++ b/src/Dotnet.Watch/Web.Middleware/HostingStartup.cs
@@ -4,11 +4,13 @@
#nullable enable
using System;
-using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Logging;
[assembly: HostingStartup(typeof(Microsoft.AspNetCore.Watch.BrowserRefresh.HostingStartup))]
@@ -18,44 +20,51 @@ internal sealed class HostingStartup : IHostingStartup, IStartupFilter
{
public void Configure(IWebHostBuilder builder)
{
- builder.ConfigureServices(services => services.TryAddEnumerable(ServiceDescriptor.Singleton(this)));
+ builder.ConfigureServices(services => ConfigureServices(services, BrowserToolsEnvironment.GetProviderAddress()));
+ }
+
+ internal void ConfigureServices(IServiceCollection services, Uri providerAddress)
+ {
+ services.TryAddEnumerable(ServiceDescriptor.Singleton(this));
+ services.TryAddSingleton(services => new BrowserToolsForwarder(providerAddress, services.GetRequiredService>()));
+ services.AddHttpContextAccessor();
+ services.TryAddEnumerable(ServiceDescriptor.Singleton());
}
public Action Configure(Action next)
{
return app =>
{
+ // Only the endpoints the provider actually exposes are forwarded. The route is registered
+ // ahead of UsePathBase so it is absolute, which matches the route pinned into the
+ // generated configuration module.
app.MapWhen(
- static (context) =>
- {
- var path = context.Request.Path;
- return path.StartsWithSegments(ApplicationPaths.FrameworkRoot) &&
- (path.StartsWithSegments(ApplicationPaths.ClearSiteData) ||
- path.StartsWithSegments(ApplicationPaths.BlazorHotReloadMiddleware) ||
- path.StartsWithSegments(ApplicationPaths.BrowserRefreshJS) ||
- path.StartsWithSegments(ApplicationPaths.BlazorHotReloadJS));
- },
- static app =>
+ static context =>
+ context.Request.Path.Equals(ApplicationPaths.BrowserToolsConnect, StringComparison.Ordinal) ||
+ context.Request.Path.Equals(ApplicationPaths.BrowserToolsClearCache, StringComparison.Ordinal) ||
+ context.Request.Path.Equals(ApplicationPaths.BrowserToolsHotReloadSettings, StringComparison.Ordinal),
+ static browserTools =>
{
- app.Map(ApplicationPaths.ClearSiteData, static app => app.Run(context =>
- {
- // Scoped css files can contain links to other css files. We'll try clearing out the http caches to force the browser to re-download.
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data#directives
- context.Response.Headers["Clear-Site-Data"] = "\"cache\"";
- return Task.CompletedTask;
- }));
-
- app.Map(ApplicationPaths.BlazorHotReloadMiddleware, static app => app.UseMiddleware());
-
- app.Map(ApplicationPaths.BrowserRefreshJS,
- static app => app.UseMiddleware(ApplicationPaths.BrowserRefreshJS, BrowserScriptMiddleware.GetBrowserRefreshJS()));
-
- // backwards compat only:
- app.Map(ApplicationPaths.BlazorHotReloadJS,
- static app => app.UseMiddleware(ApplicationPaths.BlazorHotReloadJS, BrowserScriptMiddleware.GetBlazorHotReloadJS()));
+ browserTools.UseWebSockets();
+ browserTools.Run(
+ context => context.RequestServices.GetRequiredService().ForwardAsync(context));
});
- app.UseMiddleware();
+ // The .NET 9 WebAssembly runtime probes the legacy HTTP replay endpoint when its Hot Reload
+ // agent starts and reports an error unless it receives a successful JSON response. Updates
+ // produced before a browser connected are replayed over the authenticated WebSocket, so the
+ // application answers the probe locally with an empty update set. Nothing is forwarded to the
+ // provider and no update is ever served over this unauthenticated route.
+ app.MapWhen(
+ static context =>
+ HttpMethods.IsGet(context.Request.Method) &&
+ context.Request.Path.Equals(ApplicationPaths.LegacyPreviousDeltas, StringComparison.OrdinalIgnoreCase),
+ static legacyReplay => legacyReplay.Run(static context =>
+ {
+ context.Response.ContentType = "application/json";
+ return context.Response.WriteAsync("[]", context.RequestAborted);
+ }));
+
next(app);
};
}
diff --git a/src/Dotnet.Watch/Web.Middleware/ResponseStreamWrapper.cs b/src/Dotnet.Watch/Web.Middleware/ResponseStreamWrapper.cs
deleted file mode 100644
index d5b77aa68257..000000000000
--- a/src/Dotnet.Watch/Web.Middleware/ResponseStreamWrapper.cs
+++ /dev/null
@@ -1,198 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-#nullable enable
-
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.IO.Compression;
-using System.IO.Pipelines;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Logging;
-using Microsoft.Net.Http.Headers;
-
-namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
-
-///
-/// Wraps the Response Stream to inject the WebSocket HTML into
-/// an HTML Page.
-///
-public class ResponseStreamWrapper : Stream
-{
- private static readonly MediaTypeHeaderValue s_textHtmlMediaType = new("text/html");
-
- private readonly HttpContext _context;
- private readonly ILogger _logger;
- private bool? _isHtmlResponse;
-
- private Stream _baseStream;
- private ScriptInjectingStream? _scriptInjectingStream;
- private Pipe? _pipe;
- private Task? _gzipCopyTask;
- private bool _disposed;
-
- public ResponseStreamWrapper(HttpContext context, ILogger logger)
- {
- _context = context;
- _baseStream = context.Response.Body;
- _logger = logger;
- }
-
- public override bool CanRead => false;
- public override bool CanSeek => false;
- public override bool CanWrite => true;
- public override long Length { get; }
- public override long Position { get; set; }
- public bool ScriptInjectionPerformed => _scriptInjectingStream?.ScriptInjectionPerformed == true;
- public bool IsHtmlResponse => _isHtmlResponse == true;
-
- public override void Flush()
- {
- OnWrite();
- _baseStream.Flush();
- }
-
- public override async Task FlushAsync(CancellationToken cancellationToken)
- {
- OnWrite();
- await _baseStream.FlushAsync(cancellationToken);
- }
-
- public override void Write(ReadOnlySpan buffer)
- {
- OnWrite();
- _baseStream.Write(buffer);
- }
-
- public override void WriteByte(byte value)
- {
- OnWrite();
- _baseStream.WriteByte(value);
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- OnWrite();
- _baseStream.Write(buffer.AsSpan(offset, count));
- }
-
- public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- OnWrite();
- await _baseStream.WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
- }
-
- public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
- {
- OnWrite();
- await _baseStream.WriteAsync(buffer, cancellationToken);
- }
-
- private void OnWrite()
- {
- if (_isHtmlResponse.HasValue)
- {
- return;
- }
-
- var response = _context.Response;
-
- _isHtmlResponse =
- (response.StatusCode == StatusCodes.Status200OK ||
- response.StatusCode == StatusCodes.Status404NotFound ||
- response.StatusCode == StatusCodes.Status500InternalServerError) &&
- MediaTypeHeaderValue.TryParse(response.ContentType, out var mediaType) &&
- mediaType.IsSubsetOf(s_textHtmlMediaType) &&
- (!mediaType.Charset.HasValue || mediaType.Charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase));
-
- if (!_isHtmlResponse.Value)
- {
- BrowserRefreshMiddleware.Log.ScriptInjectionSkipped(_logger, response.StatusCode, response.ContentType);
- return;
- }
-
- BrowserRefreshMiddleware.Log.SetupResponseForBrowserRefresh(_logger);
- // Since we're changing the markup content, reset the content-length
- response.Headers.ContentLength = null;
-
- _scriptInjectingStream = new ScriptInjectingStream(_baseStream);
-
- // By default, write directly to the script injection stream.
- // We may change the base stream below if we detect that the response
- // is compressed.
- _baseStream = _scriptInjectingStream;
-
- // Check if the response has gzip Content-Encoding
- if (response.Headers.TryGetValue(HeaderNames.ContentEncoding, out var contentEncodingValues))
- {
- var contentEncoding = contentEncodingValues.FirstOrDefault();
- if (string.Equals(contentEncoding, "gzip", StringComparison.OrdinalIgnoreCase))
- {
- // Remove the Content-Encoding header since we'll be serving uncompressed content
- response.Headers.Remove(HeaderNames.ContentEncoding);
-
- _pipe = new Pipe();
- var gzipStream = new GZipStream(_pipe.Reader.AsStream(leaveOpen: true), CompressionMode.Decompress, leaveOpen: true);
-
- _gzipCopyTask = gzipStream.CopyToAsync(_scriptInjectingStream);
- _baseStream = _pipe.Writer.AsStream(leaveOpen: true);
- }
- }
- }
-
- public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
-
- public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
-
- public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- => throw new NotSupportedException();
-
- public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
- => throw new NotSupportedException();
-
- public override void SetLength(long value) => throw new NotSupportedException();
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- DisposeAsync().AsTask().GetAwaiter().GetResult();
- }
- }
-
- public ValueTask CompleteAsync() => DisposeAsync();
-
- public override async ValueTask DisposeAsync()
- {
- if (_disposed)
- {
- return;
- }
-
- _disposed = true;
-
- if (_pipe is not null)
- {
- await _pipe.Writer.CompleteAsync();
- }
-
- if (_gzipCopyTask is not null)
- {
- await _gzipCopyTask;
- }
-
- if (_scriptInjectingStream is not null)
- {
- await _scriptInjectingStream.CompleteAsync();
- }
- else
- {
- Debug.Assert(_isHtmlResponse != true);
- await _baseStream.FlushAsync();
- }
- }
-}
diff --git a/src/Dotnet.Watch/Web.Middleware/ScriptInjectingStream.cs b/src/Dotnet.Watch/Web.Middleware/ScriptInjectingStream.cs
deleted file mode 100644
index 477979e40de1..000000000000
--- a/src/Dotnet.Watch/Web.Middleware/ScriptInjectingStream.cs
+++ /dev/null
@@ -1,403 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-#nullable enable
-
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Watch.BrowserRefresh;
-
-internal sealed class ScriptInjectingStream : Stream
-{
- internal static string InjectedScript { get; } = $"";
-
- private static readonly ReadOnlyMemory s_bodyTagBytes = "