This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: passkeys-webauthn-fido2-standard

Passkeys & WebAuthn FIDO2 Passwordless Authentication Standard

Enterprise authentication standard for Passkeys and WebAuthn FIDO2. Mandates cryptographic challenge generation, signature replay counter validation, attestation verification, and secure user-handle management using @simplewebauthn.

Prohibited Anti-Pattern: AI stores unverified WebAuthn public keys in plaintext and omits cryptographic challenge verification.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Passkeys & WebAuthn FIDO2 Passwordless Authentication Standard - Enterprise authentication standard for Passkeys and WebAuthn FIDO2. Mandates cryptographic challenge generation, signature replay counter validation, attestation verification, and secure user-handle management using @simplewebauthn.
globs: **/*passkey*.ts, **/*auth*.ts, **/*webauthn*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/passkeys-webauthn-fido2-standard"
---

# Passkeys & WebAuthn FIDO2 Passwordless Authentication Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: AI stores unverified WebAuthn public keys in plaintext and omits cryptographic challenge verification.

## System Constraints
You are a cryptography and authentication security architect. When implementing WebAuthn/Passkeys, NEVER invent custom cryptographic protocols or skip challenge verification. Always use established libraries (e.g. @simplewebauthn/server and @simplewebauthn/browser), verify registration/authentication challenges on the server, check user verification flags, and validate the credential counter to detect cloned authenticator tokens.

## Strict Guidelines
- Generate random, cryptographically secure challenges on the server and store them in a short-lived session with an expiration timeout.
- Verify registration responses using verifyRegistrationResponse() with matching expectedOrigin and expectedRPID.
- Verify authentication assertions and check that the counter value is strictly greater than the previously saved counter to detect authenticator cloning.
- Always set userVerification: 'preferred' or 'required' to mandate biometric or PIN verification.

## Bad vs Good Implementations
### Server-Side WebAuthn Authentication Verification vs Unverified Public Key Accepts

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Vulnerable to signature replay attacks, phishing on spoofed origins, and cloned authenticator tokens.
```typescript
// ANTI-PATTERN: Blindly trusting client public key signature without challenge check!
app.post("/api/passkey/login", async (req, res) => {
  const { credentialId, signature } = req.body;
  // CRITICAL VULNERABILITY: No challenge verification, no origin check, no counter validation!
  const user = await db.user.findFirst({ where: { passkeyId: credentialId } });
  if (user) return res.json({ token: createJwt(user) }); // Replay attack trivial!
});
```

#### Production Standard (Correct)
> **Standard**: Performs full cryptographic signature verification, origin matching, and monotonic counter checks conforming to FIDO2 standards.
```typescript
// PRODUCTION STANDARD: @simplewebauthn/server Challenge & Counter Verification
import { verifyAuthenticationResponse } from "@simplewebauthn/server";

export async function verifyPasskeyLogin(userId: string, body: any, sessionChallenge: string) {
  const userPasskey = await db.passkey.findUnique({ where: { id: body.id, userId } });
  if (!userPasskey) throw new Error("Passkey credential not registered");

  const verification = await verifyAuthenticationResponse({
    response: body,
    expectedChallenge: sessionChallenge,
    expectedOrigin: process.env.RP_ORIGIN!,
    expectedRPID: process.env.RP_ID!,
    credential: {
      id: userPasskey.id,
      publicKey: Buffer.from(userPasskey.publicKey, "base64"),
      counter: userPasskey.counter,
      transports: userPasskey.transports,
    },
  });

  if (!verification.verified || !verification.authenticationInfo) {
    throw new Error("WebAuthn authentication assertion verification failed");
  }

  // Update counter in database to prevent cloned authenticator replays
  await db.passkey.update({
    where: { id: userPasskey.id },
    data: { counter: verification.authenticationInfo.newCounter },
  });

  return true;
}
```

### Client-Side Browser Passkey Trigger

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Throws unhandled DOMExceptions across diverse browser vendors and iOS/Android passkey sync layers.
```typescript
// ANTI-PATTERN: Raw navigator.credentials.get without polyfills
navigator.credentials.get({ publicKey: opts });
```

#### Production Standard (Correct)
> **Standard**: Normalizes base64url array buffers cleanly across Safari, Chrome, and Android native credential managers.
```typescript
// PRODUCTION STANDARD: @simplewebauthn/browser startAuthentication
import { startAuthentication } from "@simplewebauthn/browser";

const authResp = await startAuthentication(serverOptions);
await api.post("/api/passkey/verify", authResp);
```

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: Passkeys & WebAuthn FIDO2 Passwordless Authentication Standard

Passkeys & WebAuthn FIDO2 Passwordless Authentication Standard defines an industrial-grade behavioral standard for security engineering. Enterprise authentication standard for Passkeys and WebAuthn FIDO2. Mandates cryptographic challenge generation, signature replay counter validation, attestation verification, and secure user-handle management using @simplewebauthn. 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: AI stores unverified WebAuthn public keys in plaintext and omits cryptographic challenge verification. 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 DriftAI stores unverified WebAuthn public keys in plaintext and omits cryptographic challenge verification.Critical
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

Generate random, cryptographically secure challenges on the server and store them in a short-lived session with an expiration timeout.

Generate random, cryptographically secure challenges on the server and store them in a short-lived session with an expiration timeout.

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

Verify registration responses using verifyRegistrationResponse() with matching expectedOrigin and expectedRPID.

Verify registration responses using verifyRegistrationResponse() with matching expectedOrigin and expectedRPID.

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

Verify authentication assertions and check that the counter value is strictly greater than the previously saved counter to detect authenticator cloning.

Verify authentication assertions and check that the counter value is strictly greater than the previously saved counter to detect authenticator cloning.

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

Always set userVerification

Always set userVerification: 'preferred' or 'required' to mandate biometric or PIN verification.

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 Passkeys & WebAuthn FIDO2 Passwordless Authentication Standard critical for AI coding assistants?

Enterprise authentication standard for Passkeys and WebAuthn FIDO2. Mandates cryptographic challenge generation, signature replay counter validation, attestation verification, and secure user-handle management using @simplewebauthn. 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 (AI stores unverified WebAuthn public keys in plaintext and omits cryptographic challenge verification.) 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

Passkeys