Network Capture, Interception, and Secret Redaction
The Network Capture API turns an opaque live web session into structured, queryable intelligence. It intercepts a page’s own XMLHttpRequest and fetch() traffic, correlates each request with its response and body, and delivers the result through per-event callbacks and a bulk-accumulating collector — all while redacting auth-shaped secrets at the source before any consumer observes them. The engine is deliberately pure Dart + JavaScript injection, so it behaves identically on Android, iOS, macOS, and headless WebViews without any per-platform native code. This page documents the architecture, the event lifecycle, the configuration surface, the redaction ruleset, and the per-domain budgeting that make the capture mission-grade.
Sources: network_capture_manager.dart, spec.md
Architectural Overview: A Three-Part Pure-Dart Engine
Section titled “Architectural Overview: A Three-Part Pure-Dart Engine”The subsystem is composed of three cooperating source files in the main package, sitting atop data types defined in the platform interface. The manager is the Dart-side lifecycle owner, the interceptor JS is the injected script that monkey-patches the page’s networking primitives, and the secret redactor is the source-level ruleset applied to every event before it fans out. The data types (NetworkCaptureController, NetworkRequest, NetworkResponse, NetworkResponseBody, NetworkEntry) live in the platform interface so both the engine and any consumer package can reference them without a circular dependency.
graph TD subgraph Page["Injected Page Context (all frames, document-start)"] JS["networkCaptureInterceptorJs<br/>monkey-patches fetch + XHR"] BUF["In-page queue (max 500)<br/>optimistic send + flush"] end subgraph Dart["Dart Engine (main package)"] MGR["NetworkCaptureManager<br/>handler wiring, dedup, routing"] RED["secret_redactor<br/>redactRequest / Response / Body"] end subgraph Types["Platform Interface Types"] COL["NetworkCaptureController<br/>accumulates NetworkEntry"] CB["onNetworkRequest / Response / LoadingFinished"] end JS --> BUF BUF -->|"__zikzakNetworkCapture__ handler"| MGR MGR --> RED RED --> COL RED --> CBThe manager’s own documentation states the three responsibilities precisely: it builds the interceptor UserScript injected at document start in all frames, registers the __zikzakNetworkCapture__ JavaScript handler when the WebView is created (flushing events the page buffered before the handler was ready), and routes captured events to the user’s callbacks and to the collector. Because the substrate is injection rather than native hooks, the same code path serves visible and headless WebViews alike.
Sources: network_capture_manager.dart, network_capture_interceptor_js.dart
The JavaScript Interceptor: Monkey-Patching fetch and XHR
Section titled “The JavaScript Interceptor: Monkey-Patching fetch and XHR”The injected script is a self-contained IIFE guarded by an idempotency flag so it never double-installs. It captures the original window.fetch, XMLHttpRequest.prototype.open, send, and setRequestHeader, wraps them, and reports structured events through the window.zikzak_inappwebview.callHandler('__zikzakNetworkCapture__', payload) bridge. The configuration object (body-size cap, capture toggles, URL/resource/MIME filters) is injected by replacing an @@CONFIG@@ placeholder with JSON at build time, so the same template serves every configuration.
The interceptor’s central design tension is timing: events can fire before the Dart handler is registered. It resolves this with an optimistic-send-plus-queue strategy. Every event is stamped with a pageId and a monotonically increasing seq, then optimistically sent; it is also pushed onto an in-page queue capped at 500 entries. When the Dart side calls window.__zikzakNetworkCapture__.ready(), the queue is drained and re-sent. This produces duplicate deliveries that the Dart side deduplicates by pageId:seq, guaranteeing no event is lost during the pre-ready window without leaking memory.
Sources: network_capture_interceptor_js.dart
Body serialization is deliberately defensive. Synchronous bodies (strings, URLSearchParams, FormData, ArrayBuffer) are serialized inline, while Blob bodies trigger asynchronous reads. Binary bodies are represented as short textual descriptions unless binary capture is explicitly enabled, in which case they are base64-encoded in 0x8000-byte chunks to avoid call-stack overflow. Textual bodies over the configured maximum are truncated with a ... [truncated, total: N chars] suffix. Response bodies are only read when the MIME type passes the textual- MIME allowlist and the configured MIME filter, and response.clone() is used so the page’s own consumption is never disturbed.
Sources: network_capture_interceptor_js.dart, network_capture_interceptor_js.dart
The following table summarizes the four event kinds the interceptor emits and their triggering conditions:
| Event kind | Trigger | Key payload fields |
|---|---|---|
request |
fetch() called or xhr.send() invoked, when capture is enabled for the URL/type |
requestId, url, method, headers, body, bodyIsBinary, resourceType, timestamp |
response |
fetch promise resolves / XHR load fires |
requestId, statusCode, statusText, headers, mimeType, duration, fromCache |
body |
response body fully read and MIME/type filters pass | requestId, body, isBase64, size, truncated, mimeType |
error |
fetch rejects / XHR error/abort/timeout |
requestId, url, error message |
Sources: network_capture_interceptor_js.dart, network_capture_interceptor_js.dart
The Manager Lifecycle: Attach, Flush, Deduplicate, Route
Section titled “The Manager Lifecycle: Attach, Flush, Deduplicate, Route”The NetworkCaptureManager is created conditionally via maybeCreate, which returns null unless capture is enabled — either explicitly through useNetworkCapture == true, or implicitly when the setting is null and a collector or any network callback is present. This “infer-enabled” rule means a developer who simply passes an onNetworkRequest callback gets capture without extra ceremony. The manager is associated with a controller through an Expando registry keyed on both the controller and its platform, so NetworkCaptureManager.of(controller) resolves the active manager and the controller’s networkCaptureController getter exposes its collector.
Lifecycle wiring is identical for the visible and headless widgets. The interceptor is merged into initialUserScripts at construction, attach() runs from onWebViewCreated to register the JS handler and flush the pre-ready queue, and onPageLoad() re-flushes on both onLoadStart and onLoadStop so events fired at the very start of a navigation (before the new document’s bridge is reachable) are still delivered.
sequenceDiagram participant Page participant I as Interceptor JS participant M as Manager participant R as Redactor participant C as Collector / Callbacks Page->>I: fetch()/xhr.send() I->>M: callHandler (optimistic, may fail pre-ready) I-->>I: queue event (pageId:seq) Note over M: onWebViewCreated → attach() M->>I: evaluate ready() → drain queue I->>M: re-sent events M->>M: dedup by pageId:seq (LRU 2000) M->>R: redactRequest/Response/Body R->>C: trackRequest / attachResponse / attachBody R->>C: onNetworkRequest / Response / LoadingFinishedOn receipt, _onJavaScriptEvent first deduplicates by pageId:seq using a bounded LRU set (2000 entries) that removes the oldest key when full, then switches on the event kind. Each branch deserializes the payload via the type’s fromMap, passes it through the corresponding redactor, and forwards it to both the collector and the user callback — ensuring the collector and raw callbacks always see the same redacted object.
Sources: network_capture_manager.dart, network_capture_manager.dart, in_app_webview.dart, headless_in_app_webview.dart
Secret Redaction at the Source
Section titled “Secret Redaction at the Source”Redaction is the non-negotiable security guarantee: captured live traffic routinely carries bearer tokens and session cookies, and leaking them into callbacks, the collector, or downstream distillation would be a severe defect. The secret_redactor.dart module enforces this before any consumer observes the event, replacing sensitive values with the marker <redacted>. It targets two categories. Headers whose names match authorization, proxy-authorization, cookie, or set-cookie are always redacted because they carry auth-shaped secrets. Query/body parameters named api_key, apikey, password, passwd, secret, token, access_token, refresh_token, or client_secret are redacted wherever they appear — in the URL query string and in application/x-www-form-urlencoded bodies — while non-secret params are preserved intact.
graph LR RAW["Raw NetworkRequest<br/>Authorization, Cookie,<br/>api_key, password"] --> RU["redactRequest"] RAW2["Raw NetworkResponse<br/>Set-Cookie"] --> RR["redactResponse"] RAW3["Raw NetworkResponseBody"] --> RB["redactBody<br/>(pass-through today)"] RU -->|"headers + url + body"| SAFE["Redacted event<br/>values = <redacted>"] RR -->|"headers"| SAFE RB --> SAFEThe redactor rebuilds each object rather than mutating in place: redactRequest produces a new NetworkRequest with redacted URL, headers, and form body; redactResponse produces a new NetworkResponse with redacted headers (including Set-Cookie); and redactBody is currently an intentional pass-through, with body-content redaction of auth params noted as a separate behavior. Because redaction happens inside the manager’s routing loop before both collector.trackRequest and _onNetworkRequest?.call, every tier — raw callbacks, getEntries(), and any downstream consumer — receives the redacted form uniformly.
Sources: secret_redactor.dart, network_capture_manager.dart
The redaction behavior is locked by a dedicated test suite that plants known tokens in headers, cookies, URL params, and body params, then asserts the raw values are absent and the marker is present across the request — confirming that non-secret headers and params (X-Other, scope) survive untouched.
Sources: network_capture_redaction_test.dart
The Collector: Correlation, Filtering, and Per-Domain Budgets
Section titled “The Collector: Correlation, Filtering, and Per-Domain Budgets”The NetworkCaptureController accumulates a graph of NetworkEntry objects, each correlating a request with its optional response, body, and error. Its central challenge is out-of-order arrival: because request bodies are serialized asynchronously, a response or body event can reach Dart before its request. The collector handles this with pending maps (_pendingResponses, _pendingBodies, _pendingErrors) keyed by requestId; when the request finally arrives via trackRequest, any pending fragments are drained into the new entry. This makes the collector robust to the concurrency inherent in the injection-based engine.
graph TD REQ["trackRequest(request)"] --> NEW["create NetworkEntry<br/>drain pending fragments"] RESP["attachResponse"] -->|entry exists| SETR["entry.response = ..."] RESP -->|not yet| PR["buffer in _pendingResponses"] BODY["attachBody"] -->|entry exists| SETB["budget check + entry.responseBody"] BODY -->|not yet| PB["buffer in _pendingBodies"] ERR["attachError"] -->|entry exists| SETE["entry.error = ..."] ERR -->|not yet| PE["buffer in _pendingErrors"]For bulk retrieval the collector exposes getEntries() with AND-combined, case-insensitive substring filters on URL, MIME type, resource type, and body presence; getBodies() is a convenience that returns only captured bodies; and waitForIdle() polls lastActivity until the network has been quiet for a configurable duration or throws a TimeoutException. clear() resets all state for the next navigation.
Per-domain budgets enforce resource bounds independently of any downstream caps. domainBudgets maps an exact host to a DomainBudget of maxEntries, maxBytes, and maxBodySize. When a request arrives for an over-budget domain, trackRequest silently drops it while other domains continue capturing normally; attachBody truncates a body to the per-domain maxBodySize and drops it entirely once the domain’s cumulative retained bytes cross maxBytes. This keeps a chatty or long-lived session from exhausting memory on a single host.
Sources: network_capture_controller.dart, network_capture_controller.dart, network_entry.dart
Configuration Surface
Section titled “Configuration Surface”Capture is configured entirely through InAppWebViewSettings, which the manager reads when building the interceptor config. The networkCapture controller reference is deliberately excluded from serialization (includeFromJson: false), since it is a live Dart object rather than a wire value.
| Setting | Default | Effect |
|---|---|---|
useNetworkCapture |
false (inferred true if callbacks/collector set) |
Master enable switch |
networkCapture |
null |
Collector instance; setting it enables capture |
networkCaptureMaxBodySize |
50000 |
Character cap before truncation |
networkCaptureBodies |
true |
Capture response bodies at all |
networkCaptureBinaryBodies |
false |
Base64-encode binary bodies |
networkCaptureUrlPatterns |
[] (capture all) |
URL filter (substring or regex) |
networkCaptureUrlPatternType |
UrlPatternType.substring |
How URL patterns are interpreted |
networkCaptureResourceTypes |
[xhr, fetch] |
Resource types to capture |
networkCaptureMimeTypes |
[] (all bodies) |
MIME filter for body capture |
Sources: in_app_webview_settings.dart, network_capture_manager.dart
A canonical usage flow is to pass a NetworkCaptureController into the settings, let the page run, then query it after load:
final captureController = NetworkCaptureController();
InAppWebView( initialSettings: InAppWebViewSettings(networkCapture: captureController), initialUrlRequest: URLRequest(url: WebUri('https://retailer.example')),);
// after load:final entries = await captureController.getEntries( urlPatterns: ['api'], mimeTypes: ['application/json'],);captureController.clear(); // before the next navigationSources: network_capture_controller.dart
Relationship to the Recipe Recorder and Session Recording
Section titled “Relationship to the Recipe Recorder and Session Recording”The capture pipeline is a shared substrate: the recipe recorder forwards from the same event stream to detect signals. Its onNetworkRequest matches request URLs against a step’s signalPatterns and records a RecordedSignal, while onNetworkResponse backfills the status code onto the matching signal — and its architecture explicitly mirrors NetworkCaptureManager (a maybeCreate builder plus a mergeUserScripts helper). This means the same redacted, deduplicated event flow that feeds the collector also feeds session recording, so recorded recipes inherit the source-level secret redaction automatically. For the recording/replay layer built on top of these signals, see Session Recording and Replay (Recipes); for the bulk cassette-and-pool layer that consumes captured traffic, see VCR Cassettes and the WebView Pool.
Sources: recipe_recorder.dart, recipe_recorder.dart
Scope Boundaries and Non-Goals
Section titled “Scope Boundaries and Non-Goals”The current engine has deliberate, documented limits that advanced developers should account for. Because it is JavaScript-injection based, it can only observe ResourceType.xhr and ResourceType.fetch — not document, image, or stylesheet loads. fromCache is a best-effort heuristic derived from PerformanceResourceTiming, and fromServiceWorker is always false because service-worker traffic is not observable from injected page script. The broader mission-grade spec (distillation via getSightings(), streaming with stopOn early-return, salvage flush on cancellation, and SSO/auth-flow body-dropping) describes the target contract; the verified, implemented surface documented here is the injection engine, the collector with per-domain budgets, and source-level header/param redaction. Configuration of the WebView and controller that host this engine is covered in InAppWebView Widget and InAppWebViewController, and the headless variant in Headless WebView and the Live-Instance Cap.