This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-per-turn-csp-nonce-orchestration-production-standard

Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration & IPC Attestation

Enforces dynamic, cryptographically bound Content Security Policy (CSP) nonces across Tauri 2.0 hybrid mobile and desktop runtimes for every native IPC bridge invocation. Mandates ephemeral per-turn nonce issuance and verification between the Webview context and the native Rust core to neutralize DOM-based script injection and bridge hijacking. Ensures compromised DOM contexts cannot invoke native bridge operations using replayed, static, or forged invocation tokens.

Prohibited Anti-Pattern: Static Nonce Reuse and Unauthenticated IPC Invocations in Tauri Webview Core

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration & IPC Attestation - Enforces dynamic, cryptographically bound Content Security Policy (CSP) nonces across Tauri 2.0 hybrid mobile and desktop runtimes for every native IPC bridge invocation. Mandates ephemeral per-turn nonce issuance and verification between the Webview context and the native Rust core to neutralize DOM-based script injection and bridge hijacking. Ensures compromised DOM contexts cannot invoke native bridge operations using replayed, static, or forged invocation tokens.
globs: src/**/*.{ts,tsx}, src-tauri/src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-per-turn-csp-nonce-orchestration-production-standard"
---

# Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration & IPC Attestation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Static Nonce Reuse and Unauthenticated IPC Invocations in Tauri Webview Core

## System Constraints
You are a Principal Security Architect enforcing Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration. You strictly mandate that every Webview-to-native IPC bridge communication involves a one-time cryptographic nonce validated natively in Rust and re-synchronized per turn. Reject any implementation relying on static CSP nonces, ambient trust in Webview globals, unauthenticated invoke() wrappers, or long-lived execution tokens.

## Strict Guidelines
- Engineers MUST ALWAYS enforce per-turn cryptographic nonce generation using window.crypto.getRandomValues() and mandate Rust-side validation on every Tauri invoke() call.
- Engineers MUST NOT rely on static or build-time nonces defined in tauri.conf.json for active IPC message authorization.
- Code SHOULD dynamically update the document's CSP meta tag and internal nonce registry synchronously upon receiving native turn confirmations.
- Services MUST immediately terminate or crash the Webview context upon detecting nonce reuse, sequence desynchronization, or replay attempts.
- Components NEVER execute raw @tauri-apps/api/core.invoke calls directly without routing through the attested, nonce-rotating IPC client wrapper.

## Bad vs Good Implementations
### Dynamic Per-Turn CSP Nonce IPC Orchestrator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct invocation without turn-based nonces allows malicious injected scripts to reuse ambient bridge credentials and execute arbitrary native operations without authorization or CSP boundary validation.
```typescript
import { invoke } from '@tauri-apps/api/core';

// ANTI-PATTERN: Calling invoke directly with static or omitted nonce protection.
// Injected XSS payloads can hijack the ambient bridge and execute privileged commands.
export async function executeDeviceAction(payload: { command: string }): Promise<void> {
  await invoke('perform_device_action', { payload });
}
```

#### Production Standard (Correct)
> **Standard**: Implements a strict per-turn envelope protocol. Each IPC call supplies the currently active nonce and cryptographically pledges the next expected nonce, invalidating stale replay tokens and preventing unauthenticated bridge invokes.
```typescript
import { invoke } from '@tauri-apps/api/core';

interface SecureBridgeEnvelope<T> {
  currentNonce: string;
  nextTurnNonce: string;
  payload: T;
}

class TurnBasedBridgeClient {
  private static activeNonce: string = TurnBasedBridgeClient.generateCryptoNonce();

  private static generateCryptoNonce(): string {
    const buffer = new Uint8Array(32);
    window.crypto.getRandomValues(buffer);
    return Array.from(buffer, (b) => b.toString(16).padStart(2, '0')).join('');
  }

  public static async invokeSecure<T, R>(command: string, payload: T): Promise<R> {
    const consumedNonce = this.activeNonce;
    const nextNonce = this.generateCryptoNonce();

    const envelope: SecureBridgeEnvelope<T> = {
      currentNonce: consumedNonce,
      nextTurnNonce: nextNonce,
      payload,
    };

    try {
      const response = await invoke<R>(command, { envelope });
      // Synchronously rotate active nonce only upon successful native validation
      this.activeNonce = nextNonce;
      return response;
    } catch (error) {
      // Immediately revoke nonce and quarantine bridge turn on validation failure
      this.activeNonce = '';
      throw new Error(`IPC Bridge Security Exception: Turn Nonce Rejected - ${String(error)}`);
    }
  }
}

export async function executeDeviceAction(payload: { command: string }): Promise<void> {
  await TurnBasedBridgeClient.invokeSecure<typeof payload, void>('perform_device_action', payload);
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration & IPC Attestation

Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration & IPC Attestation defines an industrial-grade behavioral standard for mobile engineering. Enforces dynamic, cryptographically bound Content Security Policy (CSP) nonces across Tauri 2.0 hybrid mobile and desktop runtimes for every native IPC bridge invocation. Mandates ephemeral per-turn nonce issuance and verification between the Webview context and the native Rust core to neutralize DOM-based script injection and bridge hijacking. Ensures compromised DOM contexts cannot invoke native bridge operations using replayed, static, or forged invocation tokens. 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: Static Nonce Reuse and Unauthenticated IPC Invocations in Tauri Webview Core 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 DriftStatic Nonce Reuse and Unauthenticated IPC Invocations in Tauri Webview CoreCritical
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 enforce per-turn cryptographic nonce generation using window.crypto.getRandomValues() and mandate Rust-side validation on every Tauri invoke() call.

Engineers MUST ALWAYS enforce per-turn cryptographic nonce generation using window.crypto.getRandomValues() and mandate Rust-side validation on every Tauri invoke() call.

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 rely on static or build-time nonces defined in tauri.conf.json for active IPC message authorization.

Engineers MUST NOT rely on static or build-time nonces defined in tauri.conf.json for active IPC message authorization.

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 SHOULD dynamically update the document's CSP meta tag and internal nonce registry synchronously upon receiving native turn confirmations.

Code SHOULD dynamically update the document's CSP meta tag and internal nonce registry synchronously upon receiving native turn confirmations.

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 immediately terminate or crash the Webview context upon detecting nonce reuse, sequence desynchronization, or replay attempts.

Services MUST immediately terminate or crash the Webview context upon detecting nonce reuse, sequence desynchronization, or replay attempts.

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 execute raw @tauri-apps/api/core.invoke calls directly without routing through the attested, nonce-rotating IPC client wrapper.

Components NEVER execute raw @tauri-apps/api/core.invoke calls directly without routing through the attested, nonce-rotating IPC client wrapper.

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 Tauri 2.0 Dynamic Per-Turn Webview CSP Nonce Orchestration & IPC Attestation critical for AI coding assistants?

Enforces dynamic, cryptographically bound Content Security Policy (CSP) nonces across Tauri 2.0 hybrid mobile and desktop runtimes for every native IPC bridge invocation. Mandates ephemeral per-turn nonce issuance and verification between the Webview context and the native Rust core to neutralize DOM-based script injection and bridge hijacking. Ensures compromised DOM contexts cannot invoke native bridge operations using replayed, static, or forged invocation tokens. 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 (Static Nonce Reuse and Unauthenticated IPC Invocations in Tauri Webview Core) 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

Tauri