This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-wkwebview-session-isolation-standard

Capacitor 7 WKWebView Process Pool & Cookie Jar Partitioning Standard

Enforces strict cookie jar partitioning and process pool isolation in Capacitor 7 iOS runtimes. Prevents cross-origin authentication bleed, session fixation, and credential leakage between embedded third-party OAuth flows and core application runtimes by prohibiting shared WKWebsiteDataStore configurations and mandate-driven ephemeral authentication sessions.

Prohibited Anti-Pattern: Executing Third-Party OAuth via Shared Process Pool WKWebView or Unpartitioned In-App Frames

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 WKWebView Process Pool & Cookie Jar Partitioning Standard - Enforces strict cookie jar partitioning and process pool isolation in Capacitor 7 iOS runtimes. Prevents cross-origin authentication bleed, session fixation, and credential leakage between embedded third-party OAuth flows and core application runtimes by prohibiting shared WKWebsiteDataStore configurations and mandate-driven ephemeral authentication sessions.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-wkwebview-session-isolation-standard"
---

# Capacitor 7 WKWebView Process Pool & Cookie Jar Partitioning Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing Third-Party OAuth via Shared Process Pool WKWebView or Unpartitioned In-App Frames

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 WKWebView Shared Process Pool Session Isolation. Mandate isolated authentication lifecycles, eliminate cross-origin cookie bleed in iOS WKWebView instances, and ensure all OAuth2/OIDC exchanges utilize ephemeral native contexts (ASWebAuthenticationSession) rather than shared WKProcessPool web views.

## Strict Guidelines
- Engineers MUST ALWAYS isolate third-party authentication flows using ASWebAuthenticationSession or SFSafariViewController rather than an in-app WKWebView sharing the default WKProcessPool.
- Engineers MUST NOT navigate the primary Capacitor WKWebView to external identity provider URLs (e.g., Auth0, Okta, Google Identity) directly via window.location.href or inline iframe elements.
- Services handling authentication MUST configure prefersEphemeralWebBrowserSession: true when invoking native OAuth flows to ensure cookies are not retained in Safari's shared container.
- Capacitor iOS plugins instantiating auxiliary WKWebView instances MUST assign WKWebsiteDataStore.nonPersistent() or a custom partitioned WKWebsiteDataStore instead of WKWebsiteDataStore.default().
- Components NEVER store sensitive JWT tokens or refresh tokens in document.cookie or localStorage where bridge-level WKWebView persistence can be inspected or extracted via cross-origin web views.

## Bad vs Good Implementations
### Third-Party OAuth Initiation via Capacitor Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Navigating the core WKWebView directly to an IdP leaks core app origin cookies, pollutes the default WKWebsiteDataStore with third-party tracking identifiers, and exposes the app origin to external redirects.
```typescript
import { Capacitor } from '@capacitor/core';

export async function initiateOAuthLogin(authUrl: string): Promise<void> {
  // CRITICAL SECURITY VIOLATION: Direct navigation inside Capacitor's primary WKWebView
  // bleeds app session cookies to third-party domains and pollutes WKProcessPool.
  if (Capacitor.isNativePlatform()) {
    window.location.href = authUrl;
  } else {
    window.open(authUrl, '_blank');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates authentication to an isolated browser controller (`@capacitor/browser`), preventing cross-origin cookie bleed and process pool contamination in Capacitor's primary WKWebView runtime.
```typescript
import { Browser } from '@capacitor/browser';
import { App } from '@capacitor/app';

interface OAuthResult {
  code: string;
  state: string;
}

export async function initiateOAuthLogin(authUrl: string, expectedState: string): Promise<OAuthResult> {
  return new Promise((resolve, reject) => {
    let appListenerHandle: { remove: () => Promise<void> } | null = null;

    const cleanup = async () => {
      if (appListenerHandle) {
        await appListenerHandle.remove();
      }
      await Browser.close().catch(() => {});
    };

    App.addListener('appUrlOpen', async (event) => {
      if (event.url.startsWith('myapp://oauth/callback')) {
        await cleanup();
        const parsed = new URL(event.url);
        const state = parsed.searchParams.get('state');
        const code = parsed.searchParams.get('code');

        if (state !== expectedState || !code) {
          reject(new Error('Invalid OAuth state or missing code.'));
          return;
        }
        resolve({ code, state });
      }
    }).then((handle) => {
      appListenerHandle = handle;
    });

    // Opens ASWebAuthenticationSession / SFSafariViewController without shared WKProcessPool state
    Browser.open({
      url: authUrl,
      windowName: '_blank',
      presentationStyle: 'popover'
    }).catch((err) => {
      cleanup();
      reject(err);
    });
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 WKWebView Process Pool & Cookie Jar Partitioning Standard

Capacitor 7 WKWebView Process Pool & Cookie Jar Partitioning Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cookie jar partitioning and process pool isolation in Capacitor 7 iOS runtimes. Prevents cross-origin authentication bleed, session fixation, and credential leakage between embedded third-party OAuth flows and core application runtimes by prohibiting shared WKWebsiteDataStore configurations and mandate-driven ephemeral authentication sessions. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Executing Third-Party OAuth via Shared Process Pool WKWebView or Unpartitioned In-App Frames Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftExecuting Third-Party OAuth via Shared Process Pool WKWebView or Unpartitioned In-App FramesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS isolate third-party authentication flows using ASWebAuthenticationSession or SFSafariViewController rather than an in-app WKWebView sharing the default WKProcessPool.

Engineers MUST ALWAYS isolate third-party authentication flows using ASWebAuthenticationSession or SFSafariViewController rather than an in-app WKWebView sharing the default WKProcessPool.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT navigate the primary Capacitor WKWebView to external identity provider URLs (e.g., Auth0, Okta, Google Identity) directly via window.location.href or inline iframe elements.

Engineers MUST NOT navigate the primary Capacitor WKWebView to external identity provider URLs (e.g., Auth0, Okta, Google Identity) directly via window.location.href or inline iframe elements.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services handling authentication MUST configure prefersEphemeralWebBrowserSession

Services handling authentication MUST configure prefersEphemeralWebBrowserSession: true when invoking native OAuth flows to ensure cookies are not retained in Safari's shared container.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Capacitor iOS plugins instantiating auxiliary WKWebView instances MUST assign WKWebsiteDataStore.nonPersistent() or a custom partitioned WKWebsiteDataStore instead of WKWebsiteDataStore.default().

Capacitor iOS plugins instantiating auxiliary WKWebView instances MUST assign WKWebsiteDataStore.nonPersistent() or a custom partitioned WKWebsiteDataStore instead of WKWebsiteDataStore.default().

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store sensitive JWT tokens or refresh tokens in document.cookie or localStorage where bridge-level WKWebView persistence can be inspected or extracted via cross-origin web views.

Components NEVER store sensitive JWT tokens or refresh tokens in document.cookie or localStorage where bridge-level WKWebView persistence can be inspected or extracted via cross-origin web views.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 WKWebView Process Pool & Cookie Jar Partitioning Standard critical for AI coding assistants?

Enforces strict cookie jar partitioning and process pool isolation in Capacitor 7 iOS runtimes. Prevents cross-origin authentication bleed, session fixation, and credential leakage between embedded third-party OAuth flows and core application runtimes by prohibiting shared WKWebsiteDataStore configurations and mandate-driven ephemeral authentication sessions. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Executing Third-Party OAuth via Shared Process Pool WKWebView or Unpartitioned In-App Frames) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor