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

Capacitor 7 Universal Link App-Site Association Integrity Guardrail

Enforces strict origin validation and association integrity for Capacitor 7 Universal Links (iOS) and Android App Links. Mitigates rogue deep-link intent hijacking and parameter tampering by mandating runtime domain verification, strict HTTPS enforcement, and origin-bound deep-link payload sanitization.

Prohibited Anti-Pattern: Blind Deep-Link Ingestion via Unvalidated App URL Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Universal Link App-Site Association Integrity Guardrail - Enforces strict origin validation and association integrity for Capacitor 7 Universal Links (iOS) and Android App Links. Mitigates rogue deep-link intent hijacking and parameter tampering by mandating runtime domain verification, strict HTTPS enforcement, and origin-bound deep-link payload sanitization.
globs: src/**/*.{ts,tsx}, android/app/src/main/AndroidManifest.xml, ios/App/App/AppDelegate.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-universal-link-integrity-guardrail"
---

# Capacitor 7 Universal Link App-Site Association Integrity Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Blind Deep-Link Ingestion via Unvalidated App URL Handlers

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust deep-link ingestion for Capacitor 7 applications. You MUST reject any deep-link routing implementation that parses raw incoming URLs without canonical origin validation, TLS scheme verification, and payload structural sanitization. Enforce strict association between the application bundle ID and the remote assetlinks.json / apple-app-site-association origins.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict origin verification against an immutable allowlist of canonical domains before processing any Capacitor `appUrlOpen` event.
- Engineers MUST NEVER trust custom URI schemes (e.g., `myapp://`) for sensitive, state-altering, or authenticated operations; only verified Universal Links/App Links via standard HTTPS MUST be accepted.
- Handlers MUST reject URLs containing unexpected subdomains, non-standard ports, userinfo components (`user:pass@`), or path traversals (`/../`).
- Navigation dispatchers MUST ALWAYS unwrap, validate, and parse deep-link parameters using a hardened schema validator (e.g., Zod) instead of raw string concatenation or naive regex.
- Native configuration files (AndroidManifest.xml and Entitlements) MUST ALWAYS set `android:autoVerify="true"` and strictly declare `applinks:` domains matching production AASA configurations.
- The application SHOULD continuously monitor and log association validation failures during runtime initialization via telemetry to detect domain hijacking or certificate pinning mismatches.

## Bad vs Good Implementations
### Universal Link Handling in Capacitor 7

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts arbitrary incoming URL schemes (including spoofed custom schemes), performs zero origin validation against approved hosts, and directly feeds unparsed query paths into the internal router, enabling malicious intent injection and parameter tampering.
```typescript
import { App, URLOpenListenerEvent } from '@capacitor/app';
import { router } from './router';

// CRITICAL SECURITY FLAW: Blindly accepting any scheme, domain, or malicious payload
App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => {
  const url = new URL(event.url);
  // Direct unvalidated redirect allows open redirection and auth token leakage
  const targetPath = url.pathname + url.search;
  router.navigate(targetPath);
});
```

#### Production Standard (Correct)
> **Standard**: Validates the incoming URL protocol to ensure only secure HTTPS links are accepted, checks the canonical host against an immutable allowlist, rejects unexpected ports or credentials, and parses routing parameters with a strict Zod schema to prevent open redirect vulnerabilities.
```typescript
import { App, URLOpenListenerEvent } from '@capacitor/app';
import { z } from 'zod';
import { router } from './router';

const TRUSTED_DOMAINS = new Set([
  'app.example.com',
  'auth.example.com'
]);

const DeepLinkPayloadSchema = z.object({
  pathname: z.string().regex(/^\/[a-zA-Z0-9_\-\/]+$/),
  token: z.string().uuid().optional(),
  redirectStep: z.enum(['checkout', 'verify', 'profile']).optional()
});

export function initializeUniversalLinks(): void {
  App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => {
    try {
      const parsedUrl = new URL(event.url);

      // 1. Enforce HTTPS scheme
      if (parsedUrl.protocol !== 'https:') {
        console.error(`Rejected non-HTTPS deep link: ${event.url}`);
        return;
      }

      // 2. Strict Domain Allowlist Matching
      if (!TRUSTED_DOMAINS.has(parsedUrl.hostname.toLowerCase())) {
        console.error(`Unauthorized deep link host: ${parsedUrl.hostname}`);
        return;
      }

      // 3. Strict Port & Userinfo Invariants
      if (parsedUrl.port !== '' || parsedUrl.username !== '' || parsedUrl.password !== '') {
        console.error(`Malformed deep link authority component detected`);
        return;
      }

      // 4. Schema-governed payload validation
      const validated = DeepLinkPayloadSchema.parse({
        pathname: parsedUrl.pathname,
        token: parsedUrl.searchParams.get('token') ?? undefined,
        redirectStep: parsedUrl.searchParams.get('step') ?? undefined
      });

      router.navigate(validated.pathname, {
        state: { token: validated.token, step: validated.redirectStep }
      });
    } catch (error) {
      console.error('Deep link integrity verification failed:', error);
    }
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Universal Link App-Site Association Integrity Guardrail

Capacitor 7 Universal Link App-Site Association Integrity Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict origin validation and association integrity for Capacitor 7 Universal Links (iOS) and Android App Links. Mitigates rogue deep-link intent hijacking and parameter tampering by mandating runtime domain verification, strict HTTPS enforcement, and origin-bound deep-link payload sanitization. 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 Deep-Link Ingestion via Unvalidated App URL Handlers 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 Deep-Link Ingestion via Unvalidated App URL HandlersCritical
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 origin verification against an immutable allowlist of canonical domains before processing any Capacitor `appUrlOpen` event.

Engineers MUST ALWAYS enforce strict origin verification against an immutable allowlist of canonical domains before processing any Capacitor `appUrlOpen` event.

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 NEVER trust custom URI schemes (e.g., `myapp

Engineers MUST NEVER trust custom URI schemes (e.g., `myapp://`) for sensitive, state-altering, or authenticated operations; only verified Universal Links/App Links via standard HTTPS MUST be accepted.

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

Handlers MUST reject URLs containing unexpected subdomains, non-standard ports, userinfo components (`user

Handlers MUST reject URLs containing unexpected subdomains, non-standard ports, userinfo components (`user:pass@`), or path traversals (`/../`).

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

Navigation dispatchers MUST ALWAYS unwrap, validate, and parse deep-link parameters using a hardened schema validator (e.g., Zod) instead of raw string concatenation or naive regex.

Navigation dispatchers MUST ALWAYS unwrap, validate, and parse deep-link parameters using a hardened schema validator (e.g., Zod) instead of raw string concatenation or naive regex.

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

Native configuration files (AndroidManifest.xml and Entitlements) MUST ALWAYS set `android

Native configuration files (AndroidManifest.xml and Entitlements) MUST ALWAYS set `android:autoVerify="true"` and strictly declare `applinks:` domains matching production AASA configurations.

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

The application SHOULD continuously monitor and log association validation failures during runtime initialization via telemetry to detect domain hijacking or certificate pinning mismatches.

The application SHOULD continuously monitor and log association validation failures during runtime initialization via telemetry to detect domain hijacking or certificate pinning mismatches.

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 App-Site Association Integrity Guardrail critical for AI coding assistants?

Enforces strict origin validation and association integrity for Capacitor 7 Universal Links (iOS) and Android App Links. Mitigates rogue deep-link intent hijacking and parameter tampering by mandating runtime domain verification, strict HTTPS enforcement, and origin-bound deep-link payload sanitization. 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 Deep-Link Ingestion via Unvalidated App URL Handlers) 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