This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-l3-client-data-origin-binding-invariant

WebAuthn Level 3 ClientDataJSON Origin Binding & Related Origin Validation

Enforces strict canonical origin binding verification on deserialized WebAuthn Level 3 clientDataJSON payloads in federated multi-tenant edge architectures. Precludes sub-origin relay, cross-tenant impersonation, and conditional UI credential leakage by enforcing strict exact-match origin validation, scheme/port verification, and Related Origin Requests (ROR) explicit allowlisting across reverse-proxy layers.

Prohibited Anti-Pattern: Lax or Regex-Based Origin Validation Allowing Subdomain Traversal and Cross-Tenant Credential Relay

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 ClientDataJSON Origin Binding & Related Origin Validation - Enforces strict canonical origin binding verification on deserialized WebAuthn Level 3 clientDataJSON payloads in federated multi-tenant edge architectures. Precludes sub-origin relay, cross-tenant impersonation, and conditional UI credential leakage by enforcing strict exact-match origin validation, scheme/port verification, and Related Origin Requests (ROR) explicit allowlisting across reverse-proxy layers.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/**/identity/**/*.{ts,tsx}, src/**/guards/**/*.{ts,tsx}, edge/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-client-data-origin-binding-invariant"
---

# WebAuthn Level 3 ClientDataJSON Origin Binding & Related Origin Validation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Lax or Regex-Based Origin Validation Allowing Subdomain Traversal and Cross-Tenant Credential Relay

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Level 3 Client Data JSON Origin Binding Invariant. In multi-tenant edge architectures with federated passkey auto-fill (Conditional UI), relying party authentication handlers must enforce deterministic, constant-time origin validation. Reject regex suffix matching, unverified sub-origins, and ambient Host headers. Strictly mandate exact canonical tuple matches (scheme, fully-qualified domain, port) and validate the Relying Party ID against canonical tenant metadata or explicit Related Origin Requests (ROR) manifests.

## Strict Guidelines
- Engineers MUST ALWAYS parse `clientDataJSON` using a secure JSON parser and extract the canonical `origin` tuple (scheme, hostname, port) using the standard `URL` Web API.
- Engineers MUST NEVER perform substring, suffix (`endsWith`), or loose regular-expression matching on `clientData.origin` to avoid sub-origin traversal (e.g., `tenant-a.auth.example.com.attacker.com`).
- Services MUST validate that `clientData.origin` exactly matches the expected canonical tenant origin registered in cryptographic tenant metadata, or matches a strictly verified Related Origin Requests (ROR) set.
- Services MUST verify that `clientData.type` is strictly either `webauthn.get` or `webauthn.create` matching the operational context, and verify the cryptographic signature over `clientDataHash`.
- Edge Proxies MUST NOT rewrite or forward untrusted ambient `Host` or `X-Forwarded-Host` headers as the expected origin ground truth for WebAuthn authentication ceremony assertions.

## Bad vs Good Implementations
### WebAuthn clientDataJSON Origin Validation in Multi-Tenant Edge Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `String.prototype.endsWith()` allows an attacker to mount sub-origin relay attacks by registering domains such as `victim.domain.attacker.com`. Additionally, checking `type.startsWith('webauthn.')` permits registration credentials (`webauthn.create`) to be submitted to assertion endpoints (`webauthn.get`).
```typescript
import { AuthenticatorAssertionResponse } from '@simplewebauthn/types';

interface VerifyRequest {
  tenantId: string;
  response: AuthenticatorAssertionResponse;
}

export async function verifyAssertionBad(req: VerifyRequest, tenantBaseDomain: string) {
  const clientData = JSON.parse(
    Buffer.from(req.response.clientDataJSON, 'base64url').toString('utf-8')
  );

  // CRITICAL VULNERABILITY: Loose suffix matching allows relay attacks
  // e.g. 'https://tenant-target.corp.com.attacker-controlled.net' passes
  if (!clientData.origin.endsWith(tenantBaseDomain)) {
    throw new Error('Invalid origin');
  }

  // CRITICAL VULNERABILITY: Permissive type check allows registration replay in auth flow
  if (!clientData.type.startsWith('webauthn.')) {
    throw new Error('Invalid ceremony type');
  }

  return true;
}
```

#### Production Standard (Correct)
> **Standard**: Parses the origin using the `URL` API to normalize the scheme, host, and port tuple, then evaluates canonical equivalence against tenant isolation boundaries and explicit Related Origin sets. Validates the exact ceremonial operation (`webauthn.get`) and performs constant-time challenge comparison before returning the cryptographic `clientDataHash`.
```typescript
import { AuthenticatorAssertionResponse } from '@simplewebauthn/types';
import crypto from 'node:crypto';

interface VerifyRequest {
  tenantId: string;
  response: AuthenticatorAssertionResponse;
  expectedChallenge: string;
}

interface TenantConfig {
  expectedOrigin: string; // e.g. 'https://tenant-a.identity.cloud.com'
  allowedRelatedOrigins: ReadonlySet<string>;
  expectedRpId: string;
}

export async function verifyAssertionSecure(
  req: VerifyRequest,
  tenant: TenantConfig
): Promise<{ clientDataHash: Buffer }> {
  const rawClientData = Buffer.from(req.response.clientDataJSON, 'base64url');
  const clientData = JSON.parse(rawClientData.toString('utf-8'));

  // INVARIANT 1: Strict ceremony type assertion
  if (clientData.type !== 'webauthn.get') {
    throw new Error('Disallowed clientData type: expected webauthn.get');
  }

  // INVARIANT 2: Constant-time challenge comparison
  const clientChallenge = Buffer.from(clientData.challenge, 'base64url');
  const expectedChallengeBuf = Buffer.from(req.expectedChallenge, 'base64url');
  if (
    clientChallenge.length !== expectedChallengeBuf.length ||
    !crypto.timingSafeEqual(clientChallenge, expectedChallengeBuf)
  ) {
    throw new Error('Challenge mismatch');
  }

  // INVARIANT 3: Strict origin parsing and canonical tuple validation
  const clientOriginUrl = new URL(clientData.origin);
  const canonicalClientOrigin = clientOriginUrl.origin;

  const isPrimaryOrigin = canonicalClientOrigin === tenant.expectedOrigin;
  const isRelatedOrigin = tenant.allowedRelatedOrigins.has(canonicalClientOrigin);

  if (!isPrimaryOrigin && !isRelatedOrigin) {
    throw new Error(`Unauthorized origin binding: ${canonicalClientOrigin}`);
  }

  // Compute SHA-256 clientDataHash for signature verification over authenticatorData
  const clientDataHash = crypto.createHash('sha256').update(rawClientData).digest();
  return { clientDataHash };
}
```

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: WebAuthn Level 3 ClientDataJSON Origin Binding & Related Origin Validation

WebAuthn Level 3 ClientDataJSON Origin Binding & Related Origin Validation defines an industrial-grade behavioral standard for security engineering. Enforces strict canonical origin binding verification on deserialized WebAuthn Level 3 clientDataJSON payloads in federated multi-tenant edge architectures. Precludes sub-origin relay, cross-tenant impersonation, and conditional UI credential leakage by enforcing strict exact-match origin validation, scheme/port verification, and Related Origin Requests (ROR) explicit allowlisting across reverse-proxy layers. 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: Lax or Regex-Based Origin Validation Allowing Subdomain Traversal and Cross-Tenant Credential Relay 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 DriftLax or Regex-Based Origin Validation Allowing Subdomain Traversal and Cross-Tenant Credential RelayCritical
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 parse `clientDataJSON` using a secure JSON parser and extract the canonical `origin` tuple (scheme, hostname, port) using the standard `URL` Web API.

Engineers MUST ALWAYS parse `clientDataJSON` using a secure JSON parser and extract the canonical `origin` tuple (scheme, hostname, port) using the standard `URL` Web API.

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 perform substring, suffix (`endsWith`), or loose regular-expression matching on `clientData.origin` to avoid sub-origin traversal (e.g., `tenant-a.auth.example.com.attacker.com`).

Engineers MUST NEVER perform substring, suffix (`endsWith`), or loose regular-expression matching on `clientData.origin` to avoid sub-origin traversal (e.g., `tenant-a.auth.example.com.attacker.com`).

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 validate that `clientData.origin` exactly matches the expected canonical tenant origin registered in cryptographic tenant metadata, or matches a strictly verified Related Origin Requests (ROR) set.

Services MUST validate that `clientData.origin` exactly matches the expected canonical tenant origin registered in cryptographic tenant metadata, or matches a strictly verified Related Origin Requests (ROR) set.

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 verify that `clientData.type` is strictly either `webauthn.get` or `webauthn.create` matching the operational context, and verify the cryptographic signature over `clientDataHash`.

Services MUST verify that `clientData.type` is strictly either `webauthn.get` or `webauthn.create` matching the operational context, and verify the cryptographic signature over `clientDataHash`.

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

Edge Proxies MUST NOT rewrite or forward untrusted ambient `Host` or `X-Forwarded-Host` headers as the expected origin ground truth for WebAuthn authentication ceremony assertions.

Edge Proxies MUST NOT rewrite or forward untrusted ambient `Host` or `X-Forwarded-Host` headers as the expected origin ground truth for WebAuthn authentication ceremony assertions.

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 WebAuthn Level 3 ClientDataJSON Origin Binding & Related Origin Validation critical for AI coding assistants?

Enforces strict canonical origin binding verification on deserialized WebAuthn Level 3 clientDataJSON payloads in federated multi-tenant edge architectures. Precludes sub-origin relay, cross-tenant impersonation, and conditional UI credential leakage by enforcing strict exact-match origin validation, scheme/port verification, and Related Origin Requests (ROR) explicit allowlisting across reverse-proxy layers. 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 (Lax or Regex-Based Origin Validation Allowing Subdomain Traversal and Cross-Tenant Credential Relay) 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.

1 Rule in Stack

WebAuthn