diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d6b1a7c..b3fd896 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -64,6 +64,10 @@ jobs: sudo apt-get update sudo apt-get install -y ninja-build llvm-18-dev libgtk-4-dev libwebkitgtk-6.0-dev pkg-config xvfb dbus-x11 echo "NIL_CI_LLVM_DIR=/usr/lib/llvm-18/lib/cmake/llvm" >> "$GITHUB_ENV" + - name: Permit the installed Linux browser sandbox on this hosted runner + if: runner.os == 'Linux' + timeout-minutes: 3 + run: bash webview/scripts/ci-linux-browser.sh setup - name: Locate macOS LLVM development package if: runner.os == 'macOS' timeout-minutes: 5 @@ -77,12 +81,58 @@ jobs: shell: pwsh timeout-minutes: 3 run: | + $ErrorActionPreference = 'Stop' + $owned = Join-Path $env:RUNNER_TEMP 'webview-msvc-telemetry' + if (Test-Path -LiteralPath $owned) { throw 'Telemetry backup directory must be fresh' } + New-Item -ItemType Directory -Path $owned | Out-Null + $evidence = Join-Path $env:RUNNER_TEMP 'webview-ci/evidence' + New-Item -ItemType Directory -Path $evidence -Force | Out-Null + $manifest = Join-Path $owned 'manifest.json' + $report = [ordered]@{ scope = 'ephemeral GitHub runner, selected MSVC x64 toolchain only'; registry = @(); uploader = $null } + function Save-TelemetryState { + $report | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $manifest -Encoding utf8 + Copy-Item -LiteralPath $manifest -Destination (Join-Path $evidence 'msvc-telemetry-setup.json') -Force + } + Save-TelemetryState + # The user requested compiler telemetry disabled. These supported + # VS2022 opt-outs apply only to this disposable hosted runner. + foreach ($key in @('HKLM:\SOFTWARE\WOW6432Node\Microsoft\VSCommon\17.0\SQM', 'HKLM:\SOFTWARE\Policies\Microsoft\VisualStudio\SQM')) { + $item = Get-Item -LiteralPath $key -ErrorAction SilentlyContinue + $present = $null -ne $item -and $item.GetValueNames() -contains 'OptIn' + if ($present -and $item.GetValueKind('OptIn').ToString() -ne 'DWord') { throw 'Unexpected Visual Studio telemetry registry type' } + $report.registry += [ordered]@{ key = $key; present = $present; value = $(if ($present) { $item.GetValue('OptIn') } else { $null }) } + Save-TelemetryState + New-Item -Path $key -Force | Out-Null + New-ItemProperty -LiteralPath $key -Name OptIn -PropertyType DWord -Value 0 -Force | Out-Null + } + $env:VSCMD_SKIP_SENDTELEMETRY = '1' $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe' $installation = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath if (-not $installation) { throw 'Visual Studio x64 Build Tools are required' } & (Join-Path $installation 'Common7/Tools/Launch-VsDevShell.ps1') -Arch amd64 -HostArch amd64 -SkipAutomaticLocation - if (-not (Get-Command cl.exe -ErrorAction SilentlyContinue)) { throw 'MSVC compiler was not activated' } - foreach ($name in @('PATH','INCLUDE','LIB','LIBPATH','VSINSTALLDIR','VCINSTALLDIR','VCToolsInstallDir','VCToolsVersion','WindowsSdkDir','WindowsSDKVersion','UniversalCRTSdkDir','UCRTVersion')) { + $compiler = (Get-Command cl.exe -ErrorAction Stop).Source + $expectedCompiler = Join-Path $env:VCToolsInstallDir 'bin/Hostx64/x64/cl.exe' + if ((Resolve-Path -LiteralPath $compiler).Path -ine (Resolve-Path -LiteralPath $expectedCompiler).Path) { throw 'Selected compiler differs from the activated x64 toolchain' } + # The documented registry opt-out alone previously left VCTIP alive. + # Quarantine only this selected compiler's adjacent optional uploader; + # retain its signed bytes and ACL for the always-run restoration step. + $uploader = Join-Path (Split-Path -Parent $compiler) 'vctip.exe' + if (Test-Path -LiteralPath $uploader) { + $item = Get-Item -LiteralPath $uploader + if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $item.Length -gt 16777216) { throw 'Unexpected optional uploader file' } + $signature = Get-AuthenticodeSignature -LiteralPath $uploader + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch '(^|, )O=Microsoft Corporation(,|$)') { throw 'Optional uploader lacks a valid Microsoft signature' } + $hash = (Get-FileHash -LiteralPath $uploader -Algorithm SHA256).Hash + $backup = Join-Path $owned 'vctip.exe' + $sections = [Security.AccessControl.AccessControlSections]::Access -bor [Security.AccessControl.AccessControlSections]::Owner -bor [Security.AccessControl.AccessControlSections]::Group + $sddl = (Get-Acl -LiteralPath $uploader).GetSecurityDescriptorSddlForm($sections) + [IO.File]::WriteAllText((Join-Path $owned 'uploader-acl.sddl'), $sddl) + $report.uploader = [ordered]@{ source = $uploader; compiler = $compiler; backup = $backup; sha256 = $hash; signer = $signature.SignerCertificate.Subject; lastWriteUtc = $item.LastWriteTimeUtc.ToString('o') } + Save-TelemetryState + Move-Item -LiteralPath $uploader -Destination $backup + if ((Test-Path -LiteralPath $uploader) -or (Get-FileHash -LiteralPath $backup -Algorithm SHA256).Hash -ne $hash) { throw 'Optional uploader quarantine verification failed' } + } + foreach ($name in @('PATH','INCLUDE','LIB','LIBPATH','VSINSTALLDIR','VCINSTALLDIR','VCToolsInstallDir','VCToolsVersion','WindowsSdkDir','WindowsSDKVersion','UniversalCRTSdkDir','UCRTVersion','VSCMD_SKIP_SENDTELEMETRY')) { $value = [Environment]::GetEnvironmentVariable($name) if ($value) { "$name=$value" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append } } @@ -131,6 +181,64 @@ jobs: "$NIL_CI_PYTHON" -B webview/scripts/ci-build.py --phase desktop \ --framework framework --output "$RUNNER_TEMP/webview-ci" \ --expected-system "$NIL_CI_SYSTEM" --expected-machine "$NIL_CI_ARCH" + - name: Remove only the owned Linux AppArmor allowance + if: always() && runner.os == 'Linux' + timeout-minutes: 3 + run: bash webview/scripts/ci-linux-browser.sh cleanup + - name: Restore selected Windows optional uploader and telemetry settings + if: always() && runner.os == 'Windows' + shell: pwsh + timeout-minutes: 3 + run: | + $ErrorActionPreference = 'Stop' + $owned = Join-Path $env:RUNNER_TEMP 'webview-msvc-telemetry' + $manifest = Join-Path $owned 'manifest.json' + if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { exit 0 } + $state = Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json + $result = [ordered]@{ status = 'FAIL'; uploader = 'not quarantined'; registry = @() } + try { + if ($state.uploader) { + $entry = $state.uploader + $expectedBackup = Join-Path $owned 'vctip.exe' + $expectedSource = Join-Path (Split-Path -Parent $entry.compiler) 'vctip.exe' + if ($entry.backup -ine $expectedBackup -or $entry.source -ine $expectedSource) { throw 'Uploader backup metadata does not identify the selected adjacent file' } + if (Test-Path -LiteralPath $entry.backup -PathType Leaf) { + if (Test-Path -LiteralPath $entry.source) { throw 'Refusing to overwrite an uploader restoration collision' } + if ((Get-FileHash -LiteralPath $entry.backup -Algorithm SHA256).Hash -ne $entry.sha256) { throw 'Uploader backup hash changed' } + Move-Item -LiteralPath $entry.backup -Destination $entry.source + $sections = [Security.AccessControl.AccessControlSections]::Access -bor [Security.AccessControl.AccessControlSections]::Owner -bor [Security.AccessControl.AccessControlSections]::Group + $sddl = [IO.File]::ReadAllText((Join-Path $owned 'uploader-acl.sddl')) + $acl = [Security.AccessControl.FileSecurity]::new() + $acl.SetSecurityDescriptorSddlForm($sddl, $sections) + Set-Acl -LiteralPath $entry.source -AclObject $acl + [IO.File]::SetLastWriteTimeUtc($entry.source, [DateTime]::Parse($entry.lastWriteUtc).ToUniversalTime()) + } + if ((Get-FileHash -LiteralPath $entry.source -Algorithm SHA256).Hash -ne $entry.sha256) { throw 'Restored uploader hash differs' } + $sections = [Security.AccessControl.AccessControlSections]::Access -bor [Security.AccessControl.AccessControlSections]::Owner -bor [Security.AccessControl.AccessControlSections]::Group + $savedSddl = [IO.File]::ReadAllText((Join-Path $owned 'uploader-acl.sddl')) + if ((Get-Acl -LiteralPath $entry.source).GetSecurityDescriptorSddlForm($sections) -cne $savedSddl) { throw 'Restored uploader owner/group/DACL differs' } + $result.uploader = 'restored with original SHA256 and owner/group/DACL' + } + foreach ($entry in $state.registry) { + if ($entry.key -notin @('HKLM:\SOFTWARE\WOW6432Node\Microsoft\VSCommon\17.0\SQM', 'HKLM:\SOFTWARE\Policies\Microsoft\VisualStudio\SQM')) { throw 'Unexpected registry restoration target' } + $current = Get-ItemPropertyValue -LiteralPath $entry.key -Name OptIn -ErrorAction SilentlyContinue + if ($null -ne $current -and $current -ne 0) { throw 'Telemetry setting changed outside this step; preserving it' } + if ($entry.present) { + New-ItemProperty -LiteralPath $entry.key -Name OptIn -PropertyType DWord -Value $entry.value -Force | Out-Null + } elseif ($null -ne $current) { + Remove-ItemProperty -LiteralPath $entry.key -Name OptIn + } + $result.registry += $entry.key + } + $result.status = 'PASS' + } catch { + $result.error = $_.Exception.Message + throw + } finally { + $evidence = Join-Path $env:RUNNER_TEMP 'webview-ci/evidence' + New-Item -ItemType Directory -Path $evidence -Force | Out-Null + $result | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $evidence 'msvc-telemetry-restore.json') -Encoding utf8 + } - name: Upload complete or partial evidence only if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 diff --git a/README.md b/README.md index 0a27f61..f6e2afb 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,12 @@ WebView2 on Windows, and WKWebView on macOS. ## Status -This is the initial implementation. Shared ownership, JSON transport and checked -framework integration have local automated coverage. The Matrix wrapper has -been exercised with a synthetic provider through textual NIL, binary NIL, -native compilation and JIT. Actual browser qualification on Linux, Windows, -Intel macOS and Apple Silicon macOS is pending. A synthetic provider pass does -not establish browser behavior or qualify a published SDK. +The current source profile is implemented on Linux, Windows, Intel macOS and +Apple Silicon macOS. Each platform has a required real-browser check through +textual NIL, binary NIL, native compilation and JIT. See +[platform support and evidence](docs/platform-support.md) for the exact scope +and [current checks](https://github.com/exec-software/exec-nil-framework-webview/actions/workflows/test.yml) +for qualification results. These source checks do not qualify a published SDK. The current profile provides hidden-window creation, explicit showing, navigation, loading HTML, synchronous JavaScript function evaluation, copied @@ -48,9 +48,11 @@ alone is not proof of origin. Applications that require origin or frame checks must reject messages when the required native metadata is unavailable. Navigation accepts HTTP, HTTPS and `about:blank`. Each explicit call authorizes -one initial request. Redirects and uninitiated navigation are cancelled and +one initial request. Redirects and uninitiated document loads are cancelled and reported as `NavigationRequested`; the application may validate the requested destination and explicitly navigate after the previous operation completes. +Same-document fragment and history changes may update the current URL without +loading another document; they do not grant permission to load a new page. ## Build and try the example diff --git a/docs/api.md b/docs/api.md index d72d5ec..cee8345 100644 --- a/docs/api.md +++ b/docs/api.md @@ -71,7 +71,7 @@ An `Event` contains these fields: | `NavigationCompleted` / `NavigationFailed` | Completion of a host navigation; URI payloads are JSON strings, not sender provenance. | | `ScriptCompleted` / `ScriptFailed` | Evaluation result or failure for the matching operation. | | `PageMessage` | Serialized page JSON plus available native sender metadata. | -| `NavigationRequested` | Cancelled navigation destination as a JSON string; the application decides whether to follow. | +| `NavigationRequested` | Cancelled document-navigation destination as a JSON string; the application decides whether to follow. | | `CloseRequested` | Native/page close request; application calls `close-window`. | | `ProviderFailed` | Browser failure; close the affected window. | @@ -79,6 +79,11 @@ Failure kinds are `None`, `Native`, `ScriptException`, `Serialization`, `AsyncResult`, `PayloadLimit`, `Timeout` and `Cancelled`. Native diagnostic wording may differ by platform. +On Windows, `Ready.detail` includes `WebView2 ` followed by the browser version +reported by that window's actual environment. It identifies the runtime used +by the window, independently of the SDK/loader version used at build time. +Treat it as a diagnostic; it does not replace capability checks. + `poll-event` copies every event field and releases the runtime snapshot on both success and error paths. Applications do not call native snapshot-release APIs. The pump processes at most 64 native dispatch iterations with a 2 ms soft @@ -115,13 +120,23 @@ data. Never concatenate untrusted messages into evaluated JavaScript. ## Navigation policy Only an explicit `navigate` authorizes an initial URL request. Redirects, -page-initiated navigation and new-window requests are cancelled and reported +page-initiated document loads and new-window requests are cancelled and reported as `NavigationRequested`. If an active navigation was cancelled, it completes with `NavigationFailed` and `FailureKind.Cancelled`. Wait for that completion, decode the requested JSON string, apply the application's destination policy, then start a new `navigate` if approved. Do not automatically follow every request. This policy is common to all initial providers. +Host fragment navigation within the current document still has an operation +identity and completion, and preserves that document. Requesting the exact +current URL including its fragment is idempotent: it completes without +reloading or dispatching another native navigation. A same-URL request without +a fragment continues to use ordinary native navigation/reload behavior. +A page may also change its same-document fragment or +history URL state without loading a new document. Such URL changes are not a +cancellable document-load request and do not authorize a later document load. +The navigation policy is not a lock on the page's exact current URL. + `load-html` supplies no base URI. Relative assets, filesystem navigation, downloads and browser-managed popups are outside the initial profile. JavaScript alert/confirm/prompt dialogs are suppressed with immediate default responses; diff --git a/docs/platform-support.md b/docs/platform-support.md index e48d6d2..2b4822a 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -1,21 +1,57 @@ # Platform support and evidence -The initial provider implementations target the four hosts below. Actual -browser qualification is pending; this table must not be read as a release or -SDK compatibility guarantee. +The current provider profile is implemented for the four hosts below. Each +host has a required real-browser check; implementation alone is not a passing +qualification result or an installed-SDK compatibility guarantee. -| Host | Native provider | Native page-message metadata | Current browser evidence | +| Host | Native provider | Native page-message metadata | Required browser check | | --- | --- | --- | --- | -| Linux x86-64 | GTK4 + WebKitGTK 6 | None; capabilities are zero, sender fields/frame unknown | Pending | -| Windows x86-64 | Win32 + WebView2 | Native sender URL and main-frame identity from the top-level message event; origin unavailable | Pending | -| macOS Intel | AppKit + WKWebView | Native frame URL, security origin when available, and frame identity | Pending | -| macOS Apple Silicon | AppKit + WKWebView | Same API profile as Intel; requires its own architecture run | Pending | +| Linux x86-64 | GTK4 + WebKitGTK 6 | None; capabilities are zero, sender fields/frame unknown | `webview-linux-x86_64` | +| Windows x86-64 | Win32 + WebView2 | Native sender URL and main-frame identity from the top-level message event; origin unavailable | `webview-windows-x86_64` | +| macOS Intel | AppKit + WKWebView | Native frame URL, security origin when available, and frame identity | `webview-macos-x86_64` | +| macOS Apple Silicon | AppKit + WKWebView | Same API profile as Intel, tested independently | `webview-macos-arm64` | -Shared controls have local native coverage, including owner-thread and handle -checks, timeouts, queue limits, immutable snapshots, JSON validation and actual -generated JavaScript transport tests. Matrix wrapper checks with a synthetic -provider pass through textual NIL, binary NIL, native compilation and JIT. -These establish the checked interface, not a real engine's behavior. +See the [current platform runs](https://github.com/exec-software/exec-nil-framework-webview/actions/workflows/test.yml) +and the [initial qualification PR](https://github.com/exec-software/exec-nil-framework-webview/pull/1). +A run is qualified only when its required jobs pass. Cancelled builds, missing +desktops, partial route results and retained private profiles are failures or +incomplete evidence, not platform passes. + +## Source qualification evidence + +The workflow pins framework revision +`e7bc2a00e6854084b7b5084e29fa50456cbe8977`. Each job records its actual WebView +checkout (including GitHub's PR merge revision), framework revision, host, +toolchain, standard library and browser dependency identities. Download the +job's evidence artifact to inspect those identities, exact contract inventories, +route output, cleanup results and unchanged-source hashes. + +Each host must verify seven exact framework/provider contracts: 57 runtime +checks, 28 WebView ABI checks, 40 UI ABI checks, 216 formatted-text checks, +392 markup checks, 209 shared-provider checks and 36 JavaScript transport +checks. It then executes four synthetic and four actual browser consumers +through textual NIL, binary NIL, AOT and JIT. Every real-browser route must pass +all 17 behavior groups, including navigation policy, messages, dialogs, script +failures, copied events and window closure. No contract may be skipped. + +The browser fixture includes an initial full-document URL with a fragment, +changed and repeated same-document fragments, preserved DOM and JavaScript +state, a cancelled redirect followed by explicit host navigation, and a real +HTTP error document. Its owned HTTP server must observe exactly one request +each for the initial page, redirect, explicit follow and error document. +Windows enforces initial document requests before network dispatch as well as +cancelling unapproved navigation: [WebView2 documents that navigation cancellation alone can allow an early GET](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2navigationstartingeventargs#get_cancel). +Ordinary subresources retain normal browser behavior. This is not a general +network sandbox. + +All 14 owned commands and the loopback HTTP fixture must clean up, and source, +toolchain, standard-library and copied-provider hashes must remain unchanged. +Windows also checks for private profile remnants after every browser route, +including a window closed during asynchronous initialization. Linux verifies a +real browser namespace launch and restores the exact pre-test AppArmor profile +inventory. Mac evidence records the actual OS version for its system WKWebView; +Windows records the actual WebView2 environment version separately from the +pinned SDK/loader version. ## Dependencies and builds @@ -67,6 +103,17 @@ source builds from installed SDKs. Record failures, missing desktop sessions and skipped assertions explicitly. Do not activate a candidate SDK or replace a user installation as part of qualification. +Hosted Linux qualification grants only the installed WebKit bubblewrap +executable a temporary AppArmor user-namespace allowance, verifies a real +namespace launch, and removes the owned profile afterward. The WebKit sandbox +stays enabled; no global user-namespace policy is relaxed. Hosted Windows +qualification disables optional MSVC telemetry and temporarily removes only the +selected compiler's verified optional uploader. Its bytes, owner/group/DACL and +saved telemetry preferences are restored in the job's final cleanup. These +steps target disposable GitHub runners, not developer machines. +CMake's Windows probes and builds use embedded MSVC debug information (`/Z7`) +to avoid leaving a persistent compiler PDB server after the owning command exits. + ## Distribution Original nil-webview source is MIT licensed. GTK/WebKitGTK and their dependencies diff --git a/native/src/provider_linux.cpp b/native/src/provider_linux.cpp index 0bccd65..5eff914 100644 --- a/native/src/provider_linux.cpp +++ b/native/src/provider_linux.cpp @@ -27,19 +27,33 @@ struct LinuxWindow final : Window { WebKitWebView *view = nullptr; WebKitUserContentManager *manager = nullptr; GCancellable *script_cancel = nullptr; + GCancellable *fragment_cancel = nullptr; + std::int64_t fragment_dispatch_operation = 0; std::int64_t script_operation = 0; std::int64_t navigation_operation = 0; bool initializing = true; bool initial_policy = false; bool policy_cancelled = false; bool load_started = false; + bool fragment_navigation = false; + bool fragment_dispatch_complete = false; bool stopped = false; std::string requested_uri; + void cancel_fragment_dispatch() noexcept { + fragment_dispatch_operation = 0; + if (fragment_cancel) { + g_cancellable_cancel(fragment_cancel); + g_object_unref(fragment_cancel); + fragment_cancel = nullptr; + } + } void cancel_native() noexcept { if (stopped) return; stopped = true; initial_policy = false; + fragment_navigation = false; + cancel_fragment_dispatch(); if (script_cancel) g_cancellable_cancel(script_cancel); if (view) webkit_web_view_stop_loading(view); } @@ -147,9 +161,15 @@ void connect_signal(gpointer object, const char *name, GCallback function, void load_changed(WebKitWebView *, WebKitLoadEvent event, gpointer data) noexcept { callback(data, [&](LinuxContext &state, const auto &window) { - if (event == WEBKIT_LOAD_STARTED) { window->load_started = true; return; } + if (event == WEBKIT_LOAD_STARTED) { + window->load_started = true; + window->fragment_navigation = false; + return; + } if (event != WEBKIT_LOAD_FINISHED || !window->load_started) return; window->load_started = false; + window->fragment_navigation = false; + window->cancel_fragment_dispatch(); window->initial_policy = false; if (window->initializing) { window->initializing = false; @@ -172,6 +192,8 @@ void load_changed(WebKitWebView *, WebKitLoadEvent event, gpointer data) noexcep gboolean load_failed(WebKitWebView *, WebKitLoadEvent, const char *, GError *error, gpointer data) noexcept { callback(data, [&](LinuxContext &state, const auto &window) { window->load_started = false; + window->fragment_navigation = false; + window->cancel_fragment_dispatch(); window->initial_policy = false; const auto detail = native_detail(error, "WebKit navigation failed"); if (window->initializing) { @@ -218,7 +240,16 @@ gboolean decide_policy(WebKitWebView *, WebKitPolicyDecision *decision, state.navigation_requested(window, uri); if (window->navigation_operation) { window->policy_cancelled = true; + const bool fragment = window->fragment_navigation; + window->fragment_navigation = false; window->initial_policy = false; + if (fragment) { + const auto operation = window->navigation_operation; + window->navigation_operation = 0; + window->cancel_fragment_dispatch(); + state.navigation_finished(window, operation, false, {}, + "Navigation requires explicit application authorization", NILWV_FAILURE_CANCELLED); + } cancel_active_navigation = true; } } @@ -288,6 +319,35 @@ struct ScriptCompletion { std::int64_t operation; }; +void fragment_dispatched(GObject *object, GAsyncResult *result, gpointer data) noexcept { + std::unique_ptr completion(static_cast(data)); + GError *error = nullptr; + JSCValue *value = webkit_web_view_evaluate_javascript_finish(WEBKIT_WEB_VIEW(object), result, &error); + auto window = completion->window.lock(); + auto state = window ? window->context.lock() : nullptr; + if (state && state->owner_thread() && state->live(window)) { + if (window->fragment_dispatch_operation == completion->operation) { + window->fragment_dispatch_operation = 0; + if (window->fragment_cancel) { g_object_unref(window->fragment_cancel); window->fragment_cancel = nullptr; } + } + try { + if (!window->failed && window->fragment_navigation && + window->navigation_operation == completion->operation && + window->operation == completion->operation && window->operation_kind == Operation::navigation) { + if (error || !value) { + window->fragment_navigation = false; + window->initial_policy = false; + window->navigation_operation = 0; + state->navigation_finished(window, completion->operation, false, {}, + native_detail(error, "WebKit same-document navigation dispatch failed")); + } else window->fragment_dispatch_complete = true; + } + } catch (...) { state->callback_failed(); } + } + if (value) g_object_unref(value); + if (error) g_error_free(error); +} + void script_completed(GObject *object, GAsyncResult *result, gpointer data) noexcept { std::unique_ptr completion(static_cast(data)); GError *error = nullptr; @@ -433,14 +493,49 @@ void NILWV_CALL navigate(nilwv_context_v1 *context, std::int64_t id, if (!copy_native(webkit_uri_request_get_uri(request), uri) || uri.empty()) { state.fail(out, NILWV_E_ARGUMENT, "Navigation URI cannot be represented within the text bound"); return; } + std::string current_uri; + const auto fragment = uri.find('#'); + const bool fragment_navigation = !webkit_web_view_is_loading(window->view) && + copy_native(webkit_web_view_get_uri(window->view), current_uri) && + fragment != std::string::npos && + current_uri.compare(0, current_uri.find('#'), uri, 0, fragment) == 0; + const bool repeated_fragment = fragment_navigation && current_uri == uri; + std::string fragment_script; + std::unique_ptr completion; + std::unique_ptr cancel(nullptr, g_object_unref); + if (fragment_navigation && !repeated_fragment) { + fragment_script = "window.location.assign(" + json_string(uri) + "); void 0;"; + completion = std::make_unique(); + completion->window = window; + cancel.reset(g_cancellable_new()); + if (!cancel) { state.fail(out, NILWV_E_NATIVE, "Navigation cancellation state creation failed"); return; } + } const auto operation = state.start(window, Operation::navigation, out); if (!operation) return; + if (repeated_fragment) { + // Repeating an exact settled fragment URI is an API-level no-op; + // engine versions disagree on whether their load API reloads it. + state.navigation_finished(window, operation, true, uri); + return; + } window->navigation_operation = operation; window->requested_uri = std::move(uri); window->initial_policy = true; window->policy_cancelled = false; window->load_started = false; - webkit_web_view_load_request(window->view, request); + window->fragment_navigation = fragment_navigation; + window->fragment_dispatch_complete = false; + if (fragment_navigation) { + // load_request may replace the document even for a fragment URI. + // Location.assign preserves the native document and still passes + // through the exact host navigation policy above. + completion->operation = operation; + window->fragment_dispatch_operation = operation; + window->fragment_cancel = cancel.release(); + webkit_web_view_evaluate_javascript(window->view, fragment_script.c_str(), + static_cast(fragment_script.size()), nullptr, nullptr, window->fragment_cancel, + fragment_dispatched, completion.release()); + } else webkit_web_view_load_request(window->view, request); }); } @@ -458,6 +553,7 @@ void NILWV_CALL load_html(nilwv_context_v1 *context, std::int64_t id, window->initial_policy = true; window->policy_cancelled = false; window->load_started = false; + window->fragment_navigation = false; webkit_web_view_load_html(window->view, html.c_str(), nullptr); }); } @@ -493,6 +589,27 @@ void NILWV_CALL poll(nilwv_context_v1 *context, std::int64_t id, nilwv_result_v1 if (state.fatal()) break; } state.expire_operations(); + // A fragment navigation has no load-changed finish. Wait for the native + // dispatch callback and exact policy admission as well as a settled + // native URI; URI notification alone could describe a provisional URL. + for (const auto &weak : state.native_windows) { + auto window = weak.lock(); + if (!window || !state.live(window) || window->failed || window->initializing || + !window->fragment_navigation || window->navigation_operation <= 0 || + !window->fragment_dispatch_complete || + window->operation_kind != Operation::navigation || window->operation != window->navigation_operation || + window->initial_policy || window->policy_cancelled || window->load_started || + webkit_web_view_is_loading(window->view)) continue; + std::string uri; + if (!copy_native(webkit_web_view_get_uri(window->view), uri)) { + state.provider_failed(window, "Navigation URL exceeds the provider text bound"); + } else if (uri == window->requested_uri) { + const auto operation = window->navigation_operation; + window->navigation_operation = 0; + window->fragment_navigation = false; + state.navigation_finished(window, operation, true, uri); + } + } state.cancel_failed(); state.poll(id, out); }); diff --git a/native/src/provider_macos.mm b/native/src/provider_macos.mm index 8898e31..88df5b3 100644 --- a/native/src/provider_macos.mm +++ b/native/src/provider_macos.mm @@ -20,6 +20,8 @@ bool bootstrap = true; bool admit_request = false; bool policy_cancelled = false; + bool fragment_navigation = false; + bool fragment_dispatch_complete = false; NSURL *requested_url = nil; }; struct MacContext final : Context { @@ -42,6 +44,7 @@ bool from_ns(NSString *value, std::string &output, std::size_t limit = NILWV_MAX void dispose(const std::shared_ptr &window) { if (!window) return; window->admit_request = false; + window->fragment_navigation = false; [window->view.configuration.userContentController removeScriptMessageHandlerForName:@"nilwebview"]; window->view.navigationDelegate = nil; window->view.UIDelegate = nil; @@ -105,12 +108,13 @@ - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigati state.provider_failed(value, "WebKit navigation URI exceeds the text contract"); return; } state.navigation_requested(value, url); - if (action.targetFrame.isMainFrame && value->navigation) { + if (action.targetFrame.isMainFrame && (value->navigation || value->fragment_navigation)) { // A policy cancellation need not produce a later navigation // delegate error. Complete the owned operation here and clear // its native identity first, so late callbacks cannot finish // a newer application navigation. value->policy_cancelled = true; + value->fragment_navigation = false; value->admit_request = false; value->navigation = nil; const auto operation = value->navigation_operation; @@ -133,10 +137,16 @@ - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigati }); } } +- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { + (void)webView; + nilwebview::macos::callback(context, window, [&](auto &, const auto &value) { + if (value->fragment_navigation || navigation == value->navigation) value->fragment_navigation = false; + }); +} - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { nilwebview::macos::callback(context, window, [&](auto &state, const auto &value) { if (navigation != value->navigation || value->failed) return; - value->admit_request = false; value->navigation = nil; + value->admit_request = false; value->navigation = nil; value->fragment_navigation = false; if (value->bootstrap) { value->bootstrap = false; state.initialized(value); return; } std::string url; if (!nilwebview::macos::from_ns(webView.URL.absoluteString, url)) { @@ -149,7 +159,7 @@ - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigat - (void)failedNavigation:(WKNavigation *)navigation { nilwebview::macos::callback(context, window, [&](auto &state, const auto &value) { if (navigation != value->navigation || value->failed) return; - value->admit_request = false; value->navigation = nil; + value->admit_request = false; value->navigation = nil; value->fragment_navigation = false; if (value->bootstrap) { state.initialization_failed(value, "WebKit initial page failed"); return; } state.navigation_finished(value, value->navigation_operation, false, "", value->policy_cancelled ? "WebKit navigation cancelled by application policy" : "WebKit navigation failed", @@ -290,19 +300,58 @@ void show(nilwv_context_v1 *context, std::int64_t id, nilwv_result_v1 *out) { call(context, out, [&](MacContext &state) { auto value = state.window(id, out); if (!value) return; [std::static_pointer_cast(value)->native_window makeKeyAndOrderFront:nil]; success(out); }); } -void navigate_common(nilwv_context_v1 *context, std::int64_t id, nilwv_text_v1 input, nilwv_result_v1 *out, bool html) { +void navigate_common(nilwv_context_v1 *context, std::int64_t window_id, nilwv_text_v1 input, nilwv_result_v1 *out, bool html) { call(context, out, [&](MacContext &state) { std::string data; if (!state.read_text(input, data, out, html)) return; - auto base = state.window(id, out); if (!base) return; auto value = std::static_pointer_cast(base); + auto base = state.window(window_id, out); if (!base) return; auto value = std::static_pointer_cast(base); NSURL *url = html ? [NSURL URLWithString:@"about:blank"] : [NSURL URLWithString:to_ns(data)]; if (!html && (!navigation_uri(data) || !url || (![url.scheme isEqualToString:@"about"] && !url.host.length))) { state.fail(out, NILWV_E_ARGUMENT, "WebView navigation requires an HTTP(S) URI or about:blank"); return; } + std::string current_uri, requested_uri; + const bool native_uris = !html && from_ns(value->view.URL.absoluteString, current_uri) && + from_ns(url.absoluteString, requested_uri); + const auto fragment = requested_uri.find('#'); + const bool fragment_navigation = native_uris && !value->view.loading && + fragment != std::string::npos && + current_uri.compare(0, current_uri.find('#'), requested_uri, 0, fragment) == 0; + const bool repeated_fragment = fragment_navigation && current_uri == requested_uri; + NSString *fragment_script = fragment_navigation && !repeated_fragment + ? to_ns("window.location.assign(" + json_string(requested_uri) + "); void 0;") : nil; const auto operation = state.start(value, Operation::navigation, out); if (!operation) return; + if (repeated_fragment) { + // Consistent across native engines: an exact settled fragment URI + // completes idempotently without reloading or replacing its DOM. + state.navigation_finished(value, operation, true, requested_uri); + return; + } value->admit_request = true; value->policy_cancelled = false; value->requested_url = url; value->navigation_operation = operation; + value->fragment_navigation = fragment_navigation; + value->fragment_dispatch_complete = false; + if (fragment_navigation) { + // loadRequest can replace this document for fragment URLs. The + // native Location operation preserves it and still visits policy. + value->navigation = nil; + std::weak_ptr weak_context = context->state; std::weak_ptr weak_window = value; + [value->view evaluateJavaScript:fragment_script completionHandler:^(id answer, NSError *error) { + (void)answer; + callback(weak_context, weak_window, [&](auto &owner, const auto &live_window) { + if (live_window->failed || !live_window->fragment_navigation || + live_window->navigation_operation != operation || live_window->operation != operation || + live_window->operation_kind != Operation::navigation) return; + if (error) { + live_window->fragment_navigation = false; live_window->admit_request = false; + live_window->navigation_operation = 0; + owner.navigation_finished(live_window, operation, false, "", + "WebKit same-document navigation dispatch failed"); + } else live_window->fragment_dispatch_complete = true; + }); + }]; + return; + } value->navigation = html ? [value->view loadHTMLString:to_ns(data) baseURL:nil] : [value->view loadRequest:[NSURLRequest requestWithURL:url]]; if (!value->navigation) { - value->admit_request = false; value->navigation_operation = 0; + value->admit_request = false; value->navigation_operation = 0; value->fragment_navigation = false; state.reject(value, operation, out, "WebKit rejected the navigation"); } }); @@ -341,8 +390,25 @@ void poll(nilwv_context_v1 *context, std::int64_t id, nilwv_result_v1 *out) { if (!event && run != kCFRunLoopRunHandledSource) break; } state.expire_operations(); - for (const auto &weak : state.native_windows) if (auto value = weak.lock(); value && value->failed) { - value->admit_request = false; [value->view stopLoading]; + for (const auto &weak : state.native_windows) if (auto value = weak.lock(); value && state.live(value)) { + if (value->failed) { + value->admit_request = false; value->fragment_navigation = false; [value->view stopLoading]; + } else if (value->fragment_navigation && value->fragment_dispatch_complete && value->navigation_operation > 0 && + value->operation_kind == Operation::navigation && value->operation == value->navigation_operation && + !value->bootstrap && !value->admit_request && !value->policy_cancelled && + !value->view.loading && [value->view.URL isEqual:value->requested_url]) { + // Same-document navigation has no public didFinish callback. + // Pair completed native dispatch and exact policy admission + // with a settled native URI, never a provisional URL alone. + std::string uri; + if (!from_ns(value->view.URL.absoluteString, uri)) { + state.provider_failed(value, "WebKit completed URI exceeds the text contract"); + continue; + } + const auto operation = value->navigation_operation; + value->navigation_operation = 0; value->navigation = nil; value->fragment_navigation = false; + state.navigation_finished(value, operation, true, uri); + } } state.poll(id, out); }); diff --git a/native/src/provider_shared.cpp b/native/src/provider_shared.cpp index 36ce729..8f4682f 100644 --- a/native/src/provider_shared.cpp +++ b/native/src/provider_shared.cpp @@ -187,9 +187,11 @@ void Context::reject(const std::shared_ptr &window, std::int64_t id, nil bool Context::matches(const std::shared_ptr &window, std::int64_t id, Operation kind) const noexcept { return live(window) && !window->failed && id > 0 && window->operation == id && window->operation_kind == kind; } -void Context::initialized(const std::shared_ptr &window) { +void Context::initialized(const std::shared_ptr &window, const std::string &detail) { if (!live(window) || window->ready || window->failed) return; - window->ready = true; enqueue(event_for(window, NILWV_EVENT_READY)); + window->ready = true; + auto event = event_for(window, NILWV_EVENT_READY); + event.detail = detail; enqueue(std::move(event)); } void Context::initialization_failed(const std::shared_ptr &window, const std::string &detail) { if (!live(window) || window->ready || window->failed) return; diff --git a/native/src/provider_shared.hpp b/native/src/provider_shared.hpp index 684156e..ca08900 100644 --- a/native/src/provider_shared.hpp +++ b/native/src/provider_shared.hpp @@ -83,7 +83,7 @@ class Context { std::int64_t start(const std::shared_ptr &, Operation, nilwv_result_v1 *); void reject(const std::shared_ptr &, std::int64_t, nilwv_result_v1 *, const std::string &); - void initialized(const std::shared_ptr &); + void initialized(const std::shared_ptr &, const std::string &detail = {}); void initialization_failed(const std::shared_ptr &, const std::string &); void navigation_finished(const std::shared_ptr &, std::int64_t, bool okay, const std::string &url, const std::string &detail = {}, diff --git a/native/src/provider_win32.cpp b/native/src/provider_win32.cpp index 0e08650..3e0b021 100644 --- a/native/src/provider_win32.cpp +++ b/native/src/provider_win32.cpp @@ -1,6 +1,7 @@ // Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT // WebView2 runs on the creating UI STA. Callbacks never enter Matrix/the VM. #include "provider_shared.hpp" +#include "win32_navigation.hpp" #include #include #include @@ -59,6 +60,13 @@ struct Profile { bool await_browser_exit = false; bool browser_resources_released = false; bool retired = false; + bool cleanup_controller_requested = false; + bool cleanup_controller_failed = false; + bool controller_requested = false; + HRESULT environment_status = E_PENDING; + HRESULT monitor_status = E_PENDING; + HRESULT process_status = E_PENDING; + HRESULT controller_status = E_PENDING; void release_monitor() noexcept { if (exit_registered && exit_environment) @@ -120,38 +128,97 @@ bool remove_owned_tree(const std::wstring &path, Clock::time_point until, unsign } bool observe_browser_exit(const std::shared_ptr &profile, ICoreWebView2Environment *environment) noexcept { try { - if (FAILED(environment->QueryInterface(IID_PPV_ARGS(&profile->exit_environment)))) return false; + profile->monitor_status = environment->QueryInterface(IID_PPV_ARGS(&profile->exit_environment)); + if (FAILED(profile->monitor_status)) return false; const std::weak_ptr weak_profile = profile; - const auto result = profile->exit_environment->add_BrowserProcessExited( + profile->monitor_status = profile->exit_environment->add_BrowserProcessExited( Callback( [weak_profile](ICoreWebView2Environment *, ICoreWebView2BrowserProcessExitedEventArgs *) -> HRESULT { if (auto value = weak_profile.lock()) value->browser_resources_released = true; return S_OK; }).Get(), &profile->exit_token); - profile->exit_registered = SUCCEEDED(result); + profile->exit_registered = SUCCEEDED(profile->monitor_status); if (!profile->exit_registered) return false; + profile->await_browser_exit = true; // A context can be closed while environment creation is pending. Even // without a retained controller, inspect only this environment's own // process collection and keep an exact handle if its browser started. + // This early snapshot is optional: controller completion captures the + // mandatory handle before Close. Its absence must neither bypass the + // exit event nor prevent a retired environment from reaching Close. ComPtr process_environment; ComPtr processes; UINT count = 0; - if (FAILED(environment->QueryInterface(IID_PPV_ARGS(&process_environment))) || - FAILED(process_environment->GetProcessInfos(&processes)) || - FAILED(processes->get_Count(&count)) || count > 128) return false; - profile->await_browser_exit = count != 0; + profile->process_status = environment->QueryInterface(IID_PPV_ARGS(&process_environment)); + if (FAILED(profile->process_status)) return true; + profile->process_status = process_environment->GetProcessInfos(&processes); + if (FAILED(profile->process_status)) return true; + if (!processes) { profile->process_status = E_POINTER; return true; } + profile->process_status = processes->get_Count(&count); + if (FAILED(profile->process_status)) return true; + if (count > 128) { profile->process_status = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); return true; } for (UINT index = 0; index < count; ++index) { ComPtr info; COREWEBVIEW2_PROCESS_KIND kind{}; INT32 pid = 0; - if (FAILED(processes->GetValueAtIndex(index, &info)) || - FAILED(info->get_Kind(&kind)) || FAILED(info->get_ProcessId(&pid))) return false; - if (kind == COREWEBVIEW2_PROCESS_KIND_BROWSER && pid > 0 && !profile->browser) + profile->process_status = processes->GetValueAtIndex(index, &info); + if (FAILED(profile->process_status)) return true; + if (!info) { profile->process_status = E_POINTER; return true; } + profile->process_status = info->get_Kind(&kind); + if (FAILED(profile->process_status)) return true; + profile->process_status = info->get_ProcessId(&pid); + if (FAILED(profile->process_status)) return true; + if (kind == COREWEBVIEW2_PROCESS_KIND_BROWSER && pid > 0 && !profile->browser) { profile->browser = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, static_cast(pid)); + if (!profile->browser) { profile->process_status = HRESULT_FROM_WIN32(GetLastError()); return true; } + } } return true; - } catch (...) { return false; } + } catch (...) { + if (profile->exit_registered) profile->process_status = E_UNEXPECTED; + else profile->monitor_status = E_UNEXPECTED; + return profile->exit_registered; + } +} +bool private_environment(const std::shared_ptr &profile, ICoreWebView2Environment *environment) { + ComPtr identified; + WideText actual; + return environment && SUCCEEDED(environment->QueryInterface(IID_PPV_ARGS(&identified))) && + SUCCEEDED(identified->get_UserDataFolder(&actual.value)) && actual.value && + _wcsicmp(actual.value, profile->directory.c_str()) == 0; +} +void close_unretained_controller(const std::shared_ptr &profile, ICoreWebView2Controller *controller) noexcept { + ComPtr view; UINT32 pid = 0; + if (FAILED(controller->get_CoreWebView2(&view)) || !view || + FAILED(view->get_BrowserProcessId(&pid)) || !pid || + (profile->browser && GetProcessId(profile->browser) != pid) || + (!profile->browser && !(profile->browser = OpenProcess( + SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)))) + profile->cleanup_controller_failed = true; + if (FAILED(controller->Close())) profile->cleanup_controller_failed = true; +} +void close_retired_environment(const std::shared_ptr &profile, ICoreWebView2Environment *environment) noexcept { + if (profile->cleanup_controller_requested) return; + profile->cleanup_controller_requested = true; + profile->await_browser_exit = true; + profile->browser_resources_released = false; + try { + if (!private_environment(profile, environment)) { profile->cleanup_controller_failed = true; return; } + const auto completion = std::make_shared(profile); + // An environment completed after its window closed may never have had + // a controller to Close. Finish that native lifecycle invisibly, so the + // same BrowserProcessExited/resource-release gate can still be used. + const auto result = environment->CreateCoreWebView2Controller(HWND_MESSAGE, + Callback( + [profile, completion](HRESULT error, ICoreWebView2Controller *controller) -> HRESULT { + const FinishCompletion finished{completion}; + if (FAILED(error) || !controller) profile->cleanup_controller_failed = true; + if (controller) close_unretained_controller(profile, controller); + return S_OK; + }).Get()); + if (FAILED(result)) { completion->finish(); profile->cleanup_controller_failed = true; } + } catch (...) { profile->cleanup_controller_failed = true; } } std::shared_ptr create_profile() { wchar_t parent[32768]{}; @@ -174,15 +241,19 @@ struct WinWindow final : Window { ComPtr environment; ComPtr controller; ComPtr view; - ComPtr modern; + ComPtr modern; std::shared_ptr profile; ComPtr requested_uri; + std::wstring requested_html_uri; std::wstring script_id; + std::string runtime_detail; std::uint64_t navigation_id = 0; std::int64_t navigation_operation = 0; bool bootstrap = true; bool admit_request = false; + bool admit_document_request = false; bool policy_cancelled = false; + bool fragment_request = false; }; struct WinContext final : Context { bool com_initialized = false; @@ -201,15 +272,20 @@ template void callback(const std::weak_ptr &weak_context, } void dispose(const std::shared_ptr &value) noexcept { if (!value) return; + // Close/DestroyWindow may synchronously complete an aborted initialization. + // Publish retirement first so that callback can drain its private environment. + if (value->profile) value->profile->retired = true; value->admit_request = false; + value->admit_document_request = false; // All registered handlers capture weak state only. Close releases the // controller's handlers; pending completions remain independently safe. if (value->view) value->view->Stop(); if (value->controller) value->controller->Close(); value->modern.Reset(); value->view.Reset(); value->controller.Reset(); value->environment.Reset(); value->requested_uri.Reset(); + value->requested_html_uri.clear(); + value->fragment_request = false; if (value->handle) { DestroyWindow(value->handle); value->handle = nullptr; } - if (value->profile) value->profile->retired = true; value->profile.reset(); } @@ -218,7 +294,7 @@ bool collect_profiles(WinContext &state, Clock::time_point until, unsigned budge for (auto &profile : state.profiles) { if (!profile) continue; complete = false; - if (!profile->retired || profile->pending.load(std::memory_order_acquire)) continue; + if (!profile->retired || profile->pending.load(std::memory_order_acquire) || profile->cleanup_controller_failed) continue; if (profile->await_browser_exit && !profile->browser_resources_released) continue; if (profile->browser && WaitForSingleObject(profile->browser, 0) != WAIT_OBJECT_0) continue; profile->release_monitor(); @@ -267,8 +343,19 @@ void drain_profiles(WinContext &state) noexcept { } if (quit_seen) PostQuitMessage(static_cast(quit_code)); bool retained = false; - for (auto &profile : state.profiles) if (profile) { + for (unsigned slot = 0; slot < state.profiles.size(); ++slot) { + auto &profile = state.profiles[slot]; + if (!profile) continue; retained = true; + const DWORD browser_wait = profile->browser ? WaitForSingleObject(profile->browser, 0) : WAIT_FAILED; + std::fprintf(stderr, "nilwebview: retained profile slot=%u pending=%u retired=%d awaiting_exit=%d " + "resources_released=%d has_browser=%d browser_wait=%lu cleanup_controller=%d cleanup_failed=%d " + "controller_requested=%d environment_hr=%ld monitor_hr=%ld process_hr=%ld controller_hr=%ld\n", + slot, profile->pending.load(std::memory_order_acquire), profile->retired, + profile->await_browser_exit, profile->browser_resources_released, profile->browser != nullptr, + static_cast(browser_wait), profile->cleanup_controller_requested, profile->cleanup_controller_failed, + profile->controller_requested, static_cast(profile->environment_status), static_cast(profile->monitor_status), + static_cast(profile->process_status), static_cast(profile->controller_status)); // Break environment/callback ownership on timeout. Late callbacks hold // independent cancelled profile state and weak context/window handles. profile->release_monitor(); @@ -280,6 +367,9 @@ void drain_profiles(WinContext &state) noexcept { std::fflush(stderr); } } +void fail_initialization(WinContext &state, const std::shared_ptr &value, const char *detail) { + state.initialization_failed(value, detail); dispose(value); +} LRESULT CALLBACK window_proc(HWND handle, UINT message, WPARAM wparam, LPARAM lparam) noexcept { if (message == WM_NCCREATE) { auto create = reinterpret_cast(lparam); @@ -288,7 +378,10 @@ LRESULT CALLBACK window_proc(HWND handle, UINT message, WPARAM wparam, LPARAM lp auto binding = reinterpret_cast(GetWindowLongPtrW(handle, GWLP_USERDATA)); if (binding) { if (message == WM_CLOSE) { - callback(binding->context, binding->window, [](auto &state, const auto &value) { state.close_requested(value); }); + callback(binding->context, binding->window, [](auto &state, const auto &value) { + if (value->bootstrap) fail_initialization(state, value, "WebView2 host window closed during initialization"); + else state.close_requested(value); + }); return 0; } if (message == WM_SIZE) { @@ -329,20 +422,120 @@ HWND create_window(WinWindow &value, const std::wstring &title, int width, int h CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top, nullptr, nullptr, module, &value.binding); } +bool canonical_uri(IUri *uri, std::wstring &output) { + struct AbsoluteUri { + BSTR value = nullptr; + ~AbsoluteUri() { SysFreeString(value); } + } absolute; + if (!uri || FAILED(uri->GetAbsoluteUri(&absolute.value)) || !absolute.value || + SysStringLen(absolute.value) > NILWV_MAX_TEXT_BYTES) return false; + output.assign(absolute.value, SysStringLen(absolute.value)); + return true; +} +bool parse_native_uri(LPCWSTR text, ComPtr &uri) { + if (!text) return false; + std::size_t length = 0; + while (length <= NILWV_MAX_TEXT_BYTES && text[length]) ++length; + return length <= NILWV_MAX_TEXT_BYTES && SUCCEEDED(CreateUri(text, Uri_CREATE_CANONICALIZE, 0, &uri)); +} bool same_uri(IUri *expected, LPCWSTR text) { - ComPtr actual; BOOL equal = FALSE; - return expected && SUCCEEDED(CreateUri(text, Uri_CREATE_CANONICALIZE, 0, &actual)) && - SUCCEEDED(expected->IsEqual(actual.Get(), &equal)) && equal; + ComPtr actual; + std::wstring requested, observed; + // IUri::IsEqual is case-insensitive. Compare canonical strings instead so + // HTTP paths and fragments retain their case-sensitive identity. + return parse_native_uri(text, actual) && + canonical_uri(expected, requested) && canonical_uri(actual.Get(), observed) && requested == observed; } -void fail_initialization(WinContext &state, const std::shared_ptr &value, const char *detail) { - state.initialization_failed(value, detail); dispose(value); +bool same_http_request(IUri *expected, LPCWSTR text) { + ComPtr actual; + std::wstring requested, observed; + if (!parse_native_uri(text, actual) || !canonical_uri(expected, requested) || + !canonical_uri(actual.Get(), observed)) return false; + if (requested.compare(0, 7, L"http://") != 0 && requested.compare(0, 8, L"https://") != 0) return false; + // HTTP requests omit the document fragment; paths and queries remain exact. + if (const auto fragment = requested.find(L'#'); fragment != std::wstring::npos) requested.erase(fragment); + if (const auto fragment = observed.find(L'#'); fragment != std::wstring::npos) observed.erase(fragment); + return requested == observed; +} +bool fragment_only(IUri *requested, LPCWSTR source, bool &repeat) { + repeat = false; + ComPtr current; + std::wstring old_uri, new_uri; + if (!parse_native_uri(source, current) || + !canonical_uri(current.Get(), old_uri) || !canonical_uri(requested, new_uri)) return false; + if (new_uri.find(L'#') == std::wstring::npos || + old_uri.substr(0, old_uri.find(L'#')) != new_uri.substr(0, new_uri.find(L'#'))) return false; + repeat = old_uri == new_uri; + return true; +} +bool pending_fragment(const std::shared_ptr &value) { + return !value->bootstrap && value->ready && !value->closed && !value->failed && value->fragment_request && + value->admit_request && !value->navigation_id && value->navigation_operation > 0 && + value->operation_kind == Operation::navigation && value->operation == value->navigation_operation; +} +void finish_fragment(WinContext &state, const std::shared_ptr &value, LPCWSTR source) { + if (!state.live(value) || !pending_fragment(value) || !same_uri(value->requested_uri.Get(), source)) return; + std::string url; + if (!narrow(source, url)) { + state.provider_failed(value, "WebView2 fragment URI exceeds text contract"); return; + } + const auto operation = value->navigation_operation; + value->admit_request = false; value->fragment_request = false; + value->admit_document_request = false; + value->navigation_operation = 0; + state.navigation_finished(value, operation, true, url, ""); } - bool attach_handlers(const std::shared_ptr &context, const std::shared_ptr &window) { const std::weak_ptr weak_context = context; const std::weak_ptr weak_window = window; EventRegistrationToken token{}; - HRESULT result = window->view->add_NavigationStarting(Callback( + // NavigationStarting cancellation preserves the current document, but + // WebView2 may already send its GET while that callback is running. Gate + // document requests separately before network access. Subresources keep + // their normal browser behavior; this is not a general network sandbox. + ComPtr denied_response; + if (FAILED(window->environment->CreateWebResourceResponse(nullptr, 403, L"Forbidden", + L"Content-Type: text/plain\r\nContent-Length: 0\r\nCache-Control: no-store\r\n", &denied_response)) || !denied_response || + FAILED(window->modern->AddWebResourceRequestedFilterWithRequestSourceKinds(L"*", + COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT, COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL))) return false; + HRESULT result = window->view->add_WebResourceRequested(Callback( + [weak_context, weak_window, denied_response](ICoreWebView2 *sender, ICoreWebView2WebResourceRequestedEventArgs *args) -> HRESULT { + if (!args) return E_POINTER; + bool allowed = false; + callback(weak_context, weak_window, [&](auto &state, const auto &value) { + if (state.fatal() || value->failed || value->bootstrap || !value->ready) return; + ComPtr request; + COREWEBVIEW2_WEB_RESOURCE_CONTEXT resource = COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL; + WideText uri, method; + if (FAILED(args->get_ResourceContext(&resource)) || resource != COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT || + FAILED(args->get_Request(&request)) || !request || FAILED(request->get_Uri(&uri.value)) || + FAILED(request->get_Method(&method.value)) || !uri.value || !method.value) { + state.provider_failed(value, "WebView2 document request metadata unavailable"); return; + } + if (value->admit_document_request && !value->policy_cancelled && + value->navigation_operation > 0 && value->operation_kind == Operation::navigation && + value->operation == value->navigation_operation && !wcsncmp(method.value, L"GET", 4) && + same_http_request(value->requested_uri.Get(), uri.value)) { + // Independent of Starting ordering. Once consumed, a + // redirect or later child request cannot reuse this grant. + value->admit_document_request = false; + allowed = true; + } + }); + if (allowed) return S_OK; + // Keep the immutable local response available even after the weak + // context/window has expired. No late request is admitted by default. + const auto response = args->put_Response(denied_response.Get()); + if (FAILED(response)) { + callback(weak_context, weak_window, [&](auto &state, const auto &value) { + state.provider_failed(value, "WebView2 cannot deny a document request"); + }); + if (sender) sender->Stop(); + } + return response; + }).Get(), &token); + if (FAILED(result)) return false; + result = window->view->add_NavigationStarting(Callback( [weak_context, weak_window](ICoreWebView2 *, ICoreWebView2NavigationStartingEventArgs *args) -> HRESULT { if (!args) return E_POINTER; args->put_Cancel(TRUE); @@ -352,12 +545,33 @@ bool attach_handlers(const std::shared_ptr &context, const std::shar if (FAILED(args->get_Uri(&uri.value)) || FAILED(args->get_IsRedirected(&redirected)) || FAILED(args->get_NavigationId(&id))) { state.provider_failed(value, "WebView2 navigation metadata unavailable"); return; } - if (value->admit_request && !redirected && same_uri(value->requested_uri.Get(), uri.value)) { + // WebView2 may announce its own initial about:blank before + // the asynchronous document-created helper is installed. It + // remains cancelled; only our subsequent NavigateToString is + // authorized. Do not expose an unrecoverable navigation event + // before the consumer has received Ready. + if (value->bootstrap && !redirected && uri.value && !wcscmp(uri.value, L"about:blank")) return; + if (value->bootstrap && !value->admit_request) { + fail_initialization(state, value, "WebView2 requested an unexpected navigation before initialization"); + return; + } + const bool requested = value->admit_request && !redirected && + (value->requested_html_uri.empty() ? same_uri(value->requested_uri.Get(), uri.value) : + uri.value && !wcsncmp(uri.value, value->requested_html_uri.c_str(), value->requested_html_uri.size() + 1)); + if (value->admit_request && !redirected && requested) { value->admit_request = false; value->navigation_id = id; + value->requested_html_uri.clear(); if (FAILED(args->put_Cancel(FALSE))) state.provider_failed(value, "WebView2 cannot authorize navigation"); return; } - if (id == value->navigation_id) value->policy_cancelled = true; + if (value->bootstrap) { + fail_initialization(state, value, "WebView2 initial document did not match its authorized HTML content"); + return; + } + if (id == value->navigation_id) { + value->policy_cancelled = true; + value->admit_document_request = false; + } std::string url; if (!narrow(uri.value, url)) { state.provider_failed(value, "WebView2 requested URI exceeds text contract"); return; } state.navigation_requested(value, url); @@ -365,11 +579,30 @@ bool attach_handlers(const std::shared_ptr &context, const std::shar return S_OK; }).Get(), &token); if (FAILED(result)) return false; + result = window->view->add_SourceChanged(Callback( + [weak_context, weak_window](ICoreWebView2 *sender, ICoreWebView2SourceChangedEventArgs *args) -> HRESULT { + callback(weak_context, weak_window, [&](auto &state, const auto &value) { + if (!pending_fragment(value)) return; + BOOL new_document = TRUE; + WideText raw; + if (!args || FAILED(args->get_IsNewDocument(&new_document)) || + !sender || FAILED(sender->get_Source(&raw.value))) { + state.provider_failed(value, "WebView2 fragment navigation metadata unavailable"); return; + } + if (!new_document) finish_fragment(state, value, raw.value); + }); + return S_OK; + }).Get(), &token); + if (FAILED(result)) return false; result = window->view->add_FrameNavigationStarting(Callback( [weak_context, weak_window](ICoreWebView2 *, ICoreWebView2NavigationStartingEventArgs *args) -> HRESULT { if (!args) return E_POINTER; args->put_Cancel(TRUE); callback(weak_context, weak_window, [&](auto &state, const auto &value) { + if (value->bootstrap) { + fail_initialization(state, value, "WebView2 requested a child-frame navigation during initialization"); + return; + } WideText raw; std::string url; if (FAILED(args->get_Uri(&raw.value)) || !narrow(raw.value, url)) state.provider_failed(value, "WebView2 frame URI unavailable"); else state.navigation_requested(value, url); @@ -386,18 +619,47 @@ bool attach_handlers(const std::shared_ptr &context, const std::shar } if (value->failed || id != value->navigation_id) return; value->admit_request = false; value->navigation_id = 0; + value->admit_document_request = false; + value->fragment_request = false; if (value->bootstrap) { value->bootstrap = false; - if (okay) state.initialized(value); + if (okay) state.initialized(value, value->runtime_detail); else fail_initialization(state, value, "WebView2 initial document failed"); return; } WideText raw; std::string url; - if (okay && (!sender || FAILED(sender->get_Source(&raw.value)) || !narrow(raw.value, url))) { + COREWEBVIEW2_WEB_ERROR_STATUS web_error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN; + int http_status = 0; + if (!okay && !value->policy_cancelled) { + if (FAILED(args->get_WebErrorStatus(&web_error))) { + state.provider_failed(value, "WebView2 navigation error metadata unavailable"); return; + } + ComPtr response; + if (SUCCEEDED(args->QueryInterface(IID_PPV_ARGS(&response)))) { + if (FAILED(response->get_HttpStatusCode(&http_status))) http_status = 0; + } + // WebView2 reports HTTP error documents as unsuccessful. + // A completed 4xx/5xx response with no native transport, + // certificate, cancellation or authentication error is still + // a document the application can inspect. Require the exact + // authorized HTTP(S) document identity as well as its status. + if (http_status >= 400 && http_status <= 599 && + web_error == COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN) { + if (!sender || FAILED(sender->get_Source(&raw.value)) || !raw.value || !narrow(raw.value, url)) { + state.provider_failed(value, "WebView2 HTTP error document URI unavailable"); return; + } + okay = (url.compare(0, 7, "http://") == 0 || url.compare(0, 8, "https://") == 0) && + same_uri(value->requested_uri.Get(), raw.value); + } + } + if (okay && !raw.value && (!sender || FAILED(sender->get_Source(&raw.value)) || !raw.value || !narrow(raw.value, url))) { state.provider_failed(value, "WebView2 completed URI exceeds text contract"); return; } + const std::string detail = value->policy_cancelled ? "WebView2 navigation cancelled by application policy" : + okay ? "" : "WebView2 navigation failed (native=" + std::to_string(static_cast(web_error)) + + ", HTTP=" + std::to_string(http_status) + ")"; state.navigation_finished(value, value->navigation_operation, okay && !value->policy_cancelled, url, - value->policy_cancelled ? "WebView2 navigation cancelled by application policy" : okay ? "" : "WebView2 navigation failed", + detail, value->policy_cancelled ? NILWV_FAILURE_CANCELLED : NILWV_FAILURE_NATIVE); value->navigation_operation = 0; }); @@ -407,6 +669,10 @@ bool attach_handlers(const std::shared_ptr &context, const std::shar result = window->view->add_WebMessageReceived(Callback( [weak_context, weak_window](ICoreWebView2 *, ICoreWebView2WebMessageReceivedEventArgs *args) -> HRESULT { callback(weak_context, weak_window, [&](auto &state, const auto &value) { + if (value->bootstrap) { + fail_initialization(state, value, "WebView2 received a page message during initialization"); + return; + } WideText raw, source; std::string payload; Provenance provenance; if (!args || FAILED(args->TryGetWebMessageAsString(&raw.value)) || !narrow(raw.value, payload)) { state.provider_failed(value, "WebView2 message must be bounded serialized JSON text"); return; @@ -428,6 +694,10 @@ bool attach_handlers(const std::shared_ptr &context, const std::shar if (!args) return E_POINTER; args->put_Handled(TRUE); callback(weak_context, weak_window, [&](auto &state, const auto &value) { + if (value->bootstrap) { + fail_initialization(state, value, "WebView2 requested a new window during initialization"); + return; + } WideText raw; std::string url; if (FAILED(args->get_Uri(&raw.value)) || !narrow(raw.value, url)) state.provider_failed(value, "WebView2 new-window URI unavailable"); else state.navigation_requested(value, url); @@ -450,7 +720,10 @@ bool attach_handlers(const std::shared_ptr &context, const std::shar if (FAILED(result)) return false; result = window->view->add_WindowCloseRequested(Callback( [weak_context, weak_window](ICoreWebView2 *, IUnknown *) -> HRESULT { - callback(weak_context, weak_window, [](auto &state, const auto &value) { state.close_requested(value); }); + callback(weak_context, weak_window, [](auto &state, const auto &value) { + if (value->bootstrap) fail_initialization(state, value, "WebView2 requested closure during initialization"); + else state.close_requested(value); + }); return S_OK; }).Get(), &token); if (FAILED(result)) return false; @@ -495,6 +768,7 @@ void initialize_controller(const std::shared_ptr &context, const std if (window->failed) return; if (FAILED(error) || !id) { fail_initialization(state, window, "WebView2 message helper registration failed"); return; } window->script_id = id; + window->requested_html_uri = wide(html_navigation_uri("")); window->admit_request = true; if (FAILED(CreateUri(L"about:blank", Uri_CREATE_CANONICALIZE, 0, &window->requested_uri)) || FAILED(window->view->NavigateToString(L""))) @@ -579,32 +853,49 @@ void window(nilwv_context_v1 *context, nilwv_text_v1 title, std::int64_t width, Callback( [weak_context, weak_window, profile, completion](HRESULT error, ICoreWebView2Environment *environment) -> HRESULT { const FinishCompletion finished{completion}; + profile->environment_status = error; + // Only an existing owner can initiate work during its drain. + // A callback arriving after the bounded context lifetime must + // not launch a new controller or retain new COM observers. + const auto owner_context = weak_context.lock(); + if (!owner_context || !owner_context->owner_thread()) return S_OK; bool observed = false; if (SUCCEEDED(error) && environment) { observed = observe_browser_exit(profile, environment); if (!observed) profile->await_browser_exit = true; } + bool controller_requested = false; + bool ownership_failed = false; callback(weak_context, weak_window, [&](auto &owner, const auto &live_window) { if (live_window->failed) return; if (FAILED(error) || !environment) { fail_initialization(owner, live_window, "WebView2 environment initialization failed"); return; } - ComPtr identified; - WideText actual; - if (FAILED(environment->QueryInterface(IID_PPV_ARGS(&identified))) || - FAILED(identified->get_UserDataFolder(&actual.value)) || !actual.value || - _wcsicmp(actual.value, profile->directory.c_str()) != 0) { + if (!private_environment(profile, environment)) { + ownership_failed = true; fail_initialization(owner, live_window, "WebView2 did not honor its isolated profile directory"); return; } if (!observed) { fail_initialization(owner, live_window, "WebView2 browser resource lifetime observation unavailable"); return; } + WideText runtime_version; + std::string version; + if (FAILED(environment->get_BrowserVersionString(&runtime_version.value)) || + !runtime_version.value || !narrow(runtime_version.value, version, 128) || version.empty()) { + fail_initialization(owner, live_window, "WebView2 environment runtime version unavailable"); return; + } + // Actual environment identity, independent of the SDK + // loader version and probe's available-runtime check. + live_window->runtime_detail = "WebView2 " + version; live_window->environment = environment; const auto controller_completion = std::make_shared(profile); const bool browser_already_started = profile->await_browser_exit; profile->await_browser_exit = true; + controller_requested = true; + profile->controller_requested = true; const auto creation = environment->CreateCoreWebView2Controller(live_window->handle, Callback( [weak_context, weak_window, profile, controller_completion](HRESULT failure, ICoreWebView2Controller *controller) -> HRESULT { const FinishCompletion finished{controller_completion}; + profile->controller_status = SUCCEEDED(failure) && !controller ? E_POINTER : failure; bool retained = false; callback(weak_context, weak_window, [&](auto &, const auto &ready_window) { if (ready_window->failed) return; @@ -617,21 +908,27 @@ void window(nilwv_context_v1 *context, nilwv_text_v1 title, std::int64_t width, if (auto owner = weak_context.lock()) initialize_controller(owner, ready_window); }); // A closed/destroyed context cannot retain a late controller. - if (!retained && controller) { - ComPtr abandoned; UINT32 pid = 0; - if (!profile->browser && SUCCEEDED(controller->get_CoreWebView2(&abandoned)) && - SUCCEEDED(abandoned->get_BrowserProcessId(&pid)) && pid) - profile->browser = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); - controller->Close(); + if (!retained && controller) close_unretained_controller(profile, controller); + if (!controller && profile->retired && profile->exit_registered) { + // The original HWND may have closed while native + // controller creation was pending. Finish the same + // private environment's lifecycle without that HWND. + const auto owner = weak_context.lock(); + if (owner && owner->owner_thread()) + close_retired_environment(profile, profile->exit_environment.Get()); } return S_OK; }).Get()); if (FAILED(creation)) { + profile->controller_status = creation; controller_completion->finish(); profile->await_browser_exit = browser_already_started; fail_initialization(owner, live_window, "WebView2 controller creation unavailable"); + close_retired_environment(profile, environment); } }); + if (SUCCEEDED(error) && environment && observed && profile->retired && !controller_requested && !ownership_failed) + close_retired_environment(profile, environment); return S_OK; }).Get()); if (FAILED(result)) { @@ -653,11 +950,40 @@ void navigate_common(nilwv_context_v1 *context, std::int64_t id, nilwv_text_v1 i if ((!html && !navigation_uri(data)) || FAILED(CreateUri(html ? L"about:blank" : text.c_str(), Uri_CREATE_CANONICALIZE, 0, &uri))) { state.fail(out, NILWV_E_ARGUMENT, "WebView navigation requires an HTTP(S) URI or about:blank"); return; } + auto html_uri = html ? wide(html_navigation_uri(data)) : std::wstring{}; + bool fragment = false, repeat = false; + std::string repeated_source; + if (!html) { + WideText current; + if (SUCCEEDED(value->view->get_Source(¤t.value))) { + fragment = fragment_only(uri.Get(), current.value, repeat); + if (fragment && repeat && !narrow(current.value, repeated_source)) { + state.fail(out, NILWV_E_NATIVE, "WebView2 repeated fragment source exceeds text contract"); return; + } + } + } const auto operation = state.start(value, Operation::navigation, out); if (!operation) return; + // Repeating the already-current fragment is explicitly idempotent. + // Older WebView2 versions would reload here, while newer versions do + // nothing. Report the observed native Source without queuing a reload + // whose delayed Starting event could escape this operation's lifetime. + if (fragment && repeat) { + state.navigation_finished(value, operation, true, repeated_source, ""); return; + } value->admit_request = true; value->policy_cancelled = false; value->navigation_id = 0; + value->admit_document_request = !html && !fragment && + (data.compare(0, 7, "http://") == 0 || data.compare(0, 8, "https://") == 0); value->requested_uri = uri; value->navigation_operation = operation; + value->requested_html_uri = std::move(html_uri); + value->fragment_request = fragment; const HRESULT result = html ? value->view->NavigateToString(text.c_str()) : value->view->Navigate(text.c_str()); - if (FAILED(result)) { value->admit_request = false; value->navigation_operation = 0; state.reject(value, operation, out, "WebView2 rejected the navigation"); } + if (FAILED(result)) { + value->admit_request = false; value->fragment_request = false; + value->admit_document_request = false; + value->navigation_operation = 0; + value->requested_html_uri.clear(); + state.reject(value, operation, out, "WebView2 rejected the navigation"); + } }); } void navigate(nilwv_context_v1 *context, std::int64_t id, nilwv_text_v1 text, nilwv_result_v1 *out) noexcept { navigate_common(context, id, text, out, false); } @@ -710,6 +1036,7 @@ void poll(nilwv_context_v1 *context, std::int64_t id, nilwv_result_v1 *out) noex state.expire_operations(); for (const auto &weak : state.native_windows) if (auto value = weak.lock(); value && value->failed) { value->admit_request = false; + value->admit_document_request = false; if (value->view) value->view->Stop(); } collect_profiles(state, Clock::now() + std::chrono::milliseconds(2), 256); diff --git a/native/src/win32_navigation.hpp b/native/src/win32_navigation.hpp new file mode 100644 index 0000000..d7733db --- /dev/null +++ b/native/src/win32_navigation.hpp @@ -0,0 +1,29 @@ +// Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT +#pragma once +#include "nilwebview/provider_v1.h" +#include +#include +#include + +namespace nilwebview::win32 { +// NavigateToString reports its UTF-8 HTML as this data URI in +// NavigationStarting; the resulting document's Source is about:blank. +// Generate the exact owned request, never an allowlist for arbitrary data URIs. +inline std::string html_navigation_uri(std::string_view html) { + if (html.size() > NILWV_MAX_TEXT_BYTES) + throw std::length_error("WebView HTML exceeds the text contract"); + constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string uri = "data:text/html;charset=utf-8;base64,"; + uri.reserve(uri.size() + ((html.size() + 2) / 3) * 4); + for (std::size_t offset = 0; offset < html.size(); offset += 3) { + const auto first = static_cast(html[offset]); + const auto second = offset + 1 < html.size() ? static_cast(html[offset + 1]) : 0; + const auto third = offset + 2 < html.size() ? static_cast(html[offset + 2]) : 0; + uri += alphabet[first >> 2]; + uri += alphabet[((first & 3) << 4) | (second >> 4)]; + uri += offset + 1 < html.size() ? alphabet[((second & 15) << 2) | (third >> 6)] : '='; + uri += offset + 2 < html.size() ? alphabet[third & 63] : '='; + } + return uri; +} +} // namespace nilwebview::win32 diff --git a/scripts/ci-build.py b/scripts/ci-build.py index bdd0a59..1328118 100644 --- a/scripts/ci-build.py +++ b/scripts/ci-build.py @@ -24,7 +24,7 @@ 'nil.markup-contract': '392 markup contract checks passed', } PROVIDER_TESTS = { - 'webview.shared': '196 WebView shared checks passed', + 'webview.shared': '209 WebView shared checks passed', 'webview.script-transport': '36 WebView script checks passed', } @@ -128,6 +128,13 @@ def contracts(build: Path, expected: dict[str, str], label: str): elif platform.system() == 'Darwin': command('macos-version', ['sw_vers'], 20) flags = ['-G', 'Ninja', '-DCMAKE_BUILD_TYPE=Release', '-DBUILD_TESTING=ON'] + if platform.system() == 'Windows': + # CMake's compiler probes otherwise use /Zi and can retain an + # mspdbsrv.exe helper after the probe exits. Embed debug info + # in each object instead; try_compile inherits this policy. + # Keep the owned-process cleanup gate unchanged. + flags += ['-DCMAKE_POLICY_DEFAULT_CMP0141=NEW', + '-DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=Embedded'] native = ['-DNIL_ENABLE_LLVM=ON', '-DNIL_BUILD_EXPERIMENTAL_TOOLS=OFF', '-DNILCOMPILER_SQLITE_INCLUDE_DIR=OFF', '-DNILCOMPILER_POSTGRESQL_INCLUDE_DIR=OFF', '-DPython3_EXECUTABLE=' + sys.executable, '-DLLVM_DIR=' + str(args.llvm_dir.resolve()), diff --git a/scripts/ci-linux-browser.sh b/scripts/ci-linux-browser.sh new file mode 100755 index 0000000..f6543cd --- /dev/null +++ b/scripts/ci-linux-browser.sh @@ -0,0 +1,267 @@ +#!/usr/bin/env bash +# Ephemeral hosted-runner setup only. Keep WebKit's bubblewrap sandbox enabled. +# Ubuntu permits user namespaces through per-program AppArmor policy: +# https://documentation.ubuntu.com/security/security-features/privilege-restriction/apparmor/ +# https://manpages.ubuntu.com/manpages/noble/man8/apparmor_parser.8.html +set -euo pipefail +exec python3 -I - "$@" <<'PY' +import fnmatch +import hashlib +import json +import mmap +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import uuid + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2) + '\n', encoding='utf-8') + + +def captured(command, prefix, seconds=20): + # Every command is owned, bounded, and recorded without dumping environment. + with prefix.with_suffix('.stdout').open('xb') as stdout, prefix.with_suffix('.stderr').open('xb') as stderr: + process = subprocess.Popen(command, stdout=stdout, stderr=stderr, start_new_session=True) + try: + code = process.wait(timeout=seconds) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + raise RuntimeError(prefix.name + ' timed out') + require(code == 0, prefix.name + ' failed; see preserved diagnostics') + return prefix.with_suffix('.stdout').read_text(encoding='utf-8') + + +def snapshot(evidence, label): + # Kernel-provided names and attachments, not guessed /etc profile filenames. + helper = r''' +import json +from pathlib import Path +root = Path('/sys/kernel/security/apparmor/policy/profiles') +if not root.is_dir(): raise RuntimeError('AppArmor profile inventory is unavailable') +rows = [] +for item in sorted(root.iterdir()): + if len(rows) >= 4096: raise RuntimeError('AppArmor inventory exceeds bound') + row = {} + for key in ('name', 'attach', 'mode'): + value = (item/key).read_text() + if len(value) > 65536: raise RuntimeError('AppArmor metadata exceeds bound') + row[key] = value.strip() + rows.append(row) +print(json.dumps(rows)) +''' + return json.loads(captured(['sudo', '-n', sys.executable, '-I', '-c', helper], evidence/label)) + + +def profile_text(name, executable): + return ('abi ,\n' + f'profile {name} "{executable}" flags=(unconfined) {{\n' + ' userns,\n' + '}\n') + + +def owned_profile_matches(row, metadata): + # AppArmor can expose an attachment as when only its compiled + # matcher is exported (apparmorfs.c: seq_profile_attach_show). For our own + # fresh --add profile, trust the verified definition and unique name; the + # real namespace probe below verifies that bubblewrap can create its userns. + # This exception never applies to the pre-existing profile conflict check. + return (row['name'] == metadata['name'] and row['mode'] == 'unconfined' and + row['attach'] in (metadata['executable'], '')) + + +def expanded_patterns(pattern): + # AppArmor supports brace alternatives. Conservative matching also treats + # * as spanning /, so an ambiguous existing attachment is refused. + pending = [pattern] + result = [] + while pending: + value = pending.pop() + require(len(pending) + len(result) < 128, 'AppArmor attachment pattern exceeds bound') + match = re.search(r'\{([^{}]+)\}', value) + if match: + pending.extend(value[:match.start()] + item + value[match.end():] + for item in match.group(1).split(',')) + else: + result.append(value) + return result + + +def conflicts(rows, executable): + alternatives = {str(executable)} + if str(executable).startswith('/usr/'): + alternatives.add(str(executable)[4:]) # merged-/usr path spelling + for row in rows: + attachment = row['attach'] + if 'bwrap' in row['name'].lower() and not attachment.startswith('/'): + return True # do not guess an opaque existing attachment + if any(fnmatch.fnmatchcase(path, pattern) for path in alternatives + for pattern in expanded_patterns(attachment)): + return True + return False + + +def webkit_bubblewrap(evidence): + # WebKit may use a private libexec copy. Inspect its installed runtime ELF + # for the compiled BWRAP_EXECUTABLE, never substitute command-v bwrap. + listing = captured(['dpkg-query', '-L', 'libwebkitgtk-6.0-4'], evidence/'webkit-package-files') + libraries = {Path(line).resolve(strict=True) for line in listing.splitlines() + if re.fullmatch(r'/usr/lib/[A-Za-z0-9_./+-]*/libwebkitgtk-6\.0\.so\.[0-9.]+', line)} + require(len(libraries) == 1, 'Expected one installed WebKitGTK6 runtime ELF') + library = libraries.pop() + require(library.stat().st_uid == 0 and 0 < library.stat().st_size < 512*1024*1024, + 'WebKit runtime ELF ownership or size differs') + with library.open('rb') as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: + compiled = {match.group(1).decode('ascii') for match in re.finditer( + rb'(? 128, "processes": []} + for pid in info.pids[:min(info.listed, 128)]: + row = {"pid": int(pid)} + handle = kernel.OpenProcess(0x1000, False, pid) # QUERY_LIMITED_INFORMATION + if not handle: + row["open_error"] = ctypes.get_last_error() + else: + try: + owned = wintypes.BOOL() + if not kernel.IsProcessInJob(handle, self.handle, ctypes.byref(owned)): + row["membership_error"] = ctypes.get_last_error() + elif not owned.value: + row["membership_changed"] = True + else: + buffer = ctypes.create_unicode_buffer(32768) + size = wintypes.DWORD(len(buffer)) + if kernel.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)): + row["image"] = Path(buffer.value).name + else: + row["image_error"] = ctypes.get_last_error() + finally: + kernel.CloseHandle(handle) + report["processes"].append(row) + return report + def terminate(self): require(bool(self.kernel.TerminateJobObject(self.handle, 124)), "cannot terminate owned Windows job") @@ -160,6 +214,11 @@ def run(command: list[str], *, cwd: Path, env: dict[str, str], evidence: Path, active = job.active if job else lambda: group_active(process.pid) row["unexpected_descendants"] = not drain(active, 5) if row["unexpected_descendants"]: + if job: + try: + row["remaining_owned_processes"] = job.members() + except Exception as error: + row["member_diagnostic_error"] = type(error).__name__ problem = AssertionError(label + " left a descendant process after exit") except subprocess.TimeoutExpired: row["timed_out"] = True diff --git a/scripts/test-platform.py b/scripts/test-platform.py index 81543e9..bd7bf44 100644 --- a/scripts/test-platform.py +++ b/scripts/test-platform.py @@ -30,7 +30,7 @@ REPO = Path(__file__).resolve().parents[1] DESKTOP_CASES = ( "configuration", "ready-show", "http-document", "message-immediate", - "message-deferred", "message-provenance", "html-json-unicode-depth", + "message-deferred", "message-provenance", "same-document-navigation", "html-json-unicode-depth", "undefined-null", "script-exception", "script-serialization", "script-async-result", "operation-busy", "redirect-explicit-follow", "http-error-document", "cross-window-routing", "close-stale-copied-events", @@ -218,7 +218,7 @@ def close(self) -> dict: return report -def verify_output(text: str, profile: str) -> dict: +def verify_output(text: str, profile: str, system: str | None = None) -> dict: lines = text.splitlines() if profile == "synthetic": require(lines == ["webview-matrix-contract-ok"], "synthetic route sentinel differs or includes a skip") @@ -230,9 +230,21 @@ def verify_output(text: str, profile: str) -> dict: re.fullmatch(r"webview-desktop-order:immediate:(?:message-first|completion-first)", orders[0]) and re.fullmatch(r"webview-desktop-order:deferred:(?:message-first|completion-first)", orders[1]), "desktop paired-event order inventory differs") - require(lines[-1:] == ["webview-desktop-contract-ok"] and len(lines) == len(DESKTOP_CASES) + 3, + runtimes = [line.removeprefix("webview-desktop-runtime:") for line in lines + if line.startswith("webview-desktop-runtime:")] + if (system or platform.system()) == "Windows": + require(len(runtimes) == 3 and all(len(value) <= 136 and + re.fullmatch(r"WebView2 [0-9]+(?:\.[0-9]+){3}(?: (?:beta|dev|canary))?", value) + for value in runtimes), "actual WebView2 environment versions are missing or malformed") + else: + require(not runtimes, "unexpected WebView2 environment version on this host") + fragments = [line.removeprefix("webview-desktop-fragment:") for line in lines + if line.startswith("webview-desktop-fragment:")] + require(fragments == ["changed", "repeated"], "same-document navigation observations differ") + require(lines[-1:] == ["webview-desktop-contract-ok"] and len(lines) == len(DESKTOP_CASES) + 5 + len(runtimes), "desktop route emitted unexpected output or omitted completion") - return {"checks": len(cases), "cases": cases, "observed_event_order": orders} + return {"checks": len(cases), "cases": cases, "observed_event_order": orders, + "browser_runtime_versions": runtimes, "fragment_navigation": fragments} def route_environment(env: dict[str, str], work: Path, label: str, diff --git a/tests/matrix/desktop_contract.matrix b/tests/matrix/desktop_contract.matrix index 4901b88..9a655f2 100644 --- a/tests/matrix/desktop_contract.matrix +++ b/tests/matrix/desktop_contract.matrix @@ -23,22 +23,36 @@ next-event receives surface as Window, deadline as number returns Event begin pa evaluate panic with "desktop event deadline expired" end paragraph -expect-ready receives surface as Window, deadline as number begin paragraph +expect-ready receives surface as Window, deadline as number, host as text begin paragraph value ready is next-event with surface, deadline expect ready.window.handle equals surface.handle expect ready.sequence is greater than 0 consider ready.kind when EventKind.Ready then expect yes + when EventKind.NavigationRequested then evaluate panic with ("expected Ready; got NavigationRequested: " plus ready.payload-json) + when EventKind.CloseRequested then evaluate panic with "expected Ready; got CloseRequested" + when EventKind.InitializationFailed then evaluate panic with ("initialization failed: " plus ready.detail) + when EventKind.ProviderFailed then evaluate panic with ("provider failed before Ready: " plus ready.detail) when _ then evaluate panic with ("expected Ready: " plus ready.detail) end consider consider ready.operation when Option.None then expect yes when _ then expect no end consider + when host equals "Windows" then + expect (the length of ready.detail) is greater than 0 + say "webview-desktop-runtime:" plus ready.detail + end when end paragraph expect-operation receives notification as Event, operation as Operation begin paragraph expect notification.window.handle equals operation.window.handle + consider notification.kind + when EventKind.NavigationRequested then evaluate panic with ("expected operation completion; got NavigationRequested: " plus notification.payload-json) + when EventKind.ProviderFailed then evaluate panic with ("provider failed during operation: " plus notification.detail) + when EventKind.CloseRequested then evaluate panic with "expected operation completion; got CloseRequested" + when _ then expect yes + end consider value completed is require-some of Operation with notification.operation, "operation event identity" expect completed.id equals operation.id expect completed.window.handle equals operation.window.handle @@ -192,12 +206,14 @@ main returns number begin paragraph evaluate mark with "configuration" value surface is require-ok of Window, text with (create-window with "NIL WebView desktop λ", 640, 480), "create hidden window" - evaluate expect-ready with surface, deadline + evaluate expect-ready with surface, deadline, host expect require-ok of boolean, text with (show-window with surface), "show window" evaluate mark with "ready-show" - value http-operation is require-ok of Operation, text with (navigate with surface, (base plus "/page")), "HTTP navigate" + !!! The initial full document includes a fragment that its HTTP request omits. + value http-operation is require-ok of Operation, text with (navigate with surface, (base plus "/page#initial")), "HTTP navigate" evaluate expect-navigation with surface, http-operation, deadline + evaluate expect-json with surface, "return location.hash;", (quote plus "#initial" plus quote), deadline evaluate expect-json with surface, "return document.getElementById('marker').textContent;", (quote plus "http-ready-λ" plus quote), deadline evaluate mark with "http-document" @@ -209,10 +225,24 @@ main returns number begin paragraph ("{" plus quote plus "order" plus quote plus ":" plus quote plus "deferred" plus quote plus "}"), (quote plus "scheduled" plus quote), deadline, "deferred" evaluate mark with "message-deferred" - evaluate expect-provenance with immediate, capabilities, (base plus "/page"), origin - evaluate expect-provenance with deferred, capabilities, (base plus "/page"), origin + evaluate expect-provenance with immediate, capabilities, (base plus "/page#initial"), origin + evaluate expect-provenance with deferred, capabilities, (base plus "/page#initial"), origin evaluate mark with "message-provenance" + evaluate expect-json with surface, "return window.nilwebviewFragmentMarker = 71;", "71", deadline + value fragment-operation is require-ok of Operation, text with (navigate with surface, (base plus "/page#section")), "same-document fragment navigation" + evaluate expect-navigation with surface, fragment-operation, deadline + evaluate expect-json with surface, "return location.hash;", (quote plus "#section" plus quote), deadline + evaluate expect-json with surface, "return window.nilwebviewFragmentMarker;", "71", deadline + evaluate expect-json with surface, "return document.getElementById('marker').textContent;", (quote plus "http-ready-λ" plus quote), deadline + say "webview-desktop-fragment:changed" + value repeated-fragment is require-ok of Operation, text with (navigate with surface, (base plus "/page#section")), "repeat same-document fragment navigation" + evaluate expect-navigation with surface, repeated-fragment, deadline + evaluate expect-json with surface, "return location.hash;", (quote plus "#section" plus quote), deadline + evaluate expect-json with surface, "return window.nilwebviewFragmentMarker;", "71", deadline + say "webview-desktop-fragment:repeated" + evaluate mark with "same-document-navigation" + value html-operation is require-ok of Operation, text with (load-html with surface, "Matrix λ
embedded λ
"), "HTML load" evaluate expect-navigation with surface, html-operation, deadline @@ -305,7 +335,7 @@ main returns number begin paragraph value second is require-ok of Window, text with (create-window with "NIL second owned window", 320, 240), "second window" expect second.handle does not equal surface.handle - evaluate expect-ready with second, deadline + evaluate expect-ready with second, deadline, host value second-operation is require-ok of Operation, text with (evaluate-function with second, "return 99;"), "second script" value first-quiet is require-ok of PendingEvent, text with (poll-event with surface), "first-window poll" consider first-quiet @@ -322,7 +352,7 @@ main returns number begin paragraph value third is require-ok of Window, text with (create-window with "NIL replacement owned window", 320, 240), "replacement window" expect third.handle does not equal second.handle - evaluate expect-ready with third, deadline + evaluate expect-ready with third, deadline, host expect require-ok of boolean, text with (close-window with third), "close replacement window" !!! Close immediately after creation without pumping or waiting for Ready. !!! Initialization may finish at any time; stale handles must still fail, diff --git a/tests/native/provider_shared_tests.cpp b/tests/native/provider_shared_tests.cpp index d716c49..3636fad 100644 --- a/tests/native/provider_shared_tests.cpp +++ b/tests/native/provider_shared_tests.cpp @@ -1,8 +1,10 @@ // Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT #include "provider_shared.hpp" +#include "win32_navigation.hpp" #include #include #include +#include using namespace nilwebview; namespace { @@ -38,6 +40,23 @@ int main(int argc, char **argv) { << json_string(evaluation_script("/*NILWEBVIEW_BODY*/")) << "}\n"; return 0; } + const std::string html_prefix = "data:text/html;charset=utf-8;base64,"; + const std::pair html_vectors[] = { + {"", ""}, {"f", "Zg=="}, {"fo", "Zm8="}, {"foo", "Zm9v"}, + {"foob", "Zm9vYg=="}, {"fooba", "Zm9vYmE="}, {"foobar", "Zm9vYmFy"}, + {"\xCE\xBB", "zrs="}, {"

\xCE\xBB

", "PHA+zrs8L3A+"}, + {"\xF0\x9F\x98\x80", "8J+YgA=="}, + }; + for (const auto &[html, encoded] : html_vectors) + check(win32::html_navigation_uri(html) == html_prefix + encoded, "owned HTML exact navigation URI"); + const auto largest_html_uri = win32::html_navigation_uri(std::string(NILWV_MAX_TEXT_BYTES, 'x')); + check(largest_html_uri.size() == html_prefix.size() + ((NILWV_MAX_TEXT_BYTES + 2) / 3) * 4 && + largest_html_uri.compare(0, html_prefix.size(), html_prefix) == 0 && + largest_html_uri.substr(largest_html_uri.size() - 4) == "eA==", "owned HTML navigation size boundary"); + bool html_overflow_rejected = false; + try { win32::html_navigation_uri(std::string(NILWV_MAX_TEXT_BYTES + 1, 'x')); } + catch (const std::length_error &) { html_overflow_rejected = true; } + check(html_overflow_rejected, "owned HTML navigation overflow rejected"); for (const auto &value : {"", "plain", "λ", "😀"}) check(utf8(value), "UTF-8 accepted"); for (const auto &value : {std::string("x\0y", 3), std::string("\xc0\x80", 2), std::string("\xed\xa0\x80", 3), std::string("\xf4\x90\x80\x80", 4), std::string("\xc2", 1)}) check(!utf8(value), "UTF-8 rejected"); @@ -61,9 +80,10 @@ int main(int argc, char **argv) { Context context, other; auto out = result(); auto pending = add(context, false); check(!context.window(pending->id, &out) && out.code == NILWV_E_NOT_READY, "pending window not ready"); check(!other.window(pending->id, &out) && out.code == NILWV_E_HANDLE, "foreign window rejected"); - context.initialized(pending); context.initialized(pending); + std::string ready_detail = "owned runtime identity"; + context.initialized(pending, ready_detail); ready_detail.clear(); context.initialized(pending, "duplicate"); const auto ready = event(context, pending->id); - check(number(context, ready, "kind") == NILWV_EVENT_READY, "ready event"); + check(number(context, ready, "kind") == NILWV_EVENT_READY && text(context, ready, "detail") == "owned runtime identity", "ready event owns its diagnostic"); check(number(context, ready, "window") == pending->id, "ready window identity"); context.poll(pending->id, &out); check(out.code == 0 && out.number == 0, "no duplicate ready"); other.event_number(ready, "kind", &out); check(out.code == NILWV_E_HANDLE, "foreign snapshot rejected"); diff --git a/tests/test_platform_harness.py b/tests/test_platform_harness.py index 8775e48..92457af 100644 --- a/tests/test_platform_harness.py +++ b/tests/test_platform_harness.py @@ -19,6 +19,35 @@ SPEC.loader.exec_module(DRIVER) +class RuntimeEvidenceControls(unittest.TestCase): + def output(self, runtimes=()): + lines = ['webview-desktop-case:' + case for case in DRIVER.DESKTOP_CASES] + lines += ['webview-desktop-order:immediate:message-first', + 'webview-desktop-order:deferred:completion-first'] + lines += ['webview-desktop-fragment:changed', 'webview-desktop-fragment:repeated'] + lines += ['webview-desktop-runtime:' + value for value in runtimes] + return '\n'.join(lines + ['webview-desktop-contract-ok']) + '\n' + + def test_windows_requires_actual_environment_versions(self): + versions = ['WebView2 142.0.3595.90', 'WebView2 143.0.3000.2 beta', 'WebView2 144.0.3000.1 dev'] + report = DRIVER.verify_output(self.output(versions), 'desktop', 'Windows') + self.assertEqual(report['browser_runtime_versions'], versions) + for invalid in ([], versions[:2], versions + versions[:1], ['WebView2 SDK 1.0.4314.35'] * 3, + ['WebView2 unknown'] * 3, ['WebView2 142.0.3000.2\nextra'] * 3): + with self.subTest(invalid=invalid), self.assertRaises(AssertionError): + DRIVER.verify_output(self.output(invalid), 'desktop', 'Windows') + + def test_other_hosts_preserve_exact_output_contract(self): + for system in ('Linux', 'Darwin'): + report = DRIVER.verify_output(self.output(), 'desktop', system) + self.assertEqual(report['browser_runtime_versions'], []) + self.assertEqual(report['fragment_navigation'], ['changed', 'repeated']) + with self.assertRaises(AssertionError): + DRIVER.verify_output(self.output().replace('webview-desktop-fragment:changed\n', ''), 'desktop', system) + with self.assertRaises(AssertionError): + DRIVER.verify_output(self.output(['WebView2 142.0.3000.2'] * 3), 'desktop', system) + + class ProfileControls(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory(prefix='nilwebview-harness-control-')