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 = ""u8.ToArray(); - private static readonly ReadOnlyMemory s_injectedScriptBytes = Encoding.UTF8.GetBytes(InjectedScript); - - private readonly Stream _baseStream; - - private int _partialBodyTagLength; - private bool _isDisposed; - - public ScriptInjectingStream(Stream baseStream) - { - _baseStream = baseStream; - } - - 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 { get; private set; } - - public override void Flush() - => _baseStream.Flush(); - - public override Task FlushAsync(CancellationToken cancellationToken) - => _baseStream.FlushAsync(cancellationToken); - - public override void Write(ReadOnlySpan buffer) - { - if (!ScriptInjectionPerformed) - { - ScriptInjectionPerformed = TryInjectScript(buffer); - } - else - { - _baseStream.Write(buffer); - } - } - - public override void WriteByte(byte value) - { - _baseStream.WriteByte(value); - } - - public override void Write(byte[] buffer, int offset, int count) - { - if (!ScriptInjectionPerformed) - { - ScriptInjectionPerformed = TryInjectScript(buffer.AsSpan(offset, count)); - } - else - { - _baseStream.Write(buffer, offset, count); - } - } - - public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - if (!ScriptInjectionPerformed) - { - ScriptInjectionPerformed = await TryInjectScriptAsync(buffer.AsMemory(offset, count), cancellationToken); - } - else - { - await _baseStream.WriteAsync(buffer.AsMemory(offset, count), cancellationToken); - } - } - - public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - { - if (!ScriptInjectionPerformed) - { - ScriptInjectionPerformed = await TryInjectScriptAsync(buffer, cancellationToken); - } - else - { - await _baseStream.WriteAsync(buffer, cancellationToken); - } - } - - private bool TryInjectScript(ReadOnlySpan buffer) - { - var sourceBuffer = new SourceBuffer(buffer); - var writer = new SyncBaseStreamWriter(_baseStream); - return TryInjectScriptCore(ref writer, sourceBuffer); - } - - private async ValueTask TryInjectScriptAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) - { - var sourceBuffer = new SourceBuffer(buffer.Span); - var writer = new AsyncBaseStreamWriter(_baseStream, buffer); - var result = TryInjectScriptCore(ref writer, sourceBuffer); - - await writer.WriteToBaseStreamAsync(cancellationToken); - - return result; - } - - // Implements the core script injection logic in a manner agnostic to whether writes - // are synchronous or asynchronous. - private bool TryInjectScriptCore(ref TWriter writer, SourceBuffer buffer) - where TWriter : struct, IBaseStreamWriter - { - if (_partialBodyTagLength != 0) - { - // We're in the middle of parsing a potential body tag, - // which means that the rest of the body tag must be - // at the start of the buffer. - - var restPartialTagLength = FindPartialTagLengthFromStart(currentBodyTagLength: _partialBodyTagLength, buffer.Span); - if (restPartialTagLength == -1) - { - // This wasn't a closing body tag. Flush what we've buffered so far and reset. - // We don't return here because we want to continue to process the buffer as if - // we weren't reading a partial body tag. - writer.Write(s_bodyTagBytes[.._partialBodyTagLength]); - _partialBodyTagLength = 0; - } - else - { - // This may still be a closing body tag. - _partialBodyTagLength += restPartialTagLength; - - Debug.Assert(_partialBodyTagLength <= s_bodyTagBytes.Length); - - if (_partialBodyTagLength == s_bodyTagBytes.Length) - { - // We've just read a full closing body tag, so we flush it to the stream. - // Then just write the rest of the stream normally as we've now finished searching - // for the script. - writer.Write(s_injectedScriptBytes); - writer.Write(s_bodyTagBytes); - writer.Write(buffer[restPartialTagLength..]); - _partialBodyTagLength = 0; - return true; - } - else - { - // We're still in the middle of reading the body tag, - // so there's nothing else to flush to the stream. - return false; - } - } - } - - // We now know we're not in the middle of processing a body tag. - Debug.Assert(_partialBodyTagLength == 0); - - var index = buffer.Span.LastIndexOf(s_bodyTagBytes.Span); - if (index == -1) - { - // We didn't find the full closing body tag in the buffer, but the end of the buffer - // might contain the start of a closing body tag. - - var partialBodyTagLength = FindPartialTagLengthFromEnd(buffer.Span); - if (partialBodyTagLength == -1) - { - // We know that the end of the buffer definitely does not - // represent a closing body tag. We'll just flush the buffer - // to the base stream. - writer.Write(buffer); - return false; - } - else - { - // We might have found a body tag at the end of the buffer. - // We'll write the buffer leading up to the start of the body - // tag candidate. - - writer.Write(buffer[..^partialBodyTagLength]); - _partialBodyTagLength = partialBodyTagLength; - return false; - } - } - - if (index > 0) - { - writer.Write(buffer[..index]); - buffer = buffer[index..]; - } - - // Write the injected script - writer.Write(s_injectedScriptBytes); - - // Write the rest of the buffer/HTML doc - writer.Write(buffer); - return true; - } - - private static int FindPartialTagLengthFromStart(int currentBodyTagLength, ReadOnlySpan buffer) - { - var remainingBodyTagBytes = s_bodyTagBytes.Span[currentBodyTagLength..]; - var minLength = Math.Min(buffer.Length, remainingBodyTagBytes.Length); - - return buffer[..minLength].SequenceEqual(remainingBodyTagBytes[..minLength]) - ? minLength - : -1; - } - - private static int FindPartialTagLengthFromEnd(ReadOnlySpan buffer) - { - var bufferLength = buffer.Length; - if (bufferLength == 0) - { - return -1; - } - - // Since each character within "" is unique, we can use the last byte - // in the buffer to determine the length of the partial body tag. - var lastByte = buffer[^1]; - var bodyMarkerIndexOfLastByte = BodyTagIndexOf(lastByte); - if (bodyMarkerIndexOfLastByte == -1) - { - // The last character does not appear "", so we know - // there's not a partial body tag. - return -1; - } - - var partialTagLength = bodyMarkerIndexOfLastByte + 1; - if (buffer.Length < partialTagLength) - { - // The buffer is shorter than the expected length of the partial - // body tag, so we know the buffer can't possibly contain it. - return -1; - } - - // Finally, we need to check that the content at the end of the buffer - // matches the expected partial body tag. - return buffer[^partialTagLength..].SequenceEqual(s_bodyTagBytes.Span[..partialTagLength]) - ? partialTagLength - : -1; - - // We can utilize the fact that each character is unique in "" - // to perform an efficient index lookup. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static int BodyTagIndexOf(byte c) - => c switch - { - (byte)'<' => 0, - (byte)'/' => 1, - (byte)'b' => 2, - (byte)'o' => 3, - (byte)'d' => 4, - (byte)'y' => 5, - (byte)'>' => 6, - _ => -1, - }; - } - - public ValueTask CompleteAsync() => DisposeAsync(); - - protected override void Dispose(bool disposing) - { - if (disposing) - { - DisposeAsync().AsTask().GetAwaiter().GetResult(); - } - } - - public override async ValueTask DisposeAsync() - { - if (_isDisposed) - { - return; - } - - _isDisposed = true; - - if (_partialBodyTagLength > 0) - { - // We might have buffered some data thinking that it could represent - // a body tag. We know at this point that there's no more data - // on its way, so we'll write the remaining data to the buffer. - await _baseStream.WriteAsync(s_bodyTagBytes[.._partialBodyTagLength]); - _partialBodyTagLength = 0; - } - - await FlushAsync(); - } - - 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(); - - // A thin wrapper over ReadOnlySpan that keeps track of the current range relative - // to the originally-provided buffer. - // This enables the sharing of logic between scenarios where only a ReadOnlySpan - // is available (some synchronous writes) and scenarios where ReadOnlyMemory - // is required (all asynchronous writes). - private readonly ref struct SourceBuffer - { - private readonly int _offsetFromOriginal; - - public readonly ReadOnlySpan Span; - - public int Length => Span.Length; - - public Range RangeInOriginal => new(_offsetFromOriginal, _offsetFromOriginal + Span.Length); - - public SourceBuffer(ReadOnlySpan span) - : this(span, offsetFromOriginal: 0) - { - } - - private SourceBuffer(ReadOnlySpan span, int offsetFromOriginal) - { - Span = span; - _offsetFromOriginal = offsetFromOriginal; - } - - public SourceBuffer Slice(int start, int length) - => new(Span.Slice(start, length), offsetFromOriginal: _offsetFromOriginal + start); - } - - // Represents a writer to the base stream. - // Accepts arbitrary heap-allocated buffers and - // ranges of the source buffer. - private interface IBaseStreamWriter - { - void Write(in SourceBuffer buffer); - void Write(ReadOnlyMemory data); - } - - // A base stream writer that performs synchronous writes. - private struct SyncBaseStreamWriter(Stream baseStream) : IBaseStreamWriter - { - public readonly void Write(ReadOnlyMemory data) => baseStream.Write(data.Span); - public readonly void Write(in SourceBuffer buffer) => baseStream.Write(buffer.Span); - } - - // A base stream writer that enables buffering writes synchronously and applying - // them to the base stream when an async context is available. - private struct AsyncBaseStreamWriter(Stream baseStream, ReadOnlyMemory bufferMemory) : IBaseStreamWriter - { - private WriteBuffer _writes; - private int _writeCount; - - public void Write(ReadOnlyMemory data) => _writes[_writeCount++] = data; - public void Write(in SourceBuffer buffer) => _writes[_writeCount++] = bufferMemory[buffer.RangeInOriginal]; - - public readonly async ValueTask WriteToBaseStreamAsync(CancellationToken cancellationToken) - { - for (var i = 0; i < _writeCount; i++) - { - await baseStream.WriteAsync(_writes[i], cancellationToken); - } - } - - // We don't currently need than 4 writes, but we can bump this in the future if needed. - // If we ever target .NET 8+, we can use the [InlineArray] feature instead. - private struct WriteBuffer - { - ReadOnlyMemory _write0; - ReadOnlyMemory _write1; - ReadOnlyMemory _write2; - ReadOnlyMemory _write3; - - private static ref ReadOnlyMemory GetAt(ref WriteBuffer buffer, int index) - { - switch (index) - { - case 0: return ref buffer._write0; - case 1: return ref buffer._write1; - case 2: return ref buffer._write2; - case 3: return ref buffer._write3; - default: throw new IndexOutOfRangeException(nameof(index)); - } - } - - public ReadOnlyMemory this[int index] - { - get => GetAt(ref this, index); - set => GetAt(ref this, index) = value; - } - } - } -} diff --git a/src/Dotnet.Watch/Web.Middleware/StartupHook.cs b/src/Dotnet.Watch/Web.Middleware/StartupHook.cs index 01ae4ee90a00..95bfc546a744 100644 --- a/src/Dotnet.Watch/Web.Middleware/StartupHook.cs +++ b/src/Dotnet.Watch/Web.Middleware/StartupHook.cs @@ -1,16 +1,9 @@ // 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; - internal class StartupHook { public static void Initialize() { - // See https://github.com/dotnet/aspnetcore/issues/37357#issuecomment-941237000 - // We'll configure an environment variable that will indicate to blazor-wasm that the middleware is available. - Environment.SetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS", "true"); } } diff --git a/src/Dotnet.Watch/Web.Middleware/WebSocketScriptInjection.js b/src/Dotnet.Watch/Web.Middleware/WebSocketScriptInjection.js deleted file mode 100644 index e03aaeb5d477..000000000000 --- a/src/Dotnet.Watch/Web.Middleware/WebSocketScriptInjection.js +++ /dev/null @@ -1,358 +0,0 @@ -setTimeout(async function () { - const hotReloadActiveKey = '_dotnet_watch_hot_reload_active'; - // Ensure we only try to connect once, even if the script is both injected and manually inserted - const scriptInjectedSentinel = '_dotnet_watch_ws_injected'; - if (window.hasOwnProperty(scriptInjectedSentinel)) { - return; - } - window[scriptInjectedSentinel] = true; - - // dotnet-watch browser reload script - const webSocketUrls = '{{hostString}}'.split(','); - const sharedSecret = await getSecret('{{ServerKey}}'); - let connection; - for (const url of webSocketUrls) { - try { - connection = await getWebSocket(url); - break; - } catch (ex) { - console.debug(ex); - } - } - if (!connection) { - console.debug('Unable to establish a connection to the browser refresh server.'); - return; - } - - let waiting = false; - - connection.onmessage = function (message) { - const payload = JSON.parse(message.data); - const action = { - 'Reload': () => reload(), - 'Wait': () => wait(), - 'UpdateStaticFile': () => updateStaticFile(payload.path), - 'ApplyManagedCodeUpdates': () => applyManagedCodeUpdates(payload.sharedSecret, payload.updateId, payload.deltas, payload.responseLoggingLevel), - 'ReportDiagnostics': () => reportDiagnostics(payload.diagnostics), - 'GetApplyUpdateCapabilities': () => getApplyUpdateCapabilities(), - 'RefreshBrowser': () => refreshBrowser() - }; - - if (payload.type && action.hasOwnProperty(payload.type)) { - action[payload.type](); - } else { - console.error('Unknown payload:', message.data); - } - } - - connection.onerror = function (event) { console.debug('dotnet-watch reload socket error.', event) } - connection.onclose = function () { console.debug('dotnet-watch reload socket closed.') } - connection.onopen = function () { console.debug('dotnet-watch reload socket connected.') } - - function updateStaticFile(path) { - if (path && path.endsWith('.css')) { - updateCssByPath(path); - } else { - console.debug(`File change detected to file ${path}. Reloading page...`); - location.reload(); - return; - } - } - - async function updateCssByPath(path) { - const styleElement = document.querySelector(`link[href^="${path}"]`) || - document.querySelector(`link[href^="${document.baseURI}${path}"]`); - - // Receive a Clear-site-data header. - await fetch('/_framework/clear-browser-cache'); - - if (!styleElement || !styleElement.parentNode) { - console.debug('Unable to find a stylesheet to update. Updating all local css files.'); - updateAllLocalCss(); - } - - updateCssElement(styleElement); - } - - function updateAllLocalCss() { - [...document.querySelectorAll('link')] - .filter(l => l.baseURI === document.baseURI) - .forEach(e => updateCssElement(e)); - } - - function getMessageAndStack(error) { - const message = error.message || '' - let messageAndStack = error.stack || message - if (!messageAndStack.includes(message)) { - messageAndStack = message + "\n" + messageAndStack; - } - - return messageAndStack - } - - function getApplyUpdateCapabilities() { - let applyUpdateCapabilities; - try { - applyUpdateCapabilities = window.Blazor._internal.getApplyUpdateCapabilities(); - } catch (error) { - applyUpdateCapabilities = "!" + getMessageAndStack(error); - } - connection.send(applyUpdateCapabilities); - } - - function updateCssElement(styleElement) { - if (!styleElement || styleElement.loading) { - // A file change notification may be triggered for the same file before the browser - // finishes processing a previous update. In this case, it's easiest to ignore later updates - return; - } - - const newElement = styleElement.cloneNode(); - const href = styleElement.href; - newElement.href = href.split('?', 1)[0] + `?nonce=${Date.now()}`; - - styleElement.loading = true; - newElement.loading = true; - newElement.addEventListener('load', function () { - newElement.loading = false; - styleElement.remove(); - }); - - styleElement.parentNode.insertBefore(newElement, styleElement.nextSibling); - } - - function applyDeltas_legacy(deltas) { - let apply = window.Blazor?._internal?.applyHotReload - - // Only apply hot reload deltas if Blazor has been initialized. - // It's possible for Blazor to start after the initial page load, so we don't consider skipping this step - // to be a failure. These deltas will get applied later, when Blazor completes initialization. - if (apply) { - deltas.forEach(d => { - if (apply.length == 5) { - // WASM 8.0 - apply(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta, d.updatedTypes) - } else { - // WASM 9.0 - apply(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta) - } - }); - } - } - - async function applyManagedCodeUpdates(serverSecret, updateId, deltas, responseLoggingLevel) { - if (sharedSecret && (serverSecret != sharedSecret.encodedSharedSecret)) { - // Validate the shared secret if it was specified. It might be unspecified in older versions of VS - // that do not support this feature as yet. - throw 'Unable to validate the server. Rejecting apply-update payload.'; - } - - console.debug('Applying managed code updates.'); - - const AgentMessageSeverity_Error = 2 - - let applyError = undefined; - let log = []; - try { - let applyDeltas = window.Blazor?._internal?.applyHotReloadDeltas - if (applyDeltas) { - // Only apply hot reload deltas if Blazor has been initialized. - // It's possible for Blazor to start after the initial page load, so we don't consider skipping this step - // to be a failure. These deltas will get applied later, when Blazor completes initialization. - - let wasmDeltas = deltas.map(delta => { - return { - "moduleId": delta.moduleId, - "metadataDelta": delta.metadataDelta, - "ilDelta": delta.ilDelta, - "pdbDelta": delta.pdbDelta, - "updatedTypes": delta.updatedTypes, - }; - }); - - log = applyDeltas(wasmDeltas, responseLoggingLevel); - } else { - // Try invoke older WASM API: - applyDeltas_legacy(deltas) - } - } catch (error) { - console.warn(error); - applyError = error; - log.push({ "message": getMessageAndStack(error), "severity": AgentMessageSeverity_Error }); - } - - try { - let body = JSON.stringify({ - "id": updateId, - "deltas": deltas - }); - - await fetch('/_framework/blazor-hotreload', { method: 'post', headers: { 'content-type': 'application/json' }, body: body }); - } catch (error) { - console.warn(error); - applyError = error; - log.push({ "message": getMessageAndStack(error), "severity": AgentMessageSeverity_Error }); - } - - connection.send(JSON.stringify({ - "success": !applyError, - "log": log - })); - - if (!applyError) { - displayChangesAppliedToast(); - } - } - - function reportDiagnostics(diagnostics) { - console.debug('Reporting Hot Reload diagnostics.'); - - document.querySelectorAll('#dotnet-compile-error').forEach(el => el.remove()); - - if (diagnostics.length == 0) { - return; - } - - const el = document.body.appendChild(document.createElement('div')); - el.id = 'dotnet-compile-error'; - el.setAttribute('style', 'z-index:1000000; position:fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); color:black; overflow: scroll;'); - diagnostics.forEach(error => { - const item = el.appendChild(document.createElement('div')); - item.setAttribute('style', 'border: 2px solid red; padding: 8px; background-color: #faa;') - const message = item.appendChild(document.createElement('div')); - message.setAttribute('style', 'font-weight: bold'); - message.textContent = error.Message; - item.appendChild(document.createElement('div')).textContent = error; - }); - } - - function displayChangesAppliedToast() { - document.querySelectorAll('#dotnet-compile-error').forEach(el => el.remove()); - if (document.querySelector('#dotnet-hotreload-toast')) { - return; - } - if (!window[hotReloadActiveKey]) - { - return; - } - const el = document.createElement('div'); - el.id = 'dotnet-hotreload-toast'; - el.innerHTML = ""; - el.setAttribute('style', 'z-index: 1000000; width: 48px; height: 48px; position:fixed; top:5px; left: 5px'); - document.body.appendChild(el); - window[hotReloadActiveKey] = false; - setTimeout(() => el.remove(), 2000); - } - - function refreshBrowser() { - if (window.Blazor) { - window[hotReloadActiveKey] = true; - // hotReloadApplied triggers an enhanced navigation to - // refresh pages that have been statically rendered with - // Blazor SSR. - if (window.Blazor?._internal?.hotReloadApplied) - { - console.debug('Refreshing browser: WASM.'); - Blazor._internal.hotReloadApplied(); - } - else - { - console.debug('Refreshing browser.'); - displayChangesAppliedToast(); - } - } else { - console.debug('Refreshing browser: Reloading.'); - location.reload(); - } - } - - function reload() { - console.debug('Reloading.'); - location.reload(); - } - - function wait() { - console.debug('Waiting for application to rebuild.'); - - if (waiting) { - return; - } - - waiting = true; - const glyphs = ['☱', '☲', '☴']; - const title = document.title; - let i = 0; - setInterval(function () { document.title = glyphs[i++ % glyphs.length] + ' ' + title; }, 240); - } - - async function getSecret(serverKeyString) { - if (!serverKeyString || !window.crypto || !window.crypto.subtle) { - return null; - } - - const secretBytes = window.crypto.getRandomValues(new Uint8Array(32)); // 32-bytes of entropy - - // Based on https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#subjectpublickeyinfo_import - const binaryServerKey = str2ab(atob(serverKeyString)); - const serverKey = await window.crypto.subtle.importKey('spki', binaryServerKey, { name: "RSA-OAEP", hash: "SHA-256" }, false, ['encrypt']); - const encrypted = await window.crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverKey, secretBytes); - return { - encryptedSharedSecret: btoa(String.fromCharCode(...new Uint8Array(encrypted))), - encodedSharedSecret: btoa(String.fromCharCode(...secretBytes)), - }; - - function str2ab(str) { - const buf = new ArrayBuffer(str.length); - const bufView = new Uint8Array(buf); - for (let i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); - } - return buf; - } - } - - function getWebSocket(url) { - return new Promise((resolve, reject) => { - const encryptedSecret = sharedSecret && sharedSecret.encryptedSharedSecret; - const protocol = encryptedSecret ? encodeURIComponent(encryptedSecret) : []; - const webSocket = new WebSocket(url, protocol); - let opened = false; - - function onOpen() { - opened = true; - clearEventListeners(); - resolve(webSocket); - } - - function onClose(event) { - if (opened) { - // Open completed successfully. Nothing to do here. - return; - } - - let error = 'WebSocket failed to connect.'; - if (event instanceof ErrorEvent) { - error = event.error; - } - - clearEventListeners(); - reject(error); - } - - function clearEventListeners() { - webSocket.removeEventListener('open', onOpen); - // The error event isn't as reliable, but close is always called even during failures. - // If close is called without a corresponding open, we can reject the promise. - webSocket.removeEventListener('close', onClose); - } - - webSocket.addEventListener('open', onOpen); - webSocket.addEventListener('close', onClose); - if (window.Blazor?.removeEventListener && window.Blazor?.addEventListener) - { - webSocket.addEventListener('close', () => window.Blazor?.removeEventListener('enhancedload', displayChangesAppliedToast)); - window.Blazor?.addEventListener('enhancedload', displayChangesAppliedToast); - } - }); - } -}, 500); diff --git a/src/Dotnet.Watch/dotnet-watch/Watch/DotNetWatcher.cs b/src/Dotnet.Watch/dotnet-watch/Watch/DotNetWatcher.cs index e6efef90f8e8..620df094baa8 100644 --- a/src/Dotnet.Watch/dotnet-watch/Watch/DotNetWatcher.cs +++ b/src/Dotnet.Watch/dotnet-watch/Watch/DotNetWatcher.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Globalization; using Microsoft.Build.Graph; +using Microsoft.DotNet.HotReload; using Microsoft.Extensions.Logging; namespace Microsoft.DotNet.Watch; @@ -21,13 +22,13 @@ public static async Task WatchAsync(DotNetWatchContext context, CancellationToke context.Logger.LogDebug("MSBuild incremental optimizations suppressed."); } - var environmentBuilder = new Dictionary(); - ChangedFile? changedFile = null; var buildEvaluator = new BuildEvaluator(context); for (var iteration = 0;;iteration++) { + var environmentBuilder = new Dictionary(); + if (await buildEvaluator.EvaluateAsync(changedFile, shutdownCancellationToken) is not { } evaluationResult) { context.Logger.LogError("Failed to find a list of files to watch"); @@ -48,6 +49,15 @@ public static async Task WatchAsync(DotNetWatchContext context, CancellationToke staticFileHandler = null; } + using var fileSetWatcher = new FileWatcher(context.Logger, context.EnvironmentOptions); + fileSetWatcher.WatchContainingDirectories(evaluationResult.Files.Keys, includeSubdirectories: true); + + var webAppModel = + context.MainProjectOptions?.Command == "run" && + projectRootNode != null && + HotReloadAppModel.InferFromProject(context, projectRootNode) is WebApplicationAppModel inferredWebAppModel + ? inferredWebAppModel + : null; var processSpec = new ProcessSpec { Executable = context.EnvironmentOptions.GetMuxerPath(), @@ -61,11 +71,11 @@ public static async Task WatchAsync(DotNetWatchContext context, CancellationToke } }; - var browserRefreshServer = projectRootNode != null && HotReloadAppModel.InferFromProject(context, projectRootNode) is WebApplicationAppModel webAppModel + var browserRefreshServer = projectRootNode != null && webAppModel != null ? await context.BrowserRefreshServerFactory.GetOrCreateBrowserRefreshServerAsync(projectRootNode, webAppModel, shutdownCancellationToken) : null; - browserRefreshServer?.ConfigureLaunchEnvironment(environmentBuilder, enableHotReload: false); + browserRefreshServer?.ConfigureLaunchEnvironment(environmentBuilder); Action? outputObserver = null; if (projectRootNode != null) @@ -91,9 +101,6 @@ public static async Task WatchAsync(DotNetWatchContext context, CancellationToke using var currentRunCancellationSource = new CancellationTokenSource(); using var combinedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(shutdownCancellationToken, currentRunCancellationSource.Token); - using var fileSetWatcher = new FileWatcher(context.Logger, context.EnvironmentOptions); - - fileSetWatcher.WatchContainingDirectories(evaluationResult.Files.Keys, includeSubdirectories: true); var processTask = context.ProcessRunner.RunAsync(processSpec, context.Logger, launchResult: null, combinedCancellationSource.Token); diff --git a/src/Dotnet.Watch/dotnet-watch/Watch/MsBuildFileSetFactory.cs b/src/Dotnet.Watch/dotnet-watch/Watch/MsBuildFileSetFactory.cs index 2fcc8466059c..75fabf1bb76b 100644 --- a/src/Dotnet.Watch/dotnet-watch/Watch/MsBuildFileSetFactory.cs +++ b/src/Dotnet.Watch/dotnet-watch/Watch/MsBuildFileSetFactory.cs @@ -32,7 +32,7 @@ internal class MSBuildFileSetFactory( private readonly ProjectGraphFactory _buildGraphFactory = new( [new ProjectRepresentation(rootProjectFile, entryPointFilePath: null)], - buildProperties: BuildUtilities.ParseBuildProperties(buildArguments).ToImmutableDictionary(keySelector: arg => arg.key, elementSelector: arg => arg.value), + buildProperties: BuildUtilities.ParseBuildPropertiesToImmutableDictionary(buildArguments), logger, globalOptions, environmentOptions); diff --git a/src/StaticWebAssetsSdk/AGENTS.md b/src/StaticWebAssetsSdk/AGENTS.md index 8a6bb0f3b50d..c64526944752 100644 --- a/src/StaticWebAssetsSdk/AGENTS.md +++ b/src/StaticWebAssetsSdk/AGENTS.md @@ -13,6 +13,7 @@ src/StaticWebAssetsSdk/ │ ├── Utils/ # Utilities (PathTokenizer, OSPath, etc.) │ └── *.cs # Task implementations ├── Targets/ # MSBuild targets (.targets files) +│ └── DotNetWatch/ # dotnet-watch browser tools client and config template └── Sdk/ # SDK props and targets test/Microsoft.NET.Sdk.StaticWebAssets.Tests/ @@ -20,6 +21,29 @@ test/Microsoft.NET.Sdk.StaticWebAssets.Tests/ └── *.cs # Integration tests ``` +`Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets` is shared by the Web and +WebAssembly SDKs. It exists here, rather than in `dotnet watch`, because the browser tools +client must be an application static asset: the browser authenticates the watch provider +with a build-pinned public key, so the provider must not be the source of the executable +code, nor of the key. This target therefore also generates the keypair (via +`EnsureDotNetWatchBrowserToolsKey`) into `obj///dotnet-watch/` and embeds only +the public half in the generated configuration module. The existing +`EnableHotReloadInRuntimeConfigDevFile` property controls generation and defaults to +`true` for Debug builds; there is no browser-tools-specific watch-to-MSBuild property. +The generated initializer checks the provider-owned +`/_framework/dotnet-browser-tools/hot-reload-settings.json` response before importing the +configuration; this response is not a generated file or Static Web Asset. +Hosted WebAssembly's client owns these outputs; its server consumes the referenced assets +rather than generating a competing route and keypair. The assets are build only and must +never reach publish output. Its generated watch initializer also initializes the SDK Hot +Reload agent on .NET 10+; older target frameworks use the runtime's apply API. Do not add a +second Hot Reload agent initializer—the shared browser-tools rendezvous carries the SDK +agent's apply functions directly. +Browser-tools UI must remain self-contained and compatible with strict Content Security +Policy: isolate it in Shadow DOM, use constructable stylesheets, and do not require +application stylesheets, inline styles, nonces, or `style-src 'unsafe-inline'`. +See [`src/Dotnet.Watch/AGENTS.md`](../Dotnet.Watch/AGENTS.md). + ## Architecture For the full technical architecture — data model (`StaticWebAsset`, `StaticWebAssetEndpoint`, `StaticWebAssetGroup`), asset lifecycle, cross-project boundaries, manifests, target execution order, and task/target reference tables — see [Architecture.md](Architecture.md). diff --git a/src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.config.js.template b/src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.config.js.template new file mode 100644 index 000000000000..fd663acaa011 --- /dev/null +++ b/src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.config.js.template @@ -0,0 +1,23 @@ +// +// Generated by the .NET SDK for dotnet-watch. Do not edit. +// +// Pins the public half of the dotnet-watch browser tools key pair and the fixed provider route +// into the application build output, so the browser never learns them from the provider it +// authenticates. The key pair is generated by the build into the project's intermediate output; +// only this public half is ever served, and the private half is read exclusively by dotnet-watch. +// +// This module is produced when Hot Reload build outputs are enabled and never reaches publish +// output. The initializer imports it only after the provider reports that Hot Reload is available. +// + +import { startBrowserTools } from './__CLIENT_MODULE__'; + +export const browserToolsConfiguration = { + publicKey: '__PUBLIC_KEY__', + connectPath: '__ROUTE_PREFIX__/connect', + clearCachePath: '__ROUTE_PREFIX__/clear-cache', + moduleUrl: import.meta.url, +}; + +startBrowserTools(browserToolsConfiguration) + .catch(error => console.debug('Unable to start the dotnet-watch browser tools.', error)); diff --git a/src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.js b/src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.js new file mode 100644 index 000000000000..a99e8a774157 --- /dev/null +++ b/src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.js @@ -0,0 +1,647 @@ +// dotnet-watch browser tools client. +// +// This module is part of the application build output. It must never be downloaded from the +// dotnet-watch provider: the provider is the party this client authenticates, so executable code +// served by it could not be trusted. The generated configuration module pins the provider's public +// key at build time and passes it to startBrowserTools. + +const hotReloadActiveKey = '_dotnet_watch_hot_reload_active'; +// Ensures we only connect once even when several activation paths import this module. +const scriptInjectedSentinel = '_dotnet_watch_ws_injected'; +const replayResponseLoggingLevel = 1; +const AgentMessageSeverity_Warning = 1; +const AgentMessageSeverity_Error = 2; +// Bounds how long the replay waits for the Hot Reload agent. Only spent when there is something to +// replay and the apply API is still missing, which is the case that would otherwise lose updates. +const hotReloadAgentReadyTimeoutMs = 10000; +const browserToolsStyles = ` + :host { + z-index: 1000000; + position: fixed; + } + + :host(#dotnet-compile-error) { + inset: 0; + background-color: rgba(0, 0, 0, 0.5); + color: black; + overflow: scroll; + } + + .dotnet-compile-error-item { + border: 2px solid red; + padding: 8px; + background-color: #faa; + } + + .dotnet-compile-error-message { + font-weight: bold; + } + + :host(#dotnet-hotreload-toast) { + width: 48px; + height: 48px; + top: 5px; + left: 5px; + } + + svg { + filter: drop-shadow(0 2px 1px rgb(0 0 0 / 0.4)); + } + + #hotreloaded-ellipse1 { + animation: hotreloaded-ellipse1_c_o 1800ms linear 1 normal forwards; + } + + #hotreloaded-path1 { + animation-name: hotreloaded-path1__m, hotreloaded-path1_c_o; + animation-duration: 1800ms; + animation-delay: 100ms; + animation-fill-mode: forwards; + animation-timing-function: linear; + animation-direction: normal; + animation-iteration-count: 1; + } + + @keyframes hotreloaded-ellipse1_c_o { + 0% { opacity: 0; } + 16.666667% { opacity: 1; } + 72.222222% { opacity: 1; } + 90% { opacity: 0; } + 100% { opacity: 0; } + } + + @keyframes hotreloaded-path1__m { + 0% { d: path('M126.151214,288.396852L196.625037,350.661591L320.793323,178.518242'); } + 16.666667% { d: path('M126.151214,288.396852L126.151214,288.396852L126.151214,288.396852'); } + 22.222222% { + d: path('M126.151214,288.396852L196.625037,350.661591L196.625037,350.661591'); + animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1); + } + 33.333333% { d: path('M126.151214,288.396852L196.625037,350.661591L320.793323,178.518242'); } + 100% { d: path('M126.151214,288.396852L196.625037,350.661591L320.793323,178.518242'); } + } + + @keyframes hotreloaded-path1_c_o { + 0% { opacity: 0; } + 16.666667% { opacity: 0; } + 22.222222% { opacity: 1; } + 72.222222% { opacity: 1; } + 90% { opacity: 0; } + 100% { opacity: 0; } + } +`; +let browserToolsStylesheet; + +/** + * Connects to the dotnet-watch browser tools provider. + * + * @param {object} config Build-generated configuration. + * @param {string} config.publicKey Base64 SubjectPublicKeyInfo of the provider's session key. + * @param {string} config.connectPath Root-relative route of the provider's WebSocket endpoint. + * @param {string} config.clearCachePath Root-relative route of the provider's cache reset endpoint. + * @param {string} config.moduleUrl URL of the generated configuration module. Polled to detect that + * the application is reachable again after it restarted. + */ +export async function startBrowserTools(config) { + if (window.hasOwnProperty(scriptInjectedSentinel)) { + return; + } + window[scriptInjectedSentinel] = true; + + const { publicKey, connectPath, clearCachePath, moduleUrl } = config; + + const sharedSecret = await getSecret(publicKey); + if (!sharedSecret) { + delete window[scriptInjectedSentinel]; + console.debug('Unable to protect the dotnet-watch browser tools connection. Browser tools are disabled.'); + return; + } + + const connectUrl = new URL(connectPath, document.baseURI); + connectUrl.protocol = connectUrl.protocol === 'https:' ? 'wss:' : 'ws:'; + + let closing = false; + let waiting = false; + + // The provider sends the session initialization message, which carries the updates produced + // before this browser connected, as the first message on the socket. It releases live messages + // for this connection only after the browser acknowledges that message, so chaining the live + // message queue on the initialization promise preserves the order even if a live message somehow + // arrives early. + let completeInitialization; + let failInitialization; + const initialized = new Promise((resolve, reject) => { completeInitialization = resolve; failInitialization = reject; }); + initialized.catch(() => { }); + + let initializationMessageReceived = false; + let receiveInitializationMessage; + const initializationMessage = new Promise(resolve => receiveInitializationMessage = resolve); + let messageQueue = initialized; + + let connection; + try { + connection = await getWebSocket(connectUrl, sharedSecret.encryptedSharedSecret, message => { + if (!initializationMessageReceived) { + initializationMessageReceived = true; + receiveInitializationMessage(message); + } else { + messageQueue = messageQueue + .then(() => handleMessage(message)) + .catch(error => console.debug('Failed to process a browser refresh message.', error)); + } + }); + } catch (ex) { + console.debug(ex); + } + + if (!connection) { + delete window[scriptInjectedSentinel]; + console.debug('Unable to establish a connection to the browser refresh server.'); + return; + } + + connection.onerror = function (event) { console.debug('dotnet-watch reload socket error.', event) } + connection.onclose = function () { + delete window[scriptInjectedSentinel]; + failInitialization('The browser tools connection was closed.'); + console.debug('dotnet-watch reload socket closed.'); + if (!closing) { + // The browser reaches the provider through the application, so the socket dies when the + // application restarts and any pending Reload message is lost. Reload once it is back. + reloadWhenApplicationReturns(); + } + } + + if (await initializeSession()) { + completeInitialization(); + } else { + closing = true; + connection.close(); + } + + async function initializeSession() { + let payload; + try { + payload = JSON.parse((await withTimeout(initializationMessage, 30000)).data); + } catch (error) { + console.debug('Unable to initialize the browser tools session.', error); + return false; + } + + if (payload.type !== 'InitializeSession') { + console.error(`Expected the browser tools session initialization message but received '${payload.type}'.`); + return false; + } + + if (!authenticateProvider(payload.sharedSecret)) { + console.error('Unable to validate the browser refresh server. Closing the connection.'); + return false; + } + + const log = []; + let applyError; + try { + const updates = payload.updates ?? []; + if (updates.length && !(await waitForDeltaApplyApi())) { + // Keep initializing: the connection is still useful for reloads, diagnostics and CSS, and + // failing here would close the socket and reload the page into the same state. Surface the + // condition in the dotnet-watch console instead. + log.push({ + "message": 'The Hot Reload agent did not become available in time, so the updates produced before this browser connected were not applied.', + "severity": AgentMessageSeverity_Warning + }); + } + + for (const update of updates) { + try { + const entries = applyDeltas(update.deltas, replayResponseLoggingLevel); + if (entries && entries.length) { + log.push(...entries); + } + } catch (error) { + // Report the failure without failing the initialization, for the same reason as above: + // dotnet-watch prints these entries as errors, while closing the socket would only make + // the page reload into a browser that cannot apply updates either. + console.warn('Unable to replay Hot Reload updates.', error); + log.push({ "message": getMessageAndStack(error), "severity": AgentMessageSeverity_Error }); + } + } + } catch (error) { + console.warn('Unable to initialize the browser tools session.', error); + applyError = error; + log.push({ "message": getMessageAndStack(error), "severity": AgentMessageSeverity_Error }); + } + + connection.send(JSON.stringify({ "success": !applyError, "log": log })); + return !applyError; + } + + async function handleMessage(message) { + const payload = JSON.parse(message.data); + const action = { + 'Reload': () => reload(), + 'Wait': () => wait(), + 'UpdateStaticFile': () => updateStaticFile(payload.path), + 'ApplyManagedCodeUpdates': () => applyManagedCodeUpdates(payload.sharedSecret, payload.deltas, payload.responseLoggingLevel), + 'ReportDiagnostics': () => reportDiagnostics(payload.diagnostics), + 'RefreshBrowser': () => refreshBrowser() + }; + + if (payload.type && action.hasOwnProperty(payload.type)) { + await action[payload.type](); + } else { + console.error('Unknown payload:', message.data); + } + } + + // The provider proves it decrypted the secret this browser generated, which is only possible for + // the process holding the private key matching the build-pinned public key. + function authenticateProvider(providerSecret) { + return providerSecret === sharedSecret.encodedSharedSecret; + } + + async function reloadWhenApplicationReturns() { + while (true) { + await new Promise(resolve => setTimeout(resolve, 100)); + try { + const response = await fetch(moduleUrl, { cache: 'no-store' }); + if (response.ok) { + location.reload(); + return; + } + } catch (error) { + // The application is still restarting. + } + } + } + + function updateStaticFile(path) { + if (path && path.endsWith('.css')) { + updateCssByPath(path); + } else { + console.debug(`File change detected to file ${path}. Reloading page...`); + location.reload(); + return; + } + } + + async function updateCssByPath(path) { + const styleElement = document.querySelector(`link[href^="${path}"]`) || + document.querySelector(`link[href^="${document.baseURI}${path}"]`); + + // Receive a Clear-site-data header. + await fetch(new URL(clearCachePath, document.baseURI), { cache: 'no-store' }); + + if (!styleElement || !styleElement.parentNode) { + console.debug('Unable to find a stylesheet to update. Updating all local css files.'); + updateAllLocalCss(); + } + + updateCssElement(styleElement); + } + + function updateAllLocalCss() { + [...document.querySelectorAll('link')] + .filter(l => l.baseURI === document.baseURI) + .forEach(e => updateCssElement(e)); + } + + function updateCssElement(styleElement) { + if (!styleElement || styleElement.loading) { + // A file change notification may be triggered for the same file before the browser + // finishes processing a previous update. In this case, it's easiest to ignore later updates + return; + } + + const newElement = styleElement.cloneNode(); + const href = styleElement.href; + newElement.href = href.split('?', 1)[0] + `?nonce=${Date.now()}`; + + styleElement.loading = true; + newElement.loading = true; + newElement.addEventListener('load', function () { + newElement.loading = false; + styleElement.remove(); + }); + + styleElement.parentNode.insertBefore(newElement, styleElement.nextSibling); + } + + function applyDeltas_legacy(deltas) { + let apply = window.Blazor?._internal?.applyHotReload + + // Only apply hot reload deltas if Blazor has been initialized. + // It's possible for Blazor to start after the initial page load, so we don't consider skipping this step + // to be a failure. These deltas will get applied later, when Blazor completes initialization. + if (apply) { + deltas.forEach(d => { + if (apply.length == 5) { + // WASM 8.0 + apply(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta, d.updatedTypes) + } else { + // WASM 9.0 + apply(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta) + } + }); + } + } + + function applyDeltas(deltas, responseLoggingLevel) { + let applyDeltas = hotReloadAgentSignal().applyHotReloadDeltas ?? window.Blazor?._internal?.applyHotReloadDeltas + if (applyDeltas) { + // Only apply hot reload deltas if Blazor has been initialized. + // It's possible for Blazor to start after the initial page load, so we don't consider skipping this step + // to be a failure. These deltas will get applied later, when Blazor completes initialization. + + let wasmDeltas = deltas.map(delta => { + return { + "moduleId": delta.moduleId, + "metadataDelta": delta.metadataDelta, + "ilDelta": delta.ilDelta, + "pdbDelta": delta.pdbDelta, + "updatedTypes": delta.updatedTypes, + }; + }); + + return applyDeltas(wasmDeltas, responseLoggingLevel); + } + + // Try invoke older WASM API: + applyDeltas_legacy(deltas) + return []; + } + + function applyManagedCodeUpdates(providerSecret, deltas, responseLoggingLevel) { + if (!authenticateProvider(providerSecret)) { + throw 'Unable to validate the server. Rejecting apply-update payload.'; + } + + console.debug('Applying managed code updates.'); + + let applyError = undefined; + let log = []; + try { + log = applyDeltas(deltas, responseLoggingLevel); + } catch (error) { + console.warn(error); + applyError = error; + log.push({ "message": getMessageAndStack(error), "severity": AgentMessageSeverity_Error }); + } + + connection.send(JSON.stringify({ + "success": !applyError, + "log": log + })); + + if (!applyError) { + displayChangesAppliedToast(); + } + } + + function reportDiagnostics(diagnostics) { + console.debug('Reporting Hot Reload diagnostics.'); + + document.querySelectorAll('#dotnet-compile-error').forEach(el => el.remove()); + + if (diagnostics.length == 0) { + return; + } + + const { host: el, root } = createBrowserToolsHost('dotnet-compile-error'); + document.body.appendChild(el); + diagnostics.forEach(error => { + const item = root.appendChild(document.createElement('div')); + item.className = 'dotnet-compile-error-item'; + const message = item.appendChild(document.createElement('div')); + message.className = 'dotnet-compile-error-message'; + message.textContent = error.Message; + item.appendChild(document.createElement('div')).textContent = error; + }); + } + + function displayChangesAppliedToast() { + document.querySelectorAll('#dotnet-compile-error').forEach(el => el.remove()); + if (document.querySelector('#dotnet-hotreload-toast')) { + return; + } + if (!window[hotReloadActiveKey]) + { + return; + } + const { host: el, root } = createBrowserToolsHost('dotnet-hotreload-toast'); + root.appendChild(createHotReloadToastIcon()); + document.body.appendChild(el); + window[hotReloadActiveKey] = false; + setTimeout(() => el.remove(), 2000); + } + + function createHotReloadToastIcon() { + const svgNamespace = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(svgNamespace, 'svg'); + svg.setAttribute('viewBox', '0 0 500 500'); + + const ellipse = svg.appendChild(document.createElementNS(svgNamespace, 'ellipse')); + ellipse.id = 'hotreloaded-ellipse1'; + ellipse.setAttribute('rx', '212.808853'); + ellipse.setAttribute('ry', '205.404598'); + ellipse.setAttribute('transform', 'matrix(0.982102 0 0 1.017504 251 238)'); + ellipse.setAttribute('opacity', '0'); + ellipse.setAttribute('fill', 'rgb(120,120,120)'); + + const path = svg.appendChild(document.createElementNS(svgNamespace, 'path')); + path.id = 'hotreloaded-path1'; + path.setAttribute('d', 'M126.151214,288.396852L196.625037,350.661591L320.793323,178.518242'); + path.setAttribute('transform', 'matrix(1 0 0 1 27.527732 -26.589916)'); + path.setAttribute('opacity', '0'); + path.setAttribute('fill', 'none'); + path.setAttribute('stroke', 'rgb(255,255,255)'); + path.setAttribute('stroke-width', '40'); + path.setAttribute('stroke-linecap', 'round'); + return svg; + } + + function createBrowserToolsHost(id) { + const host = document.createElement('div'); + host.id = id; + const root = host.attachShadow({ mode: 'open' }); + if ('adoptedStyleSheets' in root && typeof CSSStyleSheet === 'function') { + if (!browserToolsStylesheet) { + browserToolsStylesheet = new CSSStyleSheet(); + browserToolsStylesheet.replaceSync(browserToolsStyles); + } + + root.adoptedStyleSheets = [browserToolsStylesheet]; + } + + return { host, root }; + } + + function refreshBrowser() { + if (window.Blazor) { + window[hotReloadActiveKey] = true; + // hotReloadApplied triggers an enhanced navigation to + // refresh pages that have been statically rendered with + // Blazor SSR. + if (window.Blazor?._internal?.hotReloadApplied) + { + console.debug('Refreshing browser: WASM.'); + Blazor._internal.hotReloadApplied(); + } + else + { + console.debug('Refreshing browser.'); + displayChangesAppliedToast(); + } + } else { + console.debug('Refreshing browser: Reloading.'); + location.reload(); + } + } + + function reload() { + console.debug('Reloading.'); + location.reload(); + } + + function wait() { + console.debug('Waiting for application to rebuild.'); + + if (waiting) { + return; + } + + waiting = true; + const glyphs = ['☱', '☲', '☴']; + const title = document.title; + let i = 0; + setInterval(function () { document.title = glyphs[i++ % glyphs.length] + ' ' + title; }, 240); + } + + function getWebSocket(url, encryptedSecret, onMessage) { + return new Promise((resolve, reject) => { + const webSocket = new WebSocket(url, encodeURIComponent(encryptedSecret)); + let opened = false; + + // Listen for messages before the socket opens so that the session initialization message, + // which the provider sends first, can never be missed. + webSocket.addEventListener('message', onMessage); + + function onOpen() { + opened = true; + clearEventListeners(); + resolve(webSocket); + } + + function onClose(event) { + if (opened) { + // Open completed successfully. Nothing to do here. + return; + } + + let error = 'WebSocket failed to connect.'; + if (event instanceof ErrorEvent) { + error = event.error; + } + + clearEventListeners(); + reject(error); + } + + function clearEventListeners() { + webSocket.removeEventListener('open', onOpen); + // The error event isn't as reliable, but close is always called even during failures. + // If close is called without a corresponding open, we can reject the promise. + webSocket.removeEventListener('close', onClose); + } + + webSocket.addEventListener('open', onOpen); + webSocket.addEventListener('close', onClose); + if (window.Blazor?.removeEventListener && window.Blazor?.addEventListener) + { + webSocket.addEventListener('close', () => window.Blazor?.removeEventListener('enhancedload', displayChangesAppliedToast)); + window.Blazor?.addEventListener('enhancedload', displayChangesAppliedToast); + } + }); + } +} + +function getMessageAndStack(error) { + const message = error.message || '' + let messageAndStack = error.stack || message + if (!messageAndStack.includes(message)) { + messageAndStack = message + "\n" + messageAndStack; + } + + return messageAndStack +} + +// Rendezvous with the WebAssembly initializer. Either module may create the object first because +// library initializer module evaluation order is not guaranteed; the initializer resolves it. +function hotReloadAgentSignal() { + const agent = globalThis.__DOTNET_WATCH_HOT_RELOAD_AGENT ||= {}; + if (!agent.ready) { + agent.ready = new Promise(resolve => { agent.setReady = resolve; }); + } + + return agent; +} + +function hasDeltaApplyApi() { + return !!(hotReloadAgentSignal().applyHotReloadDeltas || window.Blazor?._internal?.applyHotReloadDeltas || window.Blazor?._internal?.applyHotReload); +} + +// The provider sends the replay snapshot once, so applying it before the agent installed the apply +// API would drop those updates while still reporting success. Wait for the agent to finish starting. +// Runtimes that install the apply API through their own bootstrap never publish the signal, so the +// wait is bounded and best effort. +async function waitForDeltaApplyApi() { + if (hasDeltaApplyApi()) { + return true; + } + + try { + await withTimeout(hotReloadAgentSignal().ready, hotReloadAgentReadyTimeoutMs); + } catch (error) { + console.debug('Timed out waiting for the Hot Reload agent.', error); + } + + return hasDeltaApplyApi(); +} + +function withTimeout(promise, milliseconds) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(`Timed out after ${milliseconds}ms.`), milliseconds); + promise.then( + value => { clearTimeout(timeout); resolve(value); }, + error => { clearTimeout(timeout); reject(error); }); + }); +} + +// Generates the secret this browser uses to authenticate the provider and encrypts it with the +// build-pinned public key. The secret itself never leaves the browser in clear text and is never +// persisted. +async function getSecret(serverKeyString) { + if (!serverKeyString || !window.crypto || !window.crypto.subtle) { + return null; + } + + const secretBytes = window.crypto.getRandomValues(new Uint8Array(32)); // 32-bytes of entropy + + // Based on https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#subjectpublickeyinfo_import + const binaryServerKey = str2ab(atob(serverKeyString)); + const serverKey = await window.crypto.subtle.importKey('spki', binaryServerKey, { name: "RSA-OAEP", hash: "SHA-256" }, false, ['encrypt']); + const encrypted = await window.crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverKey, secretBytes); + return { + encryptedSharedSecret: btoa(String.fromCharCode(...new Uint8Array(encrypted))), + encodedSharedSecret: btoa(String.fromCharCode(...secretBytes)), + }; + + function str2ab(str) { + const buf = new ArrayBuffer(str.length); + const bufView = new Uint8Array(buf); + for (let i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; + } +} diff --git a/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets b/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets new file mode 100644 index 000000000000..0b91a6a747c2 --- /dev/null +++ b/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets @@ -0,0 +1,222 @@ + + + + + + + + /_framework/dotnet-browser-tools + $(DotNetWatchBrowserToolsRoutePrefix)/hot-reload-settings.json + + + <_DotNetWatchBrowserToolsEnabled>$(EnableHotReloadInRuntimeConfigDevFile) + <_DotNetWatchBrowserToolsEnabled Condition="'$(_DotNetWatchBrowserToolsEnabled)' == '' and '$(Configuration)' == 'Debug'">true + + + + + + + + + + <_DotNetWatchBrowserToolsIntermediatePath>$(IntermediateOutputPath)dotnet-watch\ + <_DotNetWatchBrowserToolsPublicKeyFile>$(_DotNetWatchBrowserToolsIntermediatePath)browser-tools-key.public.json + <_DotNetWatchBrowserToolsPrivateKeyFile>$(_DotNetWatchBrowserToolsIntermediatePath)browser-tools-key.private.json + + <_DotNetWatchBrowserToolsInitializerFileName>$(DotNetWatchBrowserToolsAssetPrefix).lib.module.js + <_DotNetWatchBrowserToolsClientFileName>$(DotNetWatchBrowserToolsAssetPrefix).BrowserTools.js + <_DotNetWatchBrowserToolsConfigFileName>$(DotNetWatchBrowserToolsAssetPrefix).BrowserTools.Config.js + <_DotNetWatchBrowserToolsClientSource>$(MSBuildThisFileDirectory)DotNetWatch\dotnet-watch-browser-tools.js + <_DotNetWatchBrowserToolsConfigTemplate>$(MSBuildThisFileDirectory)DotNetWatch\dotnet-watch-browser-tools.config.js.template + + + <_DotNetWatchBrowserToolsRuntimeHotReloadAgent>false + <_DotNetWatchBrowserToolsRuntimeHotReloadAgent + Condition="$([MSBuild]::VersionEquals('$(TargetFrameworkVersion)', '9.0'))">true + + + + + + + + + + + + + + <_DotNetWatchBrowserToolsInitializerContent>$([System.IO.File]::ReadAllText('$(DotNetWatchBrowserToolsInitializerFile)')) + <_DotNetWatchBrowserToolsInitializerContent>$(_DotNetWatchBrowserToolsInitializerContent.Replace('__RUNTIME_HOT_RELOAD_AGENT__', '$(_DotNetWatchBrowserToolsRuntimeHotReloadAgent)')) + <_DotNetWatchBrowserToolsInitializerContent>$(_DotNetWatchBrowserToolsInitializerContent.Replace('__SDK_HOT_RELOAD_AGENT__', '$(DotNetWatchBrowserToolsUseSdkHotReloadAgent)')) + <_DotNetWatchBrowserToolsInitializerContent>$(_DotNetWatchBrowserToolsInitializerContent.Replace('__SETTINGS_PATH__', '$(DotNetWatchBrowserToolsSettingsPath)')) + <_DotNetWatchBrowserToolsInitializerContent>$(_DotNetWatchBrowserToolsInitializerContent.Replace('__CONFIG_MODULE__', './$(_DotNetWatchBrowserToolsConfigFileName)')) + + <_DotNetWatchBrowserToolsConfigContent>$([System.IO.File]::ReadAllText('$(_DotNetWatchBrowserToolsConfigTemplate)')) + <_DotNetWatchBrowserToolsConfigContent>$(_DotNetWatchBrowserToolsConfigContent.Replace('__CLIENT_MODULE__', '$(_DotNetWatchBrowserToolsClientFileName)')) + <_DotNetWatchBrowserToolsConfigContent>$(_DotNetWatchBrowserToolsConfigContent.Replace('__ROUTE_PREFIX__', '$(DotNetWatchBrowserToolsRoutePrefix)')) + <_DotNetWatchBrowserToolsConfigContent>$(_DotNetWatchBrowserToolsConfigContent.Replace('__PUBLIC_KEY__', '$(_DotNetWatchBrowserToolsPublicKey)')) + + + + + + + + + <_DotNetWatchBrowserToolsInitializer Include="$(_DotNetWatchBrowserToolsIntermediatePath)$(_DotNetWatchBrowserToolsInitializerFileName)"> + _framework/$(_DotNetWatchBrowserToolsInitializerFileName) + + <_DotNetWatchBrowserToolsInitializer Update="@(_DotNetWatchBrowserToolsInitializer)"> + %(Identity) + + + <_DotNetWatchBrowserToolsClientModule Include="$(_DotNetWatchBrowserToolsIntermediatePath)$(_DotNetWatchBrowserToolsClientFileName)"> + _framework/$(_DotNetWatchBrowserToolsClientFileName) + + <_DotNetWatchBrowserToolsClientModule Include="$(_DotNetWatchBrowserToolsIntermediatePath)$(_DotNetWatchBrowserToolsConfigFileName)"> + _framework/$(_DotNetWatchBrowserToolsConfigFileName) + + <_DotNetWatchBrowserToolsClientModule Update="@(_DotNetWatchBrowserToolsClientModule)"> + %(Identity) + + + + + + + + + + + + + + + <_JSModuleStaticWebAsset Include="@(_DotNetWatchBrowserToolsInitializerAsset)" /> + + + + + + + + + + + + + + + + + + + diff --git a/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.targets b/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.targets index b72da2d4f3c2..d6f029bde6b3 100644 --- a/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.targets +++ b/src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.targets @@ -886,6 +886,8 @@ Copyright (c) .NET Foundation. All rights reserved. + + diff --git a/src/StaticWebAssetsSdk/Tasks/EnsureDotNetWatchBrowserToolsKey.cs b/src/StaticWebAssetsSdk/Tasks/EnsureDotNetWatchBrowserToolsKey.cs new file mode 100644 index 000000000000..e8298560adfa --- /dev/null +++ b/src/StaticWebAssetsSdk/Tasks/EnsureDotNetWatchBrowserToolsKey.cs @@ -0,0 +1,141 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable disable + +using Microsoft.AspNetCore.StaticWebAssets.Tasks.Utils; +using Microsoft.Build.Framework; + +namespace Microsoft.AspNetCore.StaticWebAssets.Tasks; + +/// +/// Ensures that the project has a dotnet watch browser tools key pair in its intermediate +/// output and reports the public half. +/// +/// The browser authenticates the dotnet watch provider with a key that the application pins +/// at build time, so the key has to be produced by the build rather than handed to it: a provider +/// that supplied its own key would be authenticating itself. The build therefore owns the key pair, +/// writes the two halves to separate files, and only the public half is ever pinned into an +/// application asset. +/// +/// The task is incremental. An existing pair is reused whenever both documents parse, have the +/// current version and algorithm, and describe the same key, which keeps the generated configuration +/// module byte identical across rebuilds and keeps downstream static web asset incrementality +/// intact. Anything else - a missing file, a truncated file, a document from an older SDK, or two +/// files that do not belong to each other - regenerates both halves. +/// +/// The private half is never logged, never returned as an output, and never becomes a static web +/// asset. Both files are reported through FileWrites by the caller so that Clean +/// removes them. +/// +public class EnsureDotNetWatchBrowserToolsKey : Task +{ + /// + /// Path of the JSON document that holds the base64 X.509 SubjectPublicKeyInfo. + /// + [Required] + public string PublicKeyPath { get; set; } + + /// + /// Path of the JSON document that holds the private key components. Consumed only by + /// dotnet watch. + /// + [Required] + public string PrivateKeyPath { get; set; } + + /// + /// Base64 X.509 SubjectPublicKeyInfo of the key pair. Safe to pin into build output. + /// + [Output] + public string PublicKey { get; set; } + + /// + /// True when a new key pair had to be created. Only used for diagnostics and tests. + /// + [Output] + public bool Regenerated { get; set; } + + public override bool Execute() + { + try + { + if (TryReuseExistingKeyPair(out var existingPublicKey)) + { + PublicKey = existingPublicKey; + Regenerated = false; + Log.LogMessage(MessageImportance.Low, "Reusing the existing dotnet-watch browser tools key pair."); + return true; + } + + var (publicKey, parameters) = BrowserToolsKeyPair.Create(); + + var directory = Path.GetDirectoryName(PrivateKeyPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + directory = Path.GetDirectoryName(PublicKeyPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + // The private half is written first. If the process is interrupted between the two + // writes the public document is missing, which the reuse check treats as invalid, so an + // interrupted run can never leave a public key that no private key matches. + File.WriteAllBytes(PrivateKeyPath, BrowserToolsKeyPair.CreatePrivateKeyDocument(publicKey, parameters)); + File.WriteAllBytes(PublicKeyPath, BrowserToolsKeyPair.CreatePublicKeyDocument(publicKey)); + + PublicKey = publicKey; + Regenerated = true; + + Log.LogMessage(MessageImportance.Low, "Generated a new dotnet-watch browser tools key pair."); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The message of an IO exception contains paths only, never key material. + Log.LogError("Unable to create the dotnet-watch browser tools key pair: {0}", ex.Message); + return false; + } + } + + private bool TryReuseExistingKeyPair(out string publicKey) + { + publicKey = null; + + var publicDocument = BrowserToolsKeyPair.TryReadPublicKeyFile(PublicKeyPath); + if (!publicDocument.IsValid) + { + Log.LogMessage(MessageImportance.Low, "Regenerating the dotnet-watch browser tools key pair because the public key document is not usable: {0}.", publicDocument.Reason); + return false; + } + + var privateDocument = BrowserToolsKeyPair.TryReadPrivateKeyFile(PrivateKeyPath); + if (!privateDocument.IsValid) + { + Log.LogMessage(MessageImportance.Low, "Regenerating the dotnet-watch browser tools key pair because the private key document is not usable: {0}.", privateDocument.Reason); + return false; + } + + if (!string.Equals(publicDocument.PublicKey, privateDocument.PublicKey, StringComparison.Ordinal)) + { + Log.LogMessage(MessageImportance.Low, "Regenerating the dotnet-watch browser tools key pair because the two documents describe different keys."); + return false; + } + + // The recorded public key is not trusted on its own: it is re-derived from the private + // components so that a hand edited or partially written pair cannot pin a key that the + // provider is unable to use. + if (!BrowserToolsKeyPair.TryDerivePublicKey(privateDocument.Parameters, out var derivedPublicKey) || + !string.Equals(derivedPublicKey, publicDocument.PublicKey, StringComparison.Ordinal)) + { + Log.LogMessage(MessageImportance.Low, "Regenerating the dotnet-watch browser tools key pair because the private key does not match the public key."); + return false; + } + + publicKey = publicDocument.PublicKey; + return true; + } +} diff --git a/src/StaticWebAssetsSdk/Tasks/Utils/BrowserToolsKeyPair.cs b/src/StaticWebAssetsSdk/Tasks/Utils/BrowserToolsKeyPair.cs new file mode 100644 index 000000000000..f67b07fef173 --- /dev/null +++ b/src/StaticWebAssetsSdk/Tasks/Utils/BrowserToolsKeyPair.cs @@ -0,0 +1,397 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable disable + +using System.Security.Cryptography; +using System.Text.Json; + +namespace Microsoft.AspNetCore.StaticWebAssets.Tasks.Utils; + +/// +/// Reads and writes the two JSON documents that describe the dotnet watch browser tools key +/// pair. The public document is the only half that is ever pinned into the application build output; +/// the private document is consumed exclusively by dotnet watch to key its provider. +/// +/// Both documents are versioned so that a key produced by an older SDK is treated as invalid rather +/// than misinterpreted, and both carry the same base64 X.509 SubjectPublicKeyInfo value so that a +/// mismatch between the two files can be detected without deriving anything. +/// +/// The representation of the private half is the raw components rather +/// than PKCS#8 because the task runs on .NET Framework as well, where the PKCS#8 import and export +/// APIs are not available. +/// +internal static class BrowserToolsKeyPair +{ + public const int CurrentVersion = 1; + + /// + /// The padding the browser uses to encrypt the shared secret and the provider uses to decrypt + /// it. Recorded so that a future change of algorithm invalidates existing key files. + /// + public const string Algorithm = "RSA-OAEP-SHA256"; + + public const string PublicKeyFormat = "SubjectPublicKeyInfo"; + public const string PrivateKeyFormat = "RSAParameters"; + + public const int KeySizeInBits = 2048; + + /// + /// Result of reading a key document. is false for anything that is not a + /// well formed, current version document; the caller regenerates in that case. The failure + /// reason never contains key material. + /// + public readonly struct ReadResult(bool isValid, string publicKey, RSAParameters parameters, string reason) + { + public bool IsValid { get; } = isValid; + public string PublicKey { get; } = publicKey; + public RSAParameters Parameters { get; } = parameters; + public string Reason { get; } = reason; + + public static ReadResult Invalid(string reason) => new(false, null, default, reason); + } + + public static ReadResult TryReadPublicKeyFile(string path) + { + try + { + if (!File.Exists(path)) + { + return ReadResult.Invalid("the file does not exist"); + } + + using var document = JsonDocument.Parse(File.ReadAllBytes(path)); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return ReadResult.Invalid("the document is not a JSON object"); + } + + if (!TryValidateHeader(root, PublicKeyFormat, out var headerError)) + { + return ReadResult.Invalid(headerError); + } + + if (!TryGetBase64(root, "publicKey", out var publicKey, out _)) + { + return ReadResult.Invalid("the 'publicKey' property is missing or is not base64"); + } + + return new ReadResult(true, publicKey, default, null); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + return ReadResult.Invalid($"the file could not be read ({ex.GetType().Name})"); + } + } + + public static ReadResult TryReadPrivateKeyFile(string path) + { + try + { + if (!File.Exists(path)) + { + return ReadResult.Invalid("the file does not exist"); + } + + using var document = JsonDocument.Parse(File.ReadAllBytes(path)); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return ReadResult.Invalid("the document is not a JSON object"); + } + + if (!TryValidateHeader(root, PrivateKeyFormat, out var headerError)) + { + return ReadResult.Invalid(headerError); + } + + if (!TryGetBase64(root, "publicKey", out var publicKey, out _)) + { + return ReadResult.Invalid("the 'publicKey' property is missing or is not base64"); + } + + if (!root.TryGetProperty("parameters", out var parameters) || parameters.ValueKind != JsonValueKind.Object) + { + return ReadResult.Invalid("the 'parameters' property is missing or is not an object"); + } + + var rsaParameters = new RSAParameters(); + foreach (var (name, setter) in ParameterSetters) + { + if (!TryGetBase64(parameters, name, out _, out var value)) + { + return ReadResult.Invalid($"the private key component '{name}' is missing or is not base64"); + } + + setter(ref rsaParameters, value); + } + + return new ReadResult(true, publicKey, rsaParameters, null); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + return ReadResult.Invalid($"the file could not be read ({ex.GetType().Name})"); + } + } + + private delegate void ParameterSetter(ref RSAParameters parameters, byte[] value); + + private static readonly (string Name, ParameterSetter Setter)[] ParameterSetters = + [ + ("modulus", static (ref RSAParameters p, byte[] v) => p.Modulus = v), + ("exponent", static (ref RSAParameters p, byte[] v) => p.Exponent = v), + ("d", static (ref RSAParameters p, byte[] v) => p.D = v), + ("p", static (ref RSAParameters p, byte[] v) => p.P = v), + ("q", static (ref RSAParameters p, byte[] v) => p.Q = v), + ("dp", static (ref RSAParameters p, byte[] v) => p.DP = v), + ("dq", static (ref RSAParameters p, byte[] v) => p.DQ = v), + ("inverseQ", static (ref RSAParameters p, byte[] v) => p.InverseQ = v), + ]; + + private static bool TryValidateHeader(JsonElement root, string expectedFormat, out string error) + { + if (!root.TryGetProperty("version", out var version) || version.ValueKind != JsonValueKind.Number || !version.TryGetInt32(out var versionValue)) + { + error = "the 'version' property is missing or is not a number"; + return false; + } + + if (versionValue != CurrentVersion) + { + error = $"the document version '{versionValue}' is not supported"; + return false; + } + + if (!root.TryGetProperty("algorithm", out var algorithm) || algorithm.ValueKind != JsonValueKind.String || algorithm.GetString() != Algorithm) + { + error = "the 'algorithm' property is missing or does not match the expected algorithm"; + return false; + } + + if (!root.TryGetProperty("format", out var format) || format.ValueKind != JsonValueKind.String || format.GetString() != expectedFormat) + { + error = "the 'format' property is missing or does not match the expected format"; + return false; + } + + error = null; + return true; + } + + private static bool TryGetBase64(JsonElement element, string propertyName, out string text, out byte[] value) + { + text = null; + value = null; + + if (!element.TryGetProperty(propertyName, out var property) || property.ValueKind != JsonValueKind.String) + { + return false; + } + + var candidate = property.GetString(); + if (string.IsNullOrEmpty(candidate)) + { + return false; + } + + try + { + value = Convert.FromBase64String(candidate); + } + catch (FormatException) + { + return false; + } + + text = candidate; + return true; + } + + public static byte[] CreatePublicKeyDocument(string publicKey) + { + using var buffer = new MemoryStream(); + using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true })) + { + writer.WriteStartObject(); + WriteHeader(writer, PublicKeyFormat); + writer.WriteString("publicKey", publicKey); + writer.WriteEndObject(); + } + + return buffer.ToArray(); + } + + public static byte[] CreatePrivateKeyDocument(string publicKey, RSAParameters parameters) + { + using var buffer = new MemoryStream(); + using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true })) + { + writer.WriteStartObject(); + WriteHeader(writer, PrivateKeyFormat); + writer.WriteString("publicKey", publicKey); + writer.WriteStartObject("parameters"); + writer.WriteString("modulus", Convert.ToBase64String(parameters.Modulus)); + writer.WriteString("exponent", Convert.ToBase64String(parameters.Exponent)); + writer.WriteString("d", Convert.ToBase64String(parameters.D)); + writer.WriteString("p", Convert.ToBase64String(parameters.P)); + writer.WriteString("q", Convert.ToBase64String(parameters.Q)); + writer.WriteString("dp", Convert.ToBase64String(parameters.DP)); + writer.WriteString("dq", Convert.ToBase64String(parameters.DQ)); + writer.WriteString("inverseQ", Convert.ToBase64String(parameters.InverseQ)); + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + return buffer.ToArray(); + } + + private static void WriteHeader(Utf8JsonWriter writer, string format) + { + writer.WriteNumber("version", CurrentVersion); + writer.WriteString("algorithm", Algorithm); + writer.WriteString("format", format); + } + + /// + /// Exports the base64 X.509 SubjectPublicKeyInfo of . This is the exact + /// representation crypto.subtle.importKey('spki', ...) expects in the browser. + /// + public static string ExportPublicKey(RSA rsa) +#if NET + => Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo()); +#else + => Convert.ToBase64String(SubjectPublicKeyInfoWriter.Write(rsa.ExportParameters(includePrivateParameters: false))); +#endif + + /// + /// Derives the base64 SubjectPublicKeyInfo that corresponds to a private key so that a key file + /// pair can be checked for consistency without trusting the recorded value. + /// + public static bool TryDerivePublicKey(RSAParameters parameters, out string publicKey) + { + try + { + using var rsa = RSA.Create(); + rsa.ImportParameters(parameters); + publicKey = ExportPublicKey(rsa); + return true; + } + catch (CryptographicException) + { + publicKey = null; + return false; + } + } + + public static (string PublicKey, RSAParameters Parameters) Create() + { + // The key size has to be requested at creation time: on .NET Framework the provider creates + // the key eagerly and assigning KeySize afterwards would not regenerate it. +#if NET + using var rsa = RSA.Create(KeySizeInBits); +#else + using var rsa = new RSACryptoServiceProvider(KeySizeInBits); +#endif + return (ExportPublicKey(rsa), rsa.ExportParameters(includePrivateParameters: true)); + } + +#if !NET + /// + /// Minimal DER writer for the X.509 SubjectPublicKeyInfo of an RSA public key. .NET Framework + /// has no ExportSubjectPublicKeyInfo, and the value has to be byte for byte identical to + /// the one .NET produces because dotnet watch validates the two against each other. + /// + private static class SubjectPublicKeyInfoWriter + { + private static readonly byte[] RsaEncryptionOid = [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01]; + + public static byte[] Write(RSAParameters parameters) + { + if (parameters.Modulus == null || parameters.Exponent == null) + { + throw new CryptographicException("The RSA parameters do not contain public key information."); + } + + // RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER } + using var rsaPublicKey = new MemoryStream(); + WriteInteger(rsaPublicKey, parameters.Modulus); + WriteInteger(rsaPublicKey, parameters.Exponent); + var rsaPublicKeySequence = WrapSequence(rsaPublicKey.ToArray()); + + // AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters NULL } + using var algorithm = new MemoryStream(); + WriteTagged(algorithm, 0x06, RsaEncryptionOid); + WriteTagged(algorithm, 0x05, []); + var algorithmSequence = WrapSequence(algorithm.ToArray()); + + // BIT STRING with zero unused bits wrapping the RSAPublicKey. + var bitStringContent = new byte[rsaPublicKeySequence.Length + 1]; + bitStringContent[0] = 0x00; + Array.Copy(rsaPublicKeySequence, 0, bitStringContent, 1, rsaPublicKeySequence.Length); + + using var subjectPublicKeyInfo = new MemoryStream(); + subjectPublicKeyInfo.Write(algorithmSequence, 0, algorithmSequence.Length); + WriteTagged(subjectPublicKeyInfo, 0x03, bitStringContent); + + return WrapSequence(subjectPublicKeyInfo.ToArray()); + } + + private static byte[] WrapSequence(byte[] content) + { + using var stream = new MemoryStream(); + WriteTagged(stream, 0x30, content); + return stream.ToArray(); + } + + private static void WriteTagged(Stream stream, byte tag, byte[] content) + { + stream.WriteByte(tag); + WriteLength(stream, content.Length); + stream.Write(content, 0, content.Length); + } + + private static void WriteInteger(Stream stream, byte[] value) + { + var offset = 0; + while (offset < value.Length - 1 && value[offset] == 0) + { + offset++; + } + + var length = value.Length - offset; + var needsPadding = value[offset] > 0x7f; + + stream.WriteByte(0x02); + WriteLength(stream, needsPadding ? length + 1 : length); + if (needsPadding) + { + stream.WriteByte(0x00); + } + + stream.Write(value, offset, length); + } + + private static void WriteLength(Stream stream, int length) + { + if (length < 0x80) + { + stream.WriteByte((byte)length); + return; + } + + var bytesRequired = 0; + for (var remaining = length; remaining > 0; remaining >>= 8) + { + bytesRequired++; + } + + stream.WriteByte((byte)(bytesRequired | 0x80)); + for (var i = bytesRequired - 1; i >= 0; i--) + { + stream.WriteByte((byte)((length >> (8 * i)) & 0xff)); + } + } + } +#endif +} diff --git a/src/WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template b/src/WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template new file mode 100644 index 000000000000..ea326600f5c9 --- /dev/null +++ b/src/WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template @@ -0,0 +1,114 @@ +// Activates the browser tools client. Added when Hot Reload build outputs are enabled. +// +// The provider reports its availability over a stable application route. The initializer does not +// require the launcher to mutate application files or pass activation state through the build. + +// Substituted by Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets. True only when the target +// framework's built-in WebAssembly Hot Reload agent has to be enabled explicitly. +const useRuntimeHotReloadAgent = __RUNTIME_HOT_RELOAD_AGENT__; + +// Substituted by Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets. True when the SDK ships the +// WebAssembly Hot Reload agent assembly and this initializer must install its apply API. +const useSdkHotReloadAgent = __SDK_HOT_RELOAD_AGENT__; + +// Substituted by Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets. +const settingsPath = '__SETTINGS_PATH__'; +const settingsRequestTimeoutMilliseconds = 5000; + +// Substituted by Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets. The configuration is app +// hosted and sits next to this initializer, so resolving it relative to import.meta.url keeps it +// correct under any static web asset base path or fingerprinting scheme. +const configModulePath = '__CONFIG_MODULE__'; + +let hotReloadEnabled = false; + +export async function onRuntimeConfigLoaded(config) { + if (config.debugLevel === 0) { + return; + } + + hotReloadEnabled = await isHotReloadEnabled(); + if (!hotReloadEnabled) { + return; + } + + // Activates the SDK Hot Reload agent on .NET 10+. + // Do not use __ASPNETCORE_BROWSER_TOOLS for this: .NET 8 interprets it as a request to load the + // legacy application-hosted blazor-hotreload.js module, which the SDK no longer produces. + config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"] ??= "debug"; + config.environmentVariables["__DOTNET_WATCH_BROWSER_TOOLS"] ??= "true"; + + if (useRuntimeHotReloadAgent) { + // .NET 9 keeps its Hot Reload agent null unless WebAssemblyHotReload.InitializeAsync runs, and + // that only happens when this variable is set. Without it applyHotReloadDeltas returns an empty + // log and silently applies nothing, so an edit is acknowledged but never takes effect. + config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"] ??= "true"; + } + +} + +export async function onRuntimeReady(runtime) { + if (!hotReloadEnabled) { + return; + } + + if (useSdkHotReloadAgent) { + const agent = hotReloadAgentSignal(); + try { + const exports = await runtime.getAssemblyExports("Microsoft.DotNet.HotReload.WebAssembly.Browser"); + await exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.InitializeAsync(document.baseURI); + + agent.applyHotReloadDeltas = (deltas, loggingLevel) => { + const result = exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.ApplyHotReloadDeltas(JSON.stringify(deltas), loggingLevel); + return result ? JSON.parse(result) : []; + }; + + agent.getApplyUpdateCapabilities = () => { + return exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.GetApplyUpdateCapabilities() ?? ''; + }; + } catch (error) { + console.debug('Unable to initialize the dotnet-watch Hot Reload agent.', error); + } finally { + // Release the browser tools client even when agent initialization failed. It will report + // an apply failure instead of dropping replayed updates. + agent.setReady(); + } + } + + try { + await import(new URL(configModulePath, import.meta.url).href); + } catch (error) { + console.debug('Unable to load the dotnet-watch browser tools.', error); + } +} + +// Shared with the browser tools client. Library initializer module evaluation order is not +// guaranteed, so either module may create the rendezvous object first. +function hotReloadAgentSignal() { + const agent = globalThis.__DOTNET_WATCH_HOT_RELOAD_AGENT ||= {}; + if (!agent.ready) { + agent.ready = new Promise(resolve => { agent.setReady = resolve; }); + } + + return agent; +} + +async function isHotReloadEnabled() { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), settingsRequestTimeoutMilliseconds); + + try { + const response = await fetch(settingsPath, { cache: 'no-store', signal: controller.signal }); + if (!response.ok) { + return false; + } + + const settings = await response.json(); + return settings?.hotReload === true; + } catch (error) { + console.debug('Unable to read the dotnet-watch browser tools settings.', error); + return false; + } finally { + clearTimeout(timeout); + } +} diff --git a/src/WasmSdk/Sdk/Sdk.targets b/src/WasmSdk/Sdk/Sdk.targets index 886a1979a751..efc2b9a61bcc 100644 --- a/src/WasmSdk/Sdk/Sdk.targets +++ b/src/WasmSdk/Sdk/Sdk.targets @@ -28,12 +28,8 @@ Copyright (c) .NET Foundation. All rights reserved. <_WasmHotReloadIntermediatePath>$(IntermediateOutputPath)hotreload\ - - + PreserveNewest Never - <_WasmHotReloadModule Include="$(_WasmHotReloadIntermediatePath)Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js"> - _framework/Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js - - <_WasmHotReloadModule Update="@(_WasmHotReloadModule)"> - %(Identity) - - - - - - - - - - + + + Microsoft.NET.Sdk.WebAssembly.DotNetWatch + $(MSBuildThisFileDirectory)DotNetWatch\Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template + $(_WasmEnableHotReload) + false + + diff --git a/src/WebSdk/Web/Targets/DotNetWatch/Microsoft.NET.Sdk.BlazorWeb.DotNetWatch.lib.module.js b/src/WebSdk/Web/Targets/DotNetWatch/Microsoft.NET.Sdk.BlazorWeb.DotNetWatch.lib.module.js new file mode 100644 index 000000000000..b4cfe5c4392b --- /dev/null +++ b/src/WebSdk/Web/Targets/DotNetWatch/Microsoft.NET.Sdk.BlazorWeb.DotNetWatch.lib.module.js @@ -0,0 +1,41 @@ +// Activates the browser tools client in Blazor apps that render on the server (static SSR or +// Interactive Server), which the browser refresh TagHelper does not reach. +// +// The provider reports its availability over a stable application route. The configuration module +// is app hosted, so resolving it relative to import.meta.url keeps it correct under any static web +// asset base path or fingerprinting scheme. + +// Substituted by Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets. +const settingsPath = '__SETTINGS_PATH__'; +const configModulePath = '__CONFIG_MODULE__'; +const settingsRequestTimeoutMilliseconds = 5000; + +export async function afterWebStarted() { + if (!await isHotReloadEnabled()) { + return; + } + + // The browser tools client de-duplicates activation, so importing the configuration module is safe + // even when another initializer or the browser refresh TagHelper already imported it. + await import(new URL(configModulePath, import.meta.url).href); +} + +async function isHotReloadEnabled() { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), settingsRequestTimeoutMilliseconds); + + try { + const response = await fetch(settingsPath, { cache: 'no-store', signal: controller.signal }); + if (!response.ok) { + return false; + } + + const settings = await response.json(); + return settings?.hotReload === true; + } catch (error) { + console.debug('Unable to read the dotnet-watch browser tools settings.', error); + return false; + } finally { + clearTimeout(timeout); + } +} diff --git a/src/WebSdk/Web/Targets/Sdk.Server.targets b/src/WebSdk/Web/Targets/Sdk.Server.targets index 59ff584f2eac..08690d63d51e 100644 --- a/src/WebSdk/Web/Targets/Sdk.Server.targets +++ b/src/WebSdk/Web/Targets/Sdk.Server.targets @@ -32,6 +32,15 @@ Copyright (c) .NET Foundation. All rights reserved. + + + Microsoft.NET.Sdk.BlazorWeb.DotNetWatch + $(MSBuildThisFileDirectory)DotNetWatch\Microsoft.NET.Sdk.BlazorWeb.DotNetWatch.lib.module.js + true + +