This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-v2-origin-bound-custom-protocol-deserialization

Tauri 2.0 Custom Protocol IPC Origin-Bound Deserialization Standard

Enforces strict origin validation and cryptographically attested message parsing on Tauri 2.0 custom protocol handlers (`register_uri_scheme_protocol` / `register_asynchronous_uri_scheme_protocol`). Prevents unauthorized cross-webview command execution and arbitrary payload deserialization triggered by embedded external web contexts, deep links, or untrusted IFrames on Android and iOS.

Prohibited Anti-Pattern: Blind Deserialization of Custom URI Payloads Without Strict Webview Origin and Token Attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Custom Protocol IPC Origin-Bound Deserialization Standard - Enforces strict origin validation and cryptographically attested message parsing on Tauri 2.0 custom protocol handlers (`register_uri_scheme_protocol` / `register_asynchronous_uri_scheme_protocol`). Prevents unauthorized cross-webview command execution and arbitrary payload deserialization triggered by embedded external web contexts, deep links, or untrusted IFrames on Android and iOS.
globs: src-tauri/src/**/*.rs, src-tauri/tauri.conf.json, src/**/*.{ts,tsx,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-v2-origin-bound-custom-protocol-deserialization"
---

# Tauri 2.0 Custom Protocol IPC Origin-Bound Deserialization Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Blind Deserialization of Custom URI Payloads Without Strict Webview Origin and Token Attestation

## System Constraints
You are a Principal Security Architect enforcing Tauri 2.0 Custom Protocol IPC Origin-Bound Deserialization Standards. Mandate absolute isolation between external webview contexts and native command dispatch. Ensure all custom URI scheme requests verify caller window identity, canonical hostnames, and cryptographic origin tokens before deserializing IPC arguments.

## Strict Guidelines
- Engineers MUST ALWAYS validate the `Origin` and `Sec-Fetch-Site` HTTP request headers inside `register_uri_scheme_protocol` and `register_asynchronous_uri_scheme_protocol` against compile-time declared allowed hosts.
- Engineers MUST NOT invoke `serde_json::from_slice` or any binary/text deserializer on URI scheme request bodies before asserting that the caller origin matches `tauri://localhost` (or configured internal custom mobile schemes).
- Services MUST verify per-session ephemeral nonces or HMAC-signed tokens passed via custom headers (`X-Tauri-IPC-Token`) for any privileged native command invocation executed over custom protocols.
- Code SHOULD leverage Tauri 2.0 ACL capabilities (`tauri.conf.json` permissions) rather than bypassing core IPC channels using unconstrained custom URI scheme handlers.
- Components NEVER expose universal deep-link or scheme handlers that directly map raw URI path segments and query parameters into dynamic native invocation calls.

## Bad vs Good Implementations
### Tauri 2.0 Custom Protocol Origin Validation & Safe Payload Deserialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The protocol handler parses the request body and executes commands without checking the Origin header or validating whether the calling webview context is authorized. Any rogue IFrame or external redirect inside a secondary webview can issue requests to custom-ipc:// and execute arbitrary actions.
```rust
// Insecure custom URI handler allowing arbitrary origins to trigger commands
use tauri::http::{Request, Response, ResponseBuilder};
use serde::Deserialize;

#[derive(Deserialize)]
struct CommandPayload {
    action: String,
    args: Vec<String>,
}

pub fn setup_insecure_scheme<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
    builder.register_uri_scheme_protocol("custom-ipc", |_app, request| {
        // CRITICAL BUG: Deserializes without origin validation
        let body = request.body();
        if let Ok(payload) = serde_json::from_slice::<CommandPayload>(body) {
            println!("Executing: {}", payload.action);
        }
        ResponseBuilder::new().status(200).body(vec![]).unwrap()
    })
}
```

#### Production Standard (Correct)
> **Standard**: Validates the Origin header explicitly against the local app scheme before deserializing payloads, rejects excessively large payloads to avoid denial-of-service, and confines parsing strictly to typed domain-bound structures.
```rust
// Hardened custom URI handler enforcing origin checks & cryptographically bound tokens
use tauri::http::{Request, Response, ResponseBuilder, StatusCode};
use serde::Deserialize;

const EXPECTED_ORIGIN: &str = "tauri://localhost";

#[derive(Deserialize)]
struct SafePayload {
    action: String,
    nonce: String,
}

pub fn setup_secure_scheme<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
    builder.register_asynchronous_uri_scheme_protocol("custom-ipc", |app, request, responder| {
        // 1. Invariant: Origin header must strictly match local webview authority
        let origin_valid = request
            .headers()
            .get("Origin")
            .and_then(|v| v.to_str().ok())
            .map_or(false, |origin| origin == EXPECTED_ORIGIN);

        if !origin_valid {
            responder.respond(ResponseBuilder::new().status(StatusCode::FORBIDDEN).body(b"Forbidden Origin".to_vec()).unwrap());
            return;
        }

        // 2. Bound Deserialization: Verify size and parse strictly validated structures
        let body = request.body();
        if body.len() > 65536 { // Enforce max size limits to prevent memory exhaustion
            responder.respond(ResponseBuilder::new().status(StatusCode::PAYLOAD_TOO_LARGE).body(b"Payload too large".to_vec()).unwrap());
            return;
        }

        match serde_json::from_slice::<SafePayload>(body) {
            Ok(payload) => {
                // 3. Process validated payload safely
                responder.respond(ResponseBuilder::new().status(StatusCode::OK).body(b"Acknowledged".to_vec()).unwrap());
            }
            Err(_) => {
                responder.respond(ResponseBuilder::new().status(StatusCode::BAD_REQUEST).body(b"Invalid Payload".to_vec()).unwrap());
            }
        }
    })
}
```

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: Tauri 2.0 Custom Protocol IPC Origin-Bound Deserialization Standard

Tauri 2.0 Custom Protocol IPC Origin-Bound Deserialization Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict origin validation and cryptographically attested message parsing on Tauri 2.0 custom protocol handlers (`register_uri_scheme_protocol` / `register_asynchronous_uri_scheme_protocol`). Prevents unauthorized cross-webview command execution and arbitrary payload deserialization triggered by embedded external web contexts, deep links, or untrusted IFrames on Android and iOS. 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: Blind Deserialization of Custom URI Payloads Without Strict Webview Origin and Token Attestation 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 DriftBlind Deserialization of Custom URI Payloads Without Strict Webview Origin and Token AttestationCritical
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 validate the `Origin` and `Sec-Fetch-Site` HTTP request headers inside `register_uri_scheme_protocol` and `register_asynchronous_uri_scheme_protocol` against compile-time declared allowed hosts.

Engineers MUST ALWAYS validate the `Origin` and `Sec-Fetch-Site` HTTP request headers inside `register_uri_scheme_protocol` and `register_asynchronous_uri_scheme_protocol` against compile-time declared allowed hosts.

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 invoke `serde_json

Engineers MUST NOT invoke `serde_json::from_slice` or any binary/text deserializer on URI scheme request bodies before asserting that the caller origin matches `tauri://localhost` (or configured internal custom mobile schemes).

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 MUST verify per-session ephemeral nonces or HMAC-signed tokens passed via custom headers (`X-Tauri-IPC-Token`) for any privileged native command invocation executed over custom protocols.

Services MUST verify per-session ephemeral nonces or HMAC-signed tokens passed via custom headers (`X-Tauri-IPC-Token`) for any privileged native command invocation executed over custom protocols.

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

Code SHOULD leverage Tauri 2.0 ACL capabilities (`tauri.conf.json` permissions) rather than bypassing core IPC channels using unconstrained custom URI scheme handlers.

Code SHOULD leverage Tauri 2.0 ACL capabilities (`tauri.conf.json` permissions) rather than bypassing core IPC channels using unconstrained custom URI scheme handlers.

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 expose universal deep-link or scheme handlers that directly map raw URI path segments and query parameters into dynamic native invocation calls.

Components NEVER expose universal deep-link or scheme handlers that directly map raw URI path segments and query parameters into dynamic native invocation calls.

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 Custom Protocol IPC Origin-Bound Deserialization Standard critical for AI coding assistants?

Enforces strict origin validation and cryptographically attested message parsing on Tauri 2.0 custom protocol handlers (`register_uri_scheme_protocol` / `register_asynchronous_uri_scheme_protocol`). Prevents unauthorized cross-webview command execution and arbitrary payload deserialization triggered by embedded external web contexts, deep links, or untrusted IFrames on Android and iOS. 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 (Blind Deserialization of Custom URI Payloads Without Strict Webview Origin and Token Attestation) 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