WebAuthn and Passkey Bridge
The WebAuthn and Passkey Bridge is ZikZak InAppWebView’s answer to a hard platform reality: WebKit’s in-page WebAuthn mediation is broken for entitled custom-browser apps on Apple platforms. When a third-party app embeds a WKWebView and a relying party calls navigator.credentials.create() or .get(), the system’s ASCAgent dies with AuthorizationError Code=1 roughly two milliseconds after logging “Allowing request from web browser.” — and no sheet ever appears. This page documents the bridge that routes around that failure: a single-source JavaScript shim that overrides the credentials API, forwards each ceremony over the plugin’s JS-handler channel to a native PasskeyBridge driving ASAuthorizationController, and hands a spec-shaped PublicKeyCredential back to the page. The scope covers the macOS implementation (issue #358, shipped 6.2.2), the iOS port (issue #384), the cross-origin frame fix (issue #446), and the consumer opt-out surface — with precise attention to where the bridge is armed, how it fails safe, and how the two native copies are kept byte-identical.
Why a Bridge Exists at All
Section titled “Why a Bridge Exists at All”The bridge is not a convenience layer — it is a workaround for a documented Apple defect that affects any entitled custom-browser engine. Understanding the failure mode is prerequisite to understanding every design decision that follows, because the bridge’s shape (JS interception, native ASAuthorizationController, window-anchored presentation) is dictated entirely by the need to bypass WKWebView’s own mediation path while still producing a credential the page can consume exactly as if the platform had produced it.
The diagram below shows the two paths a navigator.credentials call can take. The broken native path is what WebKit attempts by default; the bridged path is what the shim installs instead.
flowchart TD RP["Relying Party JS<br/>navigator.credentials.create/get"]:::web RP -->|default WebKit| WK["WKWebView in-page mediation"]:::broken WK --> ASC1["ASCAgent"]:::broken ASC1 --> X["AuthorizationError Code=1<br/>~2ms, no UI"]:::broken RP -->|shim installed| SHIM["PasskeysJS shim<br/>(every frame, atDocumentStart)"]:::bridge SHIM -->|postMessage / callHandler| NATIVE["PasskeyBridge.swift<br/>ASAuthorizationController"]:::bridge NATIVE --> SYS["System sheet<br/>Touch ID / Face ID / security key"]:::ok SYS --> CRED["PublicKeyCredential-shaped object<br/>back to JS"]:::ok classDef web fill:#e3f2fd,stroke:#1565c0; classDef broken fill:#ffebee,stroke:#c62828; classDef bridge fill:#f3e5f5,stroke:#6a1b9a; classDef ok fill:#e8f5e9,stroke:#2e7d32;The critical insight is that the bridged path never trusts the page for origin information. The shim defaults rp.id to location.hostname and the native side derives the signed origin from WKScriptMessage.frameInfo — WebKit’s own view of the frame the message arrived on — never from a value the page supplies. This is what makes a cross-origin iframe ceremony (such as the idmsa.apple.com widget App Store Connect loads) sign the correct origin rather than the relying party’s.
Sources: spec.md, PasskeyCallerContext.swift
The Three-Layer Architecture
Section titled “The Three-Layer Architecture”The bridge is implemented as three cooperating layers plus a single-source generation step. The shim is the page-world half, the native bridge is the platform-world half, and the InAppWebView wiring is the seam that injects one and intercepts the other. A generation script guarantees the shim body is identical across both Apple packages, and a source-contract test enforces that guarantee in CI.
flowchart LR subgraph PI["zikzak_inappwebview_platform_interface"] CANON["passkeys_js_source.dart<br/>CANONICAL shim body"]:::canon end subgraph GEN["scripts/generate_passkeys_shim.sh"] GENF["renders + substitutes<br/>placeholders"]:::gen end subgraph MAC["zikzak_inappwebview_macos"] MSWIFT["PluginScriptsJS/PasskeysJS.swift<br/>GENERATED"]:::gen MBR["PasskeyBridge.swift"]:::native MWI["InAppWebView.swift<br/>inject + intercept"]:::native end subgraph IOS["zikzak_inappwebview_ios"] ISWIFT["PluginScriptsJS/PasskeysJS.swift<br/>GENERATED"]:::gen IBR["PasskeyBridge.swift"]:::native IWI["InAppWebView/InAppWebView.swift<br/>inject + intercept"]:::native end CANON --> GENF GENF --> MSWIFT GENF --> ISWIFT MSWIFT --> MWI MBR --> MWI ISWIFT --> IWI IBR --> IWI classDef canon fill:#fff8e1,stroke:#f57f17; classDef gen fill:#f3e5f5,stroke:#6a1b9a; classDef native fill:#e3f2fd,stroke:#1565c0;The generation step is not optional hygiene — it is a correctness control for a security-critical surface. Because the shim overrides navigator.credentials, any drift between the macOS and iOS copies would mean one platform silently behaves differently from the other. The generator renders both Swift files from the canonical Dart source, substituting two named placeholders ($javascriptBridgeName and __PK_TELEMETRY_ENABLED__) with Swift interpolation, and the iOS source-contract suite extracts all three copies, normalizes the placeholder, and asserts identity.
Sources: passkeys_js_source.dart, generate_passkeys_shim.sh, passkey_bridge_test.dart
The JavaScript Shim: Page-World Interception
Section titled “The JavaScript Shim: Page-World Interception”The shim is an IIFE that installs once per frame (guarded by window.__zikzakPasskeysShimInstalled) and performs four distinct jobs: it overrides the credentials API, it encodes/decodes the binary WebAuthn fields that JSON cannot carry, it rebuilds a spec-shaped credential from the native result, and it exposes the PublicKeyCredential static feature-detection surface that sites gate their UX on.
The binary-field handling is the shim’s most load-bearing detail. WebAuthn transports challenge, user.id, and credential IDs as ArrayBuffers, which JSON.stringify cannot serialize. The shim marks every buffer as {"$b64url": "..."} before crossing the bridge, and the native side decodes it back with its own base64url decoder — because Data(base64Encoded:) rejects the -/_ alphabet and unpadded input that base64url uses.
| Shim responsibility | Mechanism | Why it matters |
|---|---|---|
| API override | navigator.credentials.create/get wrapped; non-publicKey calls fall through to the original |
Password/OTP credentials stay untouched (US-4) |
| Binary transport | ArrayBuffer → {"$b64url": ...} marker; native decodes with custom base64url |
JSON cannot carry buffers; WebKit’s decoder rejects base64url |
| rp.id defaulting | publicKey.rpId || publicKey.rp.id || location.hostname |
Normalizes both registration and authentication option shapes |
| rp.id scope check | Registrable-suffix check → SecurityError before any user gesture |
Spec-mandated rejection of a foreign rp.id |
| Credential rebuild | buildCredential() reconstructs id/rawId/response/getClientExtensionResults() + toJSON() |
RP pages serialize the credential immediately; missing toJSON breaks them |
| AbortSignal | signal.aborted → AbortError; abort event → bridge cancel + reject |
Cancellation cancels the native controller (US-5) |
| Static feature detection | isUserVerifyingPlatformAuthenticatorAvailable, isConditionalMediationAvailable → false, getClientCapabilities |
Sites gate passkey UX on these statics |
The toJSON() reconstruction deserves emphasis: relying parties (idmsa.apple.com above all) serialize the resolved credential immediately via credential.toJSON() or JSON.stringify(credential). A plain object without toJSON makes JSON.stringify emit ArrayBuffer fields as "{}", and a missing toJSON throws where the widget calls it directly — either failure surfaces to the user as the generic “your browser needs to be updated” banner. The shim’s toJSON base64url-encodes every ArrayBuffer to match the PublicKeyCredential.toJSON spec shape.
Sources: passkeys_js_source.dart, passkeys_js_source.dart, passkeys_js_source.dart
The Native Bridge: Platform-World Ceremony Execution
Section titled “The Native Bridge: Platform-World Ceremony Execution”PasskeyBridge.swift is a per-webview NSObject conforming to ASAuthorizationControllerDelegate and ASAuthorizationControllerPresentationContextProviding. It receives the shim’s {method, options} payload, maps the WebAuthn options onto ASAuthorization provider requests, runs the system ceremony anchored to the webview’s window, and serializes the result back into the {"ok": true, "credential": {...}} / {"ok": false, "error": {...}} envelope.
The bridge exposes five methods over the channel, each with a precise contract:
| Method | Purpose | Native behavior |
|---|---|---|
create |
Registration ceremony | Builds platform + (unless pinned) security-key registration requests |
get |
Authentication ceremony | Builds platform + security-key assertion requests |
cancel |
AbortSignal cancellation | ASAuthorizationController.cancel() (macOS 13+) |
isUvPaa |
Platform authenticator availability | Capability probe, not a window/entitlement check |
telemetry |
Fire-and-forget observability | Logs shim diagnostics under the env-var gate |
Option mapping is where WebAuthn semantics meet AuthenticationServices types. The pubKeyCredParams COSE algorithm integers default to ES256 (-7) and RS256 (-257) when the RP omits the list; userVerification maps required/preferred/discouraged to the ASAuthorizationPublicKeyCredentialUserVerificationPreference enum; attestation maps direct/indirect/enterprise/none; and residentKey (macOS 14.4+) maps to the resident-key preference. When authenticatorSelection.authenticatorAttachment is unspecified, both the platform and security-key requests are offered so the system sheet presents the full choice; cross-platform pins security-key, platform pins the platform authenticator.
The following sequence shows a registration ceremony from page call to credential return, including the pre-flight gates that make the bridge fail safe.
sequenceDiagram participant RP as Relying Party JS participant Shim as PasskeysJS shim participant Br as PasskeyBridge participant Sys as ASAuthorizationController RP->>Shim: navigator.credentials.create({publicKey}) Shim->>Shim: default rp.id, check registrable suffix Shim->>Shim: encodeBinary(options) → $b64url markers Shim->>Br: postMessage({method:"create", options}) Br->>Br: parseRpId / parseChallenge / parse user Br->>Br: beginCeremony pre-flight alt headless / no window / ceremony in progress Br-->>Shim: {ok:false, error:{name:"NotAllowedError"}} else armed Br->>Sys: platformRegistrationRequest (+ security-key) Sys->>RP: system sheet (Touch ID) Sys-->>Br: didCompleteWithAuthorization Br->>Br: serializeRegistration (base64url fields) Br-->>Shim: {ok:true, credential:{...}} end Shim->>Shim: buildCredential() + toJSON() Shim-->>RP: PublicKeyCredential-shaped objectThe beginCeremony pre-flight is the single most important safety gate. It enforces three conditions before any user gesture is spent: the webview must not be headless (isHeadlessOffscreen on macOS, a registry lookup on iOS), it must have a window to anchor the sheet to, and no other ceremony may be in flight (a second performRequests would fail with ASAuthorizationError 1004). Every failure resolves as NotAllowedError, preserving the pre-bridge “NONE stance” for headless webviews.
Sources: PasskeyBridge.swift, PasskeyBridge.swift, PasskeyBridge.swift
Arming, Opt-Out, and the Creation-Time Gate
Section titled “Arming, Opt-Out, and the Creation-Time Gate”The bridge is armed at WebView construction behind a two-part gate, and it cannot be toggled afterward — the shim rides the immutable WKWebViewConfiguration. Two settings participate: passkeyBridgeEnabled (default true) withholds both the shim injection and the bridge construction when false, and an explicitly requested webAuthenticationSupport == NONE disarms as well. An unset value stays armed, preserving the always-on 6.2.2 behavior.
The subtlety is in how “explicitly requested NONE” is distinguished from “unset.” On macOS the raw creation-time settings map only carries the webAuthenticationSupport key when the consumer actually set it, so the unset default never disarms. On iOS the native default is 0 (NONE), so the settings class records a separate webAuthenticationSupportExplicitlyRequested flag at parse time to make the same distinction.
| Setting | Default | Effect when armed | Effect when disarmed |
|---|---|---|---|
passkeyBridgeEnabled |
true |
Shim injected + PasskeyBridge constructed |
Neither injected nor constructed; platform mediation retained |
webAuthenticationSupport == NONE (explicit) |
unset | — | Disarms the bridge (same as passkeyBridgeEnabled: false) |
webAuthenticationSupport unset / FOR_APP / FOR_BROWSER |
unset | Armed (6.2.2 default preserved) | — |
A runtime change attempt is surfaced, not dropped silently: because the configuration is immutable after init, setSettings logs a native warning when a disarmed/armed state would change, matching the existing webAuthenticationSupport warning behavior. This creation-time-only constraint is the same reason webAuthenticationSupport itself is inert on Apple platforms — a fact the settings documentation states explicitly and the diagnostics text now repeats honestly rather than pointing integrators at the Associated Domains dead end.
Sources: in_app_webview_settings.dart, InAppWebView.swift, InAppWebViewSettings.swift, passkey_bridge_setting_test.dart
Cross-Origin Frame Correctness (Issue #446)
Section titled “Cross-Origin Frame Correctness (Issue #446)”A WebAuthn ceremony signs the origin of the frame that called navigator.credentials.get/create. When the app-context provider builds a request from a bare challenge, AuthenticationServices derives that origin from the relying-party identifier instead — so an RP used from a cross-origin iframe (Apple’s https://apple.com for the https://idmsa.apple.com iframe) signs the RP origin and the server rejects the assertion. PasskeyCallerContext fixes this by deriving the signed origin from WKScriptMessage.frameInfo, WebKit’s own view of the frame, and mapping it onto ASPublicKeyCredentialClientData (macOS 13.5+, iOS 17.4+).
Two further mechanisms complete the fix. First, the shim prefers the reply-capable WKScriptMessageHandlerWithReply channel (window.webkit.messageHandlers['PasskeyBridge'].postMessage) because the legacy callHandler reply is a main-frame evaluateJavaScript that can never resolve a promise a cross-origin iframe registered — the iframe’s promise hangs until the RP’s own timeout. Second, the native registration of the PasskeyBridge handler must use the addScriptMessageHandler(_:contentWorld:name:) overload exclusively; the plain add(_:contentWorld:name:) overload registers a non-reply handler under which postMessage resolves undefined without ever reaching the reply delegate.
| OS floor | Client-data API | Fallback behavior |
|---|---|---|
| macOS < 13.5 / iOS < 17.4 | ASPublicKeyCredentialClientData unavailable |
App-context request signs the RP origin (the #446 limitation, logged) |
| macOS 13.5+ / iOS 17.4+ | ASPublicKeyCredentialClientData(challenge:origin:topOrigin:crossOrigin:) |
Browser request signs the calling frame’s real origin |
When the caller context is unknown (a file:// or about:blank frame has no security origin), the bridge logs the fallback and builds the app-context request — a nil return is therefore the #446 defect, and it is logged where it happens rather than failing silently.
Sources: PasskeyCallerContext.swift, PasskeyBridge.swift, InAppWebView.swift, passkeys_js_source.dart
Platform Support Matrix
Section titled “Platform Support Matrix”The bridge is an Apple-platform feature; other platforms either expose a real per-WebView WebAuthn toggle (Android) or have no public WebAuthn API to bridge (Linux, Windows, Web). The webAuthenticationSupport setting is the Android path, feature-detected at runtime via WebViewFeature.WEB_AUTHENTICATION and applied through WebSettingsCompat.setWebAuthenticationSupport.
| Platform | Bridge mechanism | webAuthenticationSupport |
Notes |
|---|---|---|---|
| macOS | PasskeyBridge + shim (issue #358) |
Inert — never applied; warns at creation | Gated by host app’s webcredentials entitlement + AASA file |
| iOS | PasskeyBridge + shim (issue #384) |
Inert — never applied; warns at creation | iOS 15.0 floor; per-API availability guards |
| Android | Platform WebView mediation |
Applied via WebSettingsCompat, feature-detected |
getSettings returns null when unsupported |
| Windows | Windows Hello (WebView2) | Ignored | No per-WebView toggle |
| Linux | WebKitGTK | Ignored | No public WebAuthn API |
| Web | — | Ignored | — |
The iOS port carries its own availability story because the package floors at iOS 15.0: the request-building classes and providers run unguarded at the floor, but each over-floor API carries its own guard — ASAuthorizationController.cancel() under iOS 16.0, the platform registration request’s excludedCredentials under iOS 17.4, and the security-key residentKeyPreference under iOS 17.4 — mirroring the macOS 13.0/14.4 numbers.
Sources: in_app_webview_settings.dart, InAppWebView.java, PasskeyBridge.swift
Diagnostics and Observability
Section titled “Diagnostics and Observability”Because Apple’s widget bundle no-ops console.* in production and content-world mismatches swallow console-forwarded lines, the bridge carries its own observability channel that rides the same trusted bridge the ceremonies use. Diagnostics are gated by a single environment-variable check (ZURAFFA_PASSKEY_DEBUG=1 or ZIKZAK_PASSKEY_DEBUG=1) read once at first use — the shim interpolates this static into var telemetryEnabled = ... at generation time, so the page-side telemetry exists only under the same gate as the native prints. The default is off: a release app must not log credential metadata or RP request/response bodies.
When enabled, the shim installs a fetch/XHR wrapper that logs the RP’s authentication round-trip (URL, method, body head, response status and body head) from inside the frame — the only reliable vantage for subframe traffic that the app’s network capture and CDP do not mirror. This turns a silent server-side rejection (“Can’t verify your account”) into an attributable endpoint + payload + status, and distinguishes a client-side serialization failure from a server rejection.
Sources: PasskeyBridge.swift, passkeys_js_source.dart, passkeys_js_source.dart
Testing and Verification Posture
Section titled “Testing and Verification Posture”The Apple package suites are source-contract tests: because the test runners cannot compile Swift, they read the .swift sources as text and assert on their shape, while the compile gate is flutter build macos --debug / flutter build ios --release --no-codesign in the example app (mirroring CI’s build-macos / build-ios jobs). The suites pin the bridge contract (imports, providers, entry points, enum mappings), the InAppWebView wiring, the no-drift guarantee across all three shim copies, and the passkeyBridgeEnabled setting round-trip.
Ceremony acceptance itself is device-gated: a real registration/authentication on an entitled build requires a physical device with Face/Touch ID and the webcredentials entitlement. That acceptance is recorded as app-side verification debt (the same posture spec 015 took — plugin evidence is the source-contract suite plus compile gate; ceremony evidence is the app side), with the known gotchas (stale ASCAgent, late-availability manager APIs) carried forward.
Sources: passkey_bridge_test.dart, passkey_bridge_test.dart, spec.md
Consuming the Bridge
Section titled “Consuming the Bridge”For an integrator, using the bridge requires no special API — a standard InAppWebView with JavaScript enabled is sufficient, because the shim arms by default. The example app demonstrates the full loop: it loads a WebAuthn test page, listens to a passkeyEvent JS handler the page fires on every step, and surfaces the same verdict the page shows (which matters on macOS, where the OS refuses the ceremony before any sheet appears and the only signal is the DOMException the page catches). To opt out entirely — for automation hosts or lean embeds that want zero interception — set passkeyBridgeEnabled: false in InAppWebViewSettings.
Sources: passkey_example.screen.dart, passkey_example.screen.dart
Where to Go Next
Section titled “Where to Go Next”The bridge sits at the intersection of the settings surface and the Apple native layer. To understand the contract seam the shim source lives behind, read The Platform Interface: The Contract Seam. For the native ASAuthorizationController and WKScriptMessageHandlerWithReply wiring in depth, continue to Apple Native Layer (Swift and Swift Package Manager). The code-generation discipline that keeps the two shims identical is covered in Zorphy Entity Model Layer and Code Generation, and the source-contract testing posture is detailed in Testing Strategy and Per-Package Commands. For the distinct WebAuthenticationSession API (a standalone browser-session flow, not the in-page bridge), see Cookies, Web Storage, and Credential Management.