This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: fido-cxp-passkey-sync-verification

FIDO CXP Cross-Ecosystem Passkey Migration and Cryptographic Provenance Invariants

Enforces strict cryptographic integrity, Relying Party ID (RP ID) canonicalization, and key-pair consistency checks during FIDO Credential Exchange Protocol (CXP) and Credential Exchange Format (CXF) migrations. Prevents cross-origin credential harvesting, unpinned provenance tampering, and corrupted key ingestion during cross-ecosystem passkey imports.

Prohibited Anti-Pattern: Ingesting Unverified FIDO CXP Payloads Without Keypair Consistency Checks or RP ID Scoping

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FIDO CXP Cross-Ecosystem Passkey Migration and Cryptographic Provenance Invariants - Enforces strict cryptographic integrity, Relying Party ID (RP ID) canonicalization, and key-pair consistency checks during FIDO Credential Exchange Protocol (CXP) and Credential Exchange Format (CXF) migrations. Prevents cross-origin credential harvesting, unpinned provenance tampering, and corrupted key ingestion during cross-ecosystem passkey imports.
globs: src/**/passkey*.ts, src/**/cxp*.ts, src/**/cxf*.ts, src/**/credential-exchange/**/*.ts, src/**/migration/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fido-cxp-passkey-sync-verification"
---

# FIDO CXP Cross-Ecosystem Passkey Migration and Cryptographic Provenance Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Ingesting Unverified FIDO CXP Payloads Without Keypair Consistency Checks or RP ID Scoping

## System Constraints
You are a Principal Security Architect enforcing the FIDO Credential Exchange Protocol (CXP) and Format (CXF) standards. You must ensure all cross-ecosystem passkey import pipelines enforce cryptographic envelope authenticity, absolute RP ID origin scoping, strict COSE public-to-private keypair consistency verification, and zeroing of ephemeral decrypted secret buffers. Never allow unverified passkey ingestion into persistent vaults.

## Strict Guidelines
- Services MUST cryptographically verify the CXP exchange payload envelope (e.g., HPKE / JWE / COSE-Sign1) against pinned trusted-source public keys before accessing raw credential records.
- Engineers MUST ALWAYS re-derive the public key directly from the imported private key (COSE/JWK) and cryptographically assert bitwise equality against the imported credentialPublicKey.
- Engineers MUST NOT trust the relying party ID (rpId) in the import record without canonical FQDN syntax enforcement and strict scoping checks against acceptable origins.
- Components NEVER store or transmit raw private key buffers without immediate explicit zero-filling (Buffer.fill(0) / typed array clearing) after persistence in an isolated enclave or secure storage engine.
- Code SHOULD validate AAGUID (Authenticator Attestation Globally Unique Identifier) format and cross-reference known software and hardware authenticators via FIDO Metadata Service (MDS3) when provenance metadata is present.

## Bad vs Good Implementations
### FIDO CXP Import Keypair and Provenance Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code blindly trusts incoming JSON data, performs no envelope or signature verification, does not validate that the public key actually corresponds to the imported private key (allowing credential substitution or signature desync attacks), lacks RP ID origin validation, and leaves plaintext private keys unmanaged in garbage-collected memory.
```typescript
import { db } from './vaultDb';

interface UnsafeCxpCredential {
  credentialId: string;
  rpId: string;
  privateKeyJwk: Record<string, string>;
  publicKeyJwk: Record<string, string>;
  userHandle: string;
}

export async function importCxpPasskey(rawJson: string): Promise<void> {
  // Flaw 1: Blindly parsing untrusted JSON without schema or envelope verification
  const payload = JSON.parse(rawJson) as UnsafeCxpCredential;

  // Flaw 2: Blindly trusting claimed rpId without canonicalization or validation
  // Flaw 3: Storing private and public keys without validating that the private key matches the public key
  // Flaw 4: Leaving raw cryptographic keys vulnerable to heap inspection
  await db.passkeys.create({
    data: {
      credentialId: payload.credentialId,
      rpId: payload.rpId,
      privateKey: JSON.stringify(payload.privateKeyJwk),
      publicKey: JSON.stringify(payload.publicKeyJwk),
      userId: payload.userHandle,
      importedAt: new Date(),
    },
  });
}
```

#### Production Standard (Correct)
> **Standard**: The secure implementation strictly parses and bounds input with Zod, validates domain syntax for RP ID, derives the public key directly from the imported private key to verify exact mathematical pairing, safely passes the secret into a hardware/enclave-backed vault, and explicitly clears the raw private key buffer from memory using zeroing routines.
```typescript
import { createPublicKey, createPrivateKey } from 'node:crypto';
import { z } from 'zod';
import { secureZeroBuffer } from './cryptoUtils';
import { secureVault } from './vaultEngine';

const CxfRecordSchema = z.object({
  credentialId: z.string().base64url(),
  rpId: z.string().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/i),
  userHandle: z.string().base64url(),
  privateKeyJwk: z.object({
    kty: z.literal('EC'),
    crv: z.literal('P-256'),
    x: z.string().base64url(),
    y: z.string().base64url(),
    d: z.string().base64url(),
  }),
  publicKeyJwk: z.object({
    kty: z.literal('EC'),
    crv: z.literal('P-256'),
    x: z.string().base64url(),
    y: z.string().base64url(),
  }),
  aaguid: z.string().uuid().optional(),
});

type CxfRecord = z.infer<typeof CxfRecordSchema>;

export async function importCxpPasskeyVerified(
  verifiedEnvelopeBytes: Uint8Array,
  trustedSourceOrigin: string
): Promise<void> {
  const rawString = new TextDecoder().decode(verifiedEnvelopeBytes);
  const parsed = CxfRecordSchema.parse(JSON.parse(rawString));

  // 1. Enforce RP ID structural isolation and FQDN compliance
  const normalizedRpId = parsed.rpId.toLowerCase();
  if (normalizedRpId.startsWith('.') || normalizedRpId.includes('..')) {
    throw new SecurityError(`Invalid RP ID syntax: ${normalizedRpId}`);
  }

  // 2. Cryptographically assert that privateKeyJwk derives EXACTLY publicKeyJwk
  const privKeyObj = createPrivateKey({
    key: parsed.privateKeyJwk,
    format: 'jwk',
  });
  const derivedPubJwk = createPublicKey(privKeyObj).export({ format: 'jwk' });

  if (
    derivedPubJwk.x !== parsed.publicKeyJwk.x ||
    derivedPubJwk.y !== parsed.publicKeyJwk.y ||
    derivedPubJwk.crv !== parsed.publicKeyJwk.crv
  ) {
    throw new SecurityError('Cryptographic mismatch: Private key does not derive provided public key.');
  }

  // 3. Commit to secure vault using hardware/enclave boundary
  const rawSecretBytes = Buffer.from(parsed.privateKeyJwk.d, 'base64url');
  try {
    await secureVault.storePasskey({
      credentialId: parsed.credentialId,
      rpId: normalizedRpId,
      userHandle: parsed.userHandle,
      derivedPublicKeyJwk: derivedPubJwk,
      rawPrivateDKey: rawSecretBytes,
      sourceAaguid: parsed.aaguid ?? '00000000-0000-0000-0000-000000000000',
      provenanceProvenanceOrigin: trustedSourceOrigin,
    });
  } finally {
    // 4. Zero sensitive memory immediately after persistence handoff
    secureZeroBuffer(rawSecretBytes);
  }
}
```

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: FIDO CXP Cross-Ecosystem Passkey Migration and Cryptographic Provenance Invariants

FIDO CXP Cross-Ecosystem Passkey Migration and Cryptographic Provenance Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic integrity, Relying Party ID (RP ID) canonicalization, and key-pair consistency checks during FIDO Credential Exchange Protocol (CXP) and Credential Exchange Format (CXF) migrations. Prevents cross-origin credential harvesting, unpinned provenance tampering, and corrupted key ingestion during cross-ecosystem passkey imports. 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: Ingesting Unverified FIDO CXP Payloads Without Keypair Consistency Checks or RP ID Scoping 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 DriftIngesting Unverified FIDO CXP Payloads Without Keypair Consistency Checks or RP ID ScopingCritical
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

Services MUST cryptographically verify the CXP exchange payload envelope (e.g., HPKE / JWE / COSE-Sign1) against pinned trusted-source public keys before accessing raw credential records.

Services MUST cryptographically verify the CXP exchange payload envelope (e.g., HPKE / JWE / COSE-Sign1) against pinned trusted-source public keys before accessing raw credential records.

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 ALWAYS re-derive the public key directly from the imported private key (COSE/JWK) and cryptographically assert bitwise equality against the imported credentialPublicKey.

Engineers MUST ALWAYS re-derive the public key directly from the imported private key (COSE/JWK) and cryptographically assert bitwise equality against the imported credentialPublicKey.

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 trust the relying party ID (rpId) in the import record without canonical FQDN syntax enforcement and strict scoping checks against acceptable origins.

Engineers MUST NOT trust the relying party ID (rpId) in the import record without canonical FQDN syntax enforcement and strict scoping checks against acceptable origins.

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

Components NEVER store or transmit raw private key buffers without immediate explicit zero-filling (Buffer.fill(0) / typed array clearing) after persistence in an isolated enclave or secure storage engine.

Components NEVER store or transmit raw private key buffers without immediate explicit zero-filling (Buffer.fill(0) / typed array clearing) after persistence in an isolated enclave or secure storage engine.

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

Code SHOULD validate AAGUID (Authenticator Attestation Globally Unique Identifier) format and cross-reference known software and hardware authenticators via FIDO Metadata Service (MDS3) when provenance metadata is present.

Code SHOULD validate AAGUID (Authenticator Attestation Globally Unique Identifier) format and cross-reference known software and hardware authenticators via FIDO Metadata Service (MDS3) when provenance metadata is present.

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 FIDO CXP Cross-Ecosystem Passkey Migration and Cryptographic Provenance Invariants critical for AI coding assistants?

Enforces strict cryptographic integrity, Relying Party ID (RP ID) canonicalization, and key-pair consistency checks during FIDO Credential Exchange Protocol (CXP) and Credential Exchange Format (CXF) migrations. Prevents cross-origin credential harvesting, unpinned provenance tampering, and corrupted key ingestion during cross-ecosystem passkey imports. 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 (Ingesting Unverified FIDO CXP Payloads Without Keypair Consistency Checks or RP ID Scoping) 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

FIDO