This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-universal-link-attestation-guardrail

Capacitor 7 Universal Link Cryptographic Attestation and Bridge Sanitization Standard

Mandates strict cryptographic and domain origin attestation for Universal Links (iOS) and Android App Links prior to dispatching deep link payloads across the Capacitor 7 bridge. Prohibits implicit trust of incoming URI parameters in `appUrlOpen` listeners without host verification matching OS-level digital asset links. Prevents deep link hijacking, custom scheme interception, and unauthenticated execution of privileged native plugins.

Prohibited Anti-Pattern: Trusting Raw appUrlOpen Events and Custom Schemes for Native Bridge Dispatch

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Universal Link Cryptographic Attestation and Bridge Sanitization Standard - Mandates strict cryptographic and domain origin attestation for Universal Links (iOS) and Android App Links prior to dispatching deep link payloads across the Capacitor 7 bridge. Prohibits implicit trust of incoming URI parameters in `appUrlOpen` listeners without host verification matching OS-level digital asset links. Prevents deep link hijacking, custom scheme interception, and unauthenticated execution of privileged native plugins.
globs: src/**/*.{ts,tsx,js,jsx}, android/app/src/main/**/*.{java,kt}, ios/App/App/**/*.{swift,m}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-universal-link-attestation-guardrail"
---

# Capacitor 7 Universal Link Cryptographic Attestation and Bridge Sanitization Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Trusting Raw appUrlOpen Events and Custom Schemes for Native Bridge Dispatch

## System Constraints
You are a Principal Mobile Security Architect enforcing strict Universal Link attestation and deep link validation in Capacitor 7 hybrid architectures. You must ensure that no deep link payload is passed to the Capacitor web bridge, navigation router, or native plugins without cryptographically anchored origin validation matching the application's Apple App Site Association (AASA) or Android Digital Asset Links (assetlinks.json).

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict HTTPS protocol verification on inbound `appUrlOpen` payloads and explicitly reject custom URL schemes (e.g., `myapp://`) for state mutation or privileged actions.
- Engineers MUST validate the inbound URL against an immutable domain allowlist tied directly to verified OS-level Universal Link / App Link entitlements before processing.
- Engineers MUST NOT invoke native Capacitor plugins or deserialize payload tokens directly from unvalidated `AppUrlOpen.url` query parameters.
- Code MUST sanitize path segments and query parameters using strict URL parsing primitives (e.g., `URL` or `URLSearchParams`) rather than regular expression extraction or direct string manipulation.
- Services MUST verify the OS link handling context, confirming the deep link was routed via `NSUserActivityTypeBrowsingWeb` (iOS) or an auto-verified App Link intent (Android) when handling sensitive workflows.
- Components NEVER execute stateful side effects or navigation transitions directly within the raw `App.addListener('appUrlOpen')` callback without passing through a centralized attestation pipeline.

## Bad vs Good Implementations
### Universal Link Processing via Attested Deep Link Service

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Listens directly to incoming deep links without validating the scheme, host, or OS-level attestation. Attackers can register the same custom scheme or redirect via open redirectors to inject arbitrary authentication tokens or force privileged native plugin execution across the Capacitor bridge.
```typescript
import { App } from '@capacitor/app';
import { NativeStorage } from '@capacitor-community/native-storage';

// VULNERABLE: Implicit trust of custom schemes and unverified parameters
App.addListener('appUrlOpen', async (event) => {
  // Accepts unverified custom scheme (e.g., myapp://reset-token?token=attacker_controlled)
  const url = new URL(event.url);
  const token = url.searchParams.get('token');
  const action = url.pathname.replace('/', '');

  if (action === 'auth-exchange' && token) {
    // Directly executing native plugin with unverified payload
    await NativeStorage.set({ key: 'authToken', value: token });
    window.location.href = `/dashboard?token=${token}`;
  }
});
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```typescript
import { App, URLOpenListenerEvent } from '@capacitor/app';

const TRUSTED_DOMAINS = Object.freeze([
  'auth.enterprise.domain.com',
  'app.enterprise.domain.com'
] as const);

type TrustedDomain = (typeof TRUSTED_DOMAINS)[number];

interface ValidatedDeepLinkPayload {
  readonly domain: TrustedDomain;
  readonly pathname: string;
  readonly safeParams: ReadonlyMap<string, string>;
}

export class DeepLinkAttestationService {
  private static isTrustedHost(host: string): host is TrustedDomain {
    return (TRUSTED_DOMAINS as readonly string[]).includes(host.toLowerCase());
  }

  public static validateAndAttest(rawUrl: string): ValidatedDeepLinkPayload {
    let parsed: URL;
    try {
      parsed = new URL(rawUrl);
    } catch {
      throw new Error('Invalid deep link URI format');
    }

    // Invariant 1: Reject insecure protocols and hijackable custom schemes
    if (parsed.protocol !== 'https:') {
      throw new SecurityError(`Untrusted protocol: ${parsed.protocol}. Only HTTPS Universal Links are permitted.`);
    }

    // Invariant 2: Cryptographic origin validation against verified Digital Asset / AASA domains
    if (!this.isTrustedHost(parsed.host)) {
      throw new SecurityError(`Unregistered domain origin: ${parsed.host}. Rejected by Universal Link guardrail.`);
    }

    // Invariant 3: Sanitize and freeze query parameters
    const safeParams = new Map<string, string>();
    parsed.searchParams.forEach((value, key) => {
      safeParams.set(encodeURIComponent(key), encodeURIComponent(value));
    });

    return Object.freeze({
      domain: parsed.host,
      pathname: parsed.pathname,
      safeParams: Object.freeze(safeParams)
    });
  }
}

App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => {
  try {
    const attestedLink = DeepLinkAttestationService.validateAndAttest(event.url);
    // Hand off exclusively to sanitized internal application state router
    console.info(`Attested Universal Link processed: ${attestedLink.domain}${attestedLink.pathname}`);
  } catch (error) {
    console.error('Universal Link attestation failed. Payload rejected:', error);
  }
});
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Universal Link Cryptographic Attestation and Bridge Sanitization Standard

Capacitor 7 Universal Link Cryptographic Attestation and Bridge Sanitization Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates strict cryptographic and domain origin attestation for Universal Links (iOS) and Android App Links prior to dispatching deep link payloads across the Capacitor 7 bridge. Prohibits implicit trust of incoming URI parameters in `appUrlOpen` listeners without host verification matching OS-level digital asset links. Prevents deep link hijacking, custom scheme interception, and unauthenticated execution of privileged native plugins. 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: Trusting Raw appUrlOpen Events and Custom Schemes for Native Bridge Dispatch 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 DriftTrusting Raw appUrlOpen Events and Custom Schemes for Native Bridge DispatchCritical
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 strict HTTPS protocol verification on inbound `appUrlOpen` payloads and explicitly reject custom URL schemes (e.g., `myapp

Engineers MUST ALWAYS enforce strict HTTPS protocol verification on inbound `appUrlOpen` payloads and explicitly reject custom URL schemes (e.g., `myapp://`) for state mutation or privileged actions.

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 validate the inbound URL against an immutable domain allowlist tied directly to verified OS-level Universal Link / App Link entitlements before processing.

Engineers MUST validate the inbound URL against an immutable domain allowlist tied directly to verified OS-level Universal Link / App Link entitlements before processing.

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

Engineers MUST NOT invoke native Capacitor plugins or deserialize payload tokens directly from unvalidated `AppUrlOpen.url` query parameters.

Engineers MUST NOT invoke native Capacitor plugins or deserialize payload tokens directly from unvalidated `AppUrlOpen.url` query parameters.

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 MUST sanitize path segments and query parameters using strict URL parsing primitives (e.g., `URL` or `URLSearchParams`) rather than regular expression extraction or direct string manipulation.

Code MUST sanitize path segments and query parameters using strict URL parsing primitives (e.g., `URL` or `URLSearchParams`) rather than regular expression extraction or direct string manipulation.

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

Services MUST verify the OS link handling context, confirming the deep link was routed via `NSUserActivityTypeBrowsingWeb` (iOS) or an auto-verified App Link intent (Android) when handling sensitive workflows.

Services MUST verify the OS link handling context, confirming the deep link was routed via `NSUserActivityTypeBrowsingWeb` (iOS) or an auto-verified App Link intent (Android) when handling sensitive workflows.

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.
6

Components NEVER execute stateful side effects or navigation transitions directly within the raw `App.addListener('appUrlOpen')` callback without passing through a centralized attestation pipeline.

Components NEVER execute stateful side effects or navigation transitions directly within the raw `App.addListener('appUrlOpen')` callback without passing through a centralized attestation pipeline.

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 Universal Link Cryptographic Attestation and Bridge Sanitization Standard critical for AI coding assistants?

Mandates strict cryptographic and domain origin attestation for Universal Links (iOS) and Android App Links prior to dispatching deep link payloads across the Capacitor 7 bridge. Prohibits implicit trust of incoming URI parameters in `appUrlOpen` listeners without host verification matching OS-level digital asset links. Prevents deep link hijacking, custom scheme interception, and unauthenticated execution of privileged native plugins. 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 (Trusting Raw appUrlOpen Events and Custom Schemes for Native Bridge Dispatch) 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