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

Capacitor 7 Isolated WASM Engine Memory Sandboxing Standard

Enforces strict process and memory sandboxing for on-device edge AI WebAssembly runtimes inside Capacitor 7 hybrid applications. Prevents cross-origin context contamination and speculative execution memory extraction by isolating model weights, KV caches, and inference buffers inside ephemeral Web Workers with zero-copy buffer detachment and explicit Cross-Origin-Opener-Policy/Cross-Origin-Embedder-Policy controls.

Prohibited Anti-Pattern: Instantiating Edge AI WASM Memory on the Global Window Thread Without Origin Isolation and Worker Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Isolated WASM Engine Memory Sandboxing Standard - Enforces strict process and memory sandboxing for on-device edge AI WebAssembly runtimes inside Capacitor 7 hybrid applications. Prevents cross-origin context contamination and speculative execution memory extraction by isolating model weights, KV caches, and inference buffers inside ephemeral Web Workers with zero-copy buffer detachment and explicit Cross-Origin-Opener-Policy/Cross-Origin-Embedder-Policy controls.
globs: capacitor.config.ts, src/**/*.{ts,tsx}, src/workers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-wasm-memory-sandboxing-standard"
---

# Capacitor 7 Isolated WASM Engine Memory Sandboxing Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Instantiating Edge AI WASM Memory on the Global Window Thread Without Origin Isolation and Worker Boundaries

## System Constraints
You are a Principal Mobile Systems Architect and Security Engineer enforcing strict WebAssembly memory sandboxing in Capacitor 7. You MUST ensure on-device Edge AI inference (e.g., ONNX, WebLLM, llama.cpp WASM) executes inside dedicated, isolated Worker scopes with strict COOP/COEP headers, explicit memory zeroization, and zero-copy transferable ArrayBuffers. Reject any implementation that binds WebAssembly.Memory to window, shares memory pools across unverified bridge listeners, or bypasses origin verification.

## Strict Guidelines
- Engineers MUST ALWAYS isolate WebAssembly AI engines within dedicated Web Workers, never on the main WebView UI thread or global window scope.
- Engineers MUST configure Capacitor 7 server configuration to inject 'Cross-Origin-Opener-Policy: same-origin' and 'Cross-Origin-Embedder-Policy: require-corp' to protect SharedArrayBuffer boundaries.
- Code MUST explicitly zero-fill (overwrite) sensitive intermediate activation buffers and detached tensors immediately following inference lifecycle termination.
- Services MUST communicate across the UI and WASM worker boundary exclusively using structured clone Transferable objects (ArrayBuffer) to enforce complete ownership transfer and prevent double-read concurrency attacks.
- Components NEVER store raw WebAssembly.Memory instances or raw pointer addresses in Capacitor plugin state or non-sandboxed persistent storage.

## Bad vs Good Implementations
### Edge AI WASM Initialization and Memory Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocating shared WebAssembly.Memory directly in the main WebView window leaks sensitive model weights, user prompts, and embeddings to any compromised script or cross-origin iframe. Exposing the memory instance globally and failing to detach/zeroize buffers enables speculative side-channel extraction and memory corruption.
```typescript
import { Capacitor } from '@capacitor/core';

// ANTI-PATTERN: WASM Engine and Memory exposed globally on WebView window thread
export class InsecureModelRunner {
  private wasmMemory: WebAssembly.Memory | null = null;

  async initModel(wasmBytes: ArrayBuffer, weightsUrl: string) {
    // Insecure: SharedArrayBuffer without explicit origin sandboxing
    this.wasmMemory = new WebAssembly.Memory({ initial: 256, maximum: 1024, shared: true });
    
    const imports = {
      env: { memory: this.wasmMemory }
    };
    
    const instance = await WebAssembly.instantiate(wasmBytes, imports);
    // LEAK: Exposing internal model memory directly on window or across global scope
    (window as any).__EDGE_AI_MEMORY__ = this.wasmMemory;
    return instance;
  }

  async infer(input: Float32Array): Promise<Float32Array> {
    // Direct mutation of global memory pool without lifecycle cleanup
    const buffer = new Float32Array(this.wasmMemory!.buffer, 0, input.length);
    buffer.set(input);
    // Native Capacitor Bridge call exposes raw buffer pointer
    return buffer;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Execution is segregated inside a Dedicated Web Worker context with non-shared WebAssembly.Memory. Input data ownership is completely relinquished via ArrayBuffer transferables, preventing race conditions. Intermediate activations are explicitly zero-filled after inference to prevent cross-request memory scraping.
```typescript
import { CapacitorHttp } from '@capacitor/core';

// PRODUCTION FIX: Sandboxed Worker Controller with Zero-Copy Transfer and Explicit Zeroization
export interface InferencePayload {
  id: string;
  tensorBuffer: ArrayBuffer;
  shape: number[];
}

export class SandboxedModelController {
  private worker: Worker;

  constructor() {
    // Explicitly isolated Dedicated Worker sandbox
    this.worker = new Worker(new URL('./ai-sandbox.worker.ts', import.meta.url), {
      type: 'module'
    });
  }

  public async executeInference(inputData: Float32Array, shape: number[]): Promise<Float32Array> {
    return new Promise((resolve, reject) => {
      const runId = crypto.randomUUID();
      
      // Create disposable copy to transfer ownership entirely
      const transferableBuffer = inputData.buffer.slice(0);

      const handleResponse = (event: MessageEvent) => {
        if (event.data?.id !== runId) return;
        this.worker.removeEventListener('message', handleResponse);

        if (event.data.error) {
          reject(new Error(event.data.error));
          return;
        }

        const outputArray = new Float32Array(event.data.resultBuffer);
        resolve(outputArray);
      };

      this.worker.addEventListener('message', handleResponse);

      // Transfer buffer ownership; source buffer becomes detached immediately
      this.worker.postMessage(
        { id: runId, tensorBuffer: transferableBuffer, shape },
        [transferableBuffer]
      );
    });
  }

  public terminate(): void {
    this.worker.terminate();
  }
}

// ai-sandbox.worker.ts (Implementation Reference)
// self.onmessage = async (e: MessageEvent<InferencePayload>) => {
//   const { id, tensorBuffer, shape } = e.data;
//   try {
//     const memory = new WebAssembly.Memory({ initial: 256, maximum: 512, shared: false });
//     // Execute isolated inference logic...
//     const result = new ArrayBuffer(shape.reduce((a, b) => a * b, 4));
//     // Zeroize intermediate memory
//     new Uint8Array(tensorBuffer).fill(0);
//     self.postMessage({ id, resultBuffer: result }, [result]);
//   } catch (err: any) {
//     self.postMessage({ id, error: err.message });
//   }
// };
```

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 Isolated WASM Engine Memory Sandboxing Standard

Capacitor 7 Isolated WASM Engine Memory Sandboxing Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict process and memory sandboxing for on-device edge AI WebAssembly runtimes inside Capacitor 7 hybrid applications. Prevents cross-origin context contamination and speculative execution memory extraction by isolating model weights, KV caches, and inference buffers inside ephemeral Web Workers with zero-copy buffer detachment and explicit Cross-Origin-Opener-Policy/Cross-Origin-Embedder-Policy controls. 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: Instantiating Edge AI WASM Memory on the Global Window Thread Without Origin Isolation and Worker Boundaries 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 DriftInstantiating Edge AI WASM Memory on the Global Window Thread Without Origin Isolation and Worker BoundariesCritical
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 WebAssembly AI engines within dedicated Web Workers, never on the main WebView UI thread or global window scope.

Engineers MUST ALWAYS isolate WebAssembly AI engines within dedicated Web Workers, never on the main WebView UI thread or global window scope.

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 configure Capacitor 7 server configuration to inject 'Cross-Origin-Opener-Policy

Engineers MUST configure Capacitor 7 server configuration to inject 'Cross-Origin-Opener-Policy: same-origin' and 'Cross-Origin-Embedder-Policy: require-corp' to protect SharedArrayBuffer boundaries.

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

Code MUST explicitly zero-fill (overwrite) sensitive intermediate activation buffers and detached tensors immediately following inference lifecycle termination.

Code MUST explicitly zero-fill (overwrite) sensitive intermediate activation buffers and detached tensors immediately following inference lifecycle termination.

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

Services MUST communicate across the UI and WASM worker boundary exclusively using structured clone Transferable objects (ArrayBuffer) to enforce complete ownership transfer and prevent double-read concurrency attacks.

Services MUST communicate across the UI and WASM worker boundary exclusively using structured clone Transferable objects (ArrayBuffer) to enforce complete ownership transfer and prevent double-read concurrency attacks.

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 raw WebAssembly.Memory instances or raw pointer addresses in Capacitor plugin state or non-sandboxed persistent storage.

Components NEVER store raw WebAssembly.Memory instances or raw pointer addresses in Capacitor plugin state or non-sandboxed persistent storage.

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 Isolated WASM Engine Memory Sandboxing Standard critical for AI coding assistants?

Enforces strict process and memory sandboxing for on-device edge AI WebAssembly runtimes inside Capacitor 7 hybrid applications. Prevents cross-origin context contamination and speculative execution memory extraction by isolating model weights, KV caches, and inference buffers inside ephemeral Web Workers with zero-copy buffer detachment and explicit Cross-Origin-Opener-Policy/Cross-Origin-Embedder-Policy controls. 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 (Instantiating Edge AI WASM Memory on the Global Window Thread Without Origin Isolation and Worker Boundaries) 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