Skip to content

feat(web): save downloads and apply request headers - #76

Merged
houko merged 29 commits into
nsgo-dev:mainfrom
houko:feat/webview-downloads
Nov 14, 2026
Merged

houko merged 29 commits into
nsgo-dev:mainfrom
houko:feat/webview-downloads

Conversation

@houko

@houko houko commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Web views that request a download need to save it under the app-owned downloads directory and report the OnDownload lifecycle consistently across supported backends. Website data also needs an opt-in in-memory mode for private embedded pages, and desktop apps need to serve authenticated app content without opening a local TCP port.

Change

  • handle WebKitGTK download-started, WebView2 DownloadStarting, and Android DownloadListener
  • resolve each download to its originating web view
  • choose an app-owned <id>/<filename> destination
  • report started and terminal download events with URL, path, state, bytes and failure details
  • download Android payloads off the UI thread through a temporary file, then rename on completion
  • cancel downloads when no OnDownload destination is configured
  • cancel and release active downloads when a web view closes on Windows and Linux
  • keep suggested filenames inside the app-owned directory, including .. edge cases
  • add WebView.Headers on Apple, Windows, Linux and Android, sent with the initial URL request only
  • add WebView.Incognito: non-persistent WebKit data on Apple, an ephemeral WebKitGTK network session per view on Linux, in-private WebView2 controller profiles on Windows, and on Android, whose android.webkit has one cookie store and one set of website data per app, no HTTP cache, no DOM storage and no saved form data (cookies, IndexedDB and HTTP authentication stay shared; documented)
  • add Scope.ServeScheme, serving app-owned URL schemes on Apple, Windows and Linux with inferred content types, scoped to the web views under the serving scope
  • allow registered app-owned schemes through restricted web views and document the per-target matrix
  • make the gallery's desktop WebView demo load through its app-owned gallery:// scheme, while retaining inline fallback on unsupported targets
  • allow Apple file: pages, and HTML with a file: base URL, to navigate only within their directory
  • add Env.CanSendInput; macOS reports trusted input support and unsupported backends safely report false
  • add Env.HasWebView, reporting whether the target provides a web view host (false on tvOS)
  • save Android data: downloads by decoding them, and blob: downloads by having the page read the blob, under the name the link's download attribute gives; Android's http(s) re-fetch sends the page's cookies, user agent, a Referer and, on the source's origin, the view's Headers
  • rebuild Android classes.dex and classes.jar with internal/platform/android/runtime/build.sh
  • keep app-owned scheme MIME sniffing in a lightweight driver helper so text-only apps do not link net/http

Trusted input delivery on Windows, Linux and iOS remains unavailable because their native web hosts have no supported trusted-event injection bridge; apps can gate the action with Env.CanSendInput. Remaining gallery coverage is separate follow-up work for issue #33.

Review fixes

  • Windows: create incognito web views through ICoreWebView2Environment10's real vtable slots (CreateCoreWebView2ControllerOptions, CreateCoreWebView2CompositionControllerWithOptions, put_IsInPrivateModeEnabled), and pass the config when the controller is made so an existing environment does not lose Incognito
  • Windows: send Headers only with the initial navigation through NavigateWithWebResourceRequest, rather than intercepting every request of every origin with wrong vtable slots
  • Windows: register app schemes on the WebView2 environment (ICoreWebView2EnvironmentOptions4::SetCustomSchemeRegistrations) so ServeScheme pages load, and stop answering them with Access-Control-Allow-Origin: *
  • driver: bound the HTML and XML MIME signatures by the bytes after leading whitespace, which could slice past a short body and panic
  • core: refuse every scheme WebKit handles itself in ServeScheme (and skip such schemes on Apple), which would end the app on Apple
  • core: keep a served scheme to the scope that serves it, rather than to every web view of every window
  • Linux and Windows: report each download state as a copy, as the engine reads events later and a started report could arrive reading as finished
  • Linux: find a web view by its WebKitWebView rather than by session and window, keep the app's persistent network session for the process's life, release an incognito session with its view, register each scheme once per web context, and finish every app-scheme request, with an error when no view serves it; mounting a web view again no longer panics and closing one no longer breaks another in the same window
  • Linux: make incognito sessions with webkit_network_session_new_ephemeral, as webkit_network_session_new(NULL, NULL) is persistent in WebKit's default directories
  • Linux: cancel and forget a closing web view's downloads, and cancel a download no live view saves instead of reading the closed view
  • Apple: load unrestricted HTML with a file: base URL again, navigating within the base's directory
  • Android: rebuild the runtime, which the incognito change had not been compiled into
  • Android: keep the Blob behind a clicked a[download] link to a blob: URL until the download reads it, so a page that revokes the object URL right after the click (the usual hand-written pattern) still saves the file instead of failing with TypeError: Failed to fetch

Validation

  • go tool nsgo check -target all
  • go tool nsgo test: 1830 passed, 2 failed, 12 skipped; the failures are TestSmallJSON/v2, as the local Go 1.26 toolchain excludes encoding/json/v2, and TestASwipeTurnsTheRing, known failures unrelated to this change
  • GOOS=windows go vet and GOOS=linux go vet of the touched packages
  • go tool nsgo test -target macos in internal/platform/apple, including the new file: base URL test
  • internal/platform/linux built with CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go test -c and run under Xvfb in Debian trixie with GTK 4.18 and WebKitGTK 6.0 2.54: TestWebViewTalksToThePage and the new TestWebViewsOutliveEachOther pass; the new test fails on the previous Linux backend (an unserved scheme never finished, a download kept going after its view unmounted)
  • GOOS=windows GOARCH=amd64 go test -c ./internal/platform/windows (the Windows tests were not run on Windows)
  • classes.dex checked to contain the incognito settings and the blob bridge after the rebuild
  • the Android page scripts (the download-name script and the blob reader) extracted from WebNode.java and run in headless Chromium: without the script, a blob: link revoked in the same task or a 0 ms timeout fails with TypeError: Failed to fetch; with it, both save the bytes under the link's download name and the kept Blob is dropped once read

Real-device checks with a probe app (an Incognito web view loading a local page that fetches subresources and triggers data:, blob: and http downloads, a second web view on an app scheme, ServeScheme("ws") and ServeScheme("javascript"), and the web view unmounted and mounted again):

  • macOS: only the first request carries Headers; the app-scheme page loads and runs; all three downloads save, including a blob: URL revoked right after the click; ws and javascript are refused; everything works again after the remount.
  • Windows 11 (WebView2 157): the Incognito view loads, which the old vtable slots crashed; only the first request carries Headers; the probe:// page loads and runs, so the scheme registration takes; data:, blob: and http downloads save. Several downloads a page starts without a user gesture are held by WebView2's multiple-downloads permission, as in Edge. The new Windows tests (TestWebEnvironmentOptionsRegisterSchemes, TestWebRequestHeadersAreLines, TestWebViewPostsMessagesBothWays, TestWebDownloadFilenameStaysInDownloadDirectory) pass there. The rest of the package fails the same tests on that VM as on main, which has a locked console and no GPU.
  • Linux (Ubuntu 24.04, WebKitGTK 2.52): same results as macOS, and mounting the web view again no longer panics. Ubuntu 24.04's default kernel.apparmor_restrict_unprivileged_userns=1 stops WebKit's bubblewrap sandbox, so any nsgo web view aborts there on main too unless the app is confined by an AppArmor profile; that is outside this PR.
  • Android (Pixel 3 XL): data:, blob: (revoked right after the click) and https downloads save; an Incognito view has no localStorage, so the rebuilt runtime is in use.

Known, not changed here: when a navigation turns into a download, Apple (as on main) and now Windows also report an OnError for the interrupted navigation (Frame load interrupted, The connection was aborted.); Linux does not.

@houko houko changed the title feat(linux): save web view downloads feat(web): save web view downloads on Linux and Windows Nov 14, 2026
@houko houko changed the title feat(web): save web view downloads on Linux and Windows feat(web): save web view downloads on Linux, Windows and Android Nov 14, 2026
@houko
houko force-pushed the feat/webview-downloads branch from 236f418 to a7aabee Compare November 14, 2026 07:08
@houko houko changed the title feat(web): save web view downloads on Linux, Windows and Android feat(web): save downloads and apply request headers Nov 14, 2026
@houko
houko force-pushed the feat/webview-downloads branch 2 times, most recently from 59ac980 to 297915e Compare November 14, 2026 07:29
@houko
houko force-pushed the feat/webview-downloads branch from 653f6b5 to be1ab29 Compare November 14, 2026 14:22
@houko

houko commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

Reviewed and fixed. Head is be1ab29, rebased onto main.

Fixed:

  • Windows Incognito used the wrong ICoreWebView2Environment10 and ControllerOptions vtable slots, which crashed or failed. Every slot is now checked against the WebView2 SDK headers.
  • Windows Headers used wrong slots and were sent to every request of every origin. They now go only with the first navigation, through NavigateWithWebResourceRequest.
  • Windows app schemes were never registered with WebView2. They are now registered through ICoreWebView2EnvironmentOptions4. Access-Control-Allow-Origin: * is gone.
  • Linux:
    • The session bookkeeping is rewritten. Mounting a web view again no longer panics, and closing one web view no longer breaks another.
    • Incognito sessions are really ephemeral.
    • A closing web view's downloads are cancelled.
  • Android:
    • The runtime is rebuilt, so Incognito takes effect.
    • data: and blob: downloads save, including blobs revoked right after the click.
  • WebMIME no longer panics on a short body after leading whitespace.
  • ServeScheme:
    • It refuses schemes WebKit handles itself, such as ws and javascript, which crashed the app on Apple.
    • It is now scoped as documented.
  • Apple loads HTML with a file: base URL again.

Verified on macOS, Windows 11, Ubuntu 24.04 and a Pixel 3 XL with a probe app; details are in the description. go tool nsgo check -target all and go tool nsgo test pass apart from the known flaky tests.

@houko
houko marked this pull request as ready for review November 14, 2026 14:23
houko added 18 commits November 14, 2026 23:58
…slots

ICoreWebView2Environment10 has CreateCoreWebView2ControllerOptions at 20 and CreateCoreWebView2CompositionControllerWithOptions at 22, and ICoreWebView2ControllerOptions has put_IsInPrivateModeEnabled at 6, per WebView2.h: the backend called CreateCoreWebView2ControllerWithOptions to make the options, put_ProfileName to set in-private mode and CreateCoreWebView2ControllerOptions to make the composition controller. A web view now also takes its config when it is made, since an environment that already exists calls back before configure and the controller was made without Incognito.
The backend added `Headers` to every request the view made, subresources and other origins included, through a WebResourceRequested filter on all URLs, so an `Authorization` header reached third parties and later navigations; the filter also read the request's headers and set them through the wrong vtable slots (get_Method and GetIterator rather than get_Headers at 9 and SetHeader at 6). Following the contract and the other backends, a URL source now loads through ICoreWebView2_2::NavigateWithWebResourceRequest with a request from ICoreWebView2Environment2::CreateWebResourceRequest carrying the headers, the interception is gone, and a change of headers loads the page again as on Apple and Linux.
WebView2 raises WebResourceRequested for a custom scheme, and navigates to one, only when the environment registered it through ICoreWebView2EnvironmentOptions4::SetCustomSchemeRegistrations as it was made, and the backend made every environment without options, so no `ServeScheme` page loaded on Windows. The environment now gets a Go ICoreWebView2EnvironmentOptions with ICoreWebView2EnvironmentOptions4, following WebView2EnvironmentOptions.h's defaults, whose registrations are secure schemes with an authority and no other allowed origins. It starts once the batch that made its first web view is applied, registering the schemes of all that batch's web views, and every environment of a profile folder registers the first one's, as WebView2 refuses environments of one folder with different options; a scheme served later cannot load on Windows, which is logged once and documented. Each view filters requests by its schemes rather than all URLs, and responses no longer carry `Access-Control-Allow-Origin: *`, so pages of other origins in the view cannot read app-scheme bodies.
WebMIME checked an HTML or XML signature's length against the whole body rather than what follows its leading whitespace, so a response such as "\n<b" or " <HTML>" sliced past the body's end and panicked on the UI thread. It now matches against the rest after the whitespace, as WHATWG's sniffing does, compares only the BOM of the four-byte UTF-16 patterns rather than two following zero bytes, matches "<?xml" case-sensitively, and takes "<!--" without a tag-terminating byte, per the spec's table.
houko added 11 commits November 14, 2026 23:59
ServeScheme refused only http, https, file, data, blob and about, while WKWebView's setURLSchemeHandler:forURLScheme: raises NSInvalidArgumentException, which ends the app, for every scheme WebKit handles itself (LegacySchemeRegistry::isBuiltinScheme: ws, wss, javascript, ftp, applewebdata, webkit-fake-url and the rest). ServeScheme now refuses that whole set with an error, and Apple's host checks +[WKWebView handlesURLScheme:] before registering a scheme, skipping it with a log, so a later WebKit's own scheme cannot end the app either.
ServeScheme is documented as serving the web views created under its scope, but it wrote one map per runtime, every web view took a copy of all of it, and a restricted owner's sources allowed any scheme served anywhere, so a scheme one subtree or window served reached the web views of every other. The handler now goes in the scope's values, a web view takes the schemes served by its scope and those above, the nearest answering, and a restricted owner loads only the schemes visible from it. Tests check that a sibling subtree and another window see neither the scheme nor its handler.
The Linux and Windows hosts handed the engine a pointer to the download item they keep updating. The engine reads events on its own goroutine, so a started report could arrive reading as finished, and an app saw the end of one download twice and never its start. Each report now carries a copy, as the Apple host's does.
The Linux host kept a set of window handles per network session and released the app's session when the last window using it closed one web view, without forgetting it in webSessions. A web view mounted again then panicked on a nil map inside a GTK callback and used the freed session; with two web views in one window, closing one left the other unable to find itself, so its downloads were cancelled and its app-scheme requests never finished. Scheme requests also carried the session of whichever view registered the scheme first on the shared WebKitWebContext.

The app's persistent session now lives as long as the process, as it did before downloads were added; an Incognito view owns its session and releases it as it closes. Live pages are kept by WebKitWebView, which scheme requests and downloads look up, each scheme is registered once per web context with no session attached, and every scheme request is finished, with a WebKit network error when no live view serves its scheme. A Linux test, run in a process of its own as WebKit keeps the first thread that uses it, mounts web views again in both kinds of session and checks schemes, downloads and an unserved scheme.
webkit_network_session_new(NULL, NULL) makes a persistent session in WebKit's default directories, so an Incognito web view on Linux stored cookies and website data on disk, shared with every other such view. It now makes its session with webkit_network_session_new_ephemeral, available since WebKitGTK 2.40, whose website data manager keeps nothing on disk.
A download whose web view closed before WebKit asked for its destination read the closed view's configuration and panicked in a GLib callback. As on Windows, a closing web view now cancels and forgets the downloads it was saving, holding a reference to each download it follows until then, and the download callbacks cancel a download no live view saves rather than leave it to WebKit's default folder. The Linux web view test now unmounts a view in the middle of a download and checks that the server sees it cancelled.
The main-frame file: check refused every file: navigation of a view whose source was not a file: URL, so unrestricted HTML with a file: base URL, such as WebHTML(html, "file:///Users/me/app/"), which loaded before, was refused. HTML with a file: base URL now navigates within the base's directory, as a file: page does within its own; unrestricted views with other sources leave file: links to WebKit as before, and restricted ones still refuse them.
The commit that made Android's incognito web views turn off the HTTP cache, DOM storage and form saving changed WebNode.java without rebuilding classes.dex and classes.jar, so apps ran the old runtime and Incognito did nothing on Android. Both are rebuilt with build.sh. android.webkit keeps one cookie store and one set of website data per app, so WebView.Incognito's comment and the native views document now say what Android does and does not keep apart.
Android's web view host fetched every download again with java.net.URL, so data: and blob: downloads always failed ("unknown protocol"), and it would have copied a file: URL a page offered as a download. It now decodes data: URLs itself, base64 or percent-encoded, and has the page read a blob: URL, which only its document can, handing the bytes back under a random token through a JavaScript interface; a page that leaves first, or has JavaScript off, fails the download with a message. Both save under the name the link's download attribute gives, which a script run as each page starts notes because android.webkit reports downloads without it, else "download" with the type's extension. Only http(s) downloads are fetched again, now with a Referer as browsers send one by default and the view's Headers when the download is on its source's origin. classes.dex and classes.jar are rebuilt.
… URL

Android's web view read a blob: download by fetching its URL in the page, but only after android.webkit reports the download, which comes after the click returns, and after evaluateJavascript hops back to the renderer. Pages commonly revoke the object URL right after clicking the link (URL.revokeObjectURL in the same task or a short timeout), so the fetch failed with "TypeError: Failed to fetch" and the download was reported failed. The script run as each page starts now remembers which Blob each object URL the page makes stands for, forgetting it when the page revokes the URL, and keeps the Blob when a download link to that URL is clicked; the blob reader takes the kept Blob, dropping it, before falling back to fetching the URL. Object URLs made before that script runs, or in a frame, still go through the fetch. classes.dex and classes.jar are rebuilt.
Rebasing onto main took this branch's classes.dex and classes.jar, which lacked the biometric Java main had compiled in. Rebuilt with build.sh from the merged sources, so the runtime has both the web view changes and biometric authentication.
@houko
houko force-pushed the feat/webview-downloads branch from be1ab29 to 0326f5f Compare November 14, 2026 15:12
@houko
houko merged commit 710fb93 into nsgo-dev:main Nov 14, 2026
@houko
houko deleted the feat/webview-downloads branch November 18, 2026 05:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant