This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: rfc-9449-dpop-ephemeral-nonce-guardrail

RFC 9449 DPoP Ephemeral Proof Nonce-Clamping and Replay Prevention Guardrail

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) verification at the API gateway layer. Eliminates distributed token replay attacks by mandating cryptographic thumbprint binding, single-use proof-token jti deduplication via distributed cache, tight clock-skew clamping (max ±5 seconds), and strict ath/htm/htu claims validation.

Prohibited Anti-Pattern: Accepting Unbound Bearer Tokens or Uncached DPoP Proofs with Lenient Clock Skew

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9449 DPoP Ephemeral Proof Nonce-Clamping and Replay Prevention Guardrail - Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) verification at the API gateway layer. Eliminates distributed token replay attacks by mandating cryptographic thumbprint binding, single-use proof-token jti deduplication via distributed cache, tight clock-skew clamping (max ±5 seconds), and strict ath/htm/htu claims validation.
globs: src/middleware/**/*.{ts,js}, src/auth/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/controllers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9449-dpop-ephemeral-nonce-guardrail"
---

# RFC 9449 DPoP Ephemeral Proof Nonce-Clamping and Replay Prevention Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Unbound Bearer Tokens or Uncached DPoP Proofs with Lenient Clock Skew

## System Constraints
You are a Principal Security Architect enforcing RFC 9449 DPoP Ephemeral Proof Nonce-Clamping Guardrails. You MUST reject any OAuth 2.0 or API implementation that treats DPoP proofs as passive Bearer tokens, permits symmetric/none signature algorithms, fails to validate the access token hash (ath), allows loose clock skew (>5 seconds), or skips atomic distributed single-use jti validation.

## Strict Guidelines
- Engineers MUST ALWAYS verify that the DPoP proof header contains 'typ': 'dpop+jwt' and an embedded public key ('jwk') that uses an approved asymmetric algorithm (ES256, ES384, ES512, EdDSA, or PS256); symmetric (HS*) and 'none' algorithms MUST be explicitly rejected.
- Engineers MUST compute the SHA-256 thumbprint of the client-held public JWK ('jkt') and assert its exact match against the 'cnf.jkt' claim embedded within the sender-constrained access token.
- Engineers MUST ALWAYS validate the 'ath' (access token hash) claim within the DPoP proof by computing the base64url-encoded SHA-256 hash of the presented access token when authenticating protected resource requests.
- Services MUST atomically record and verify the uniqueness of the DPoP proof's 'jti' claim in a high-speed distributed cache (e.g., Redis via SET NX) with a TTL matching the maximum acceptable drift window; if the 'jti' was already seen, the request MUST be immediately rejected with HTTP 401 Unauthorized.
- Services MUST enforce sub-second to maximum 5-second clock skew validation on the 'iat' (issued-at) timestamp relative to gateway time, and MUST mandate a server-provided rotating 'nonce' challenge when 'iat' alone cannot guarantee freshness.
- Engineers MUST ALWAYS validate that the proof's 'htm' (HTTP method) and 'htu' (HTTP target URI normalized without query or fragment) claims match the incoming request exact values.
- Components NEVER store or persist client private keys server-side; DPoP relies entirely on asymmetric asymmetric proof-of-possession where only the client signs the proof.

## Bad vs Good Implementations
### RFC 9449 Compliant DPoP Proof & Token Verification Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The insecure implementation blindly decodes DPoP proofs without cryptographic verification against the embedded JWK, allows arbitrary replay within wide clock drifts, omits atomic distributed single-use jti checks, ignores the access token hash (ath) claim, and fails to enforce RFC 9449 cryptographic token binding.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

export async function badDpopMiddleware(req: Request, res: Response, next: NextFunction) {
  const dpopHeader = req.headers['dpop'] as string;
  const authHeader = req.headers['authorization'] as string;

  if (!dpopHeader || !authHeader) {
    return res.status(401).json({ error: 'Missing headers' });
  }

  // VULNERABILITY 1: Decoding without verifying JWK embedded signature properly
  // VULNERABILITY 2: Allowing default clock tolerances (often minutes)
  // VULNERABILITY 3: No distributed JTI replay check (vulnerable to token replay)
  // VULNERABILITY 4: Missing 'ath', 'htm', 'htu' binding
  const decodedDpop = jwt.decode(dpopHeader) as any;
  const token = authHeader.replace('DPoP ', '');
  
  if (decodedDpop.htm !== req.method) {
    return res.status(401).json({ error: 'Method mismatch' });
  }

  req.user = jwt.decode(token);
  return next();
}
```

#### Production Standard (Correct)
> **Standard**: This implementation fully enforces RFC 9449: it mandates the 'dpop+jwt' type, restricts signature algorithms to asymmetric NIST/Ed25519 suites, verifies the embedded JWK, validates strict 5-second max clock skew, enforces single-use replay protection via Redis SET NX, asserts URI/method equality, and ensures cryptographic binding between the access token and the proof via the 'ath' claim.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import type { Redis } from 'ioredis';

interface SecureDPoPOptions {
  redis: Redis;
  expectedNonceGenerator: () => Promise<string>;
  maxSkewSeconds?: number;
}

export function createDPoPVerifier({ redis, maxSkewSeconds = 5 }: SecureDPoPOptions) {
  return async function verifyDPoP(req: Request, res: Response, next: NextFunction) {
    const dpopProof = req.headers['dpop'] as string | undefined;
    const authHeader = req.headers['authorization'] as string | undefined;

    if (!dpopProof || !authHeader || !authHeader.startsWith('DPoP ')) {
      res.setHeader('WWW-Authenticate', 'DPoP error="invalid_token"');
      return res.status(401).json({ error: 'invalid_dpop_request' });
    }

    const accessToken = authHeader.slice(5).trim();

    try {
      // 1. Parse header & reject insecure algorithms
      const header = jose.decodeProtectedHeader(dpopProof);
      if (header.typ !== 'dpop+jwt' || !header.jwk) {
        return res.status(401).json({ error: 'invalid_dpop_proof_header' });
      }

      const allowedAlgs = ['ES256', 'ES384', 'ES512', 'EdDSA', 'PS256'];
      if (!header.alg || !allowedAlgs.includes(header.alg)) {
        return res.status(401).json({ error: 'unsupported_dpop_algorithm' });
      }

      // 2. Import JWK and cryptographically verify proof
      const publicKey = await jose.importJWK(header.jwk, header.alg);
      const { payload } = await jose.jwtVerify(dpopProof, publicKey, {
        algorithms: allowedAlgs,
        clockTolerance: `${maxSkewSeconds}s`,
      });

      const { jti, htm, htu, iat, ath } = payload;
      if (!jti || !htm || !htu || !iat || !ath) {
        return res.status(401).json({ error: 'missing_dpop_claims' });
      }

      // 3. Atomically check and register single-use JTI replay store
      const replayKey = `dpop:jti:${jti}`;
      const acquired = await redis.set(replayKey, '1', 'EX', maxSkewSeconds * 2, 'NX');
      if (!acquired) {
        return res.status(401).json({ error: 'dpop_proof_replayed' });
      }

      // 4. Validate HTTP Method and Target URI (normalized without query/fragment)
      const incomingHtu = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
      if (htm !== req.method.toUpperCase() || htu !== incomingHtu) {
        return res.status(401).json({ error: 'dpop_htm_htu_mismatch' });
      }

      // 5. Cryptographically bind Access Token to DPoP Proof via ath
      const computedAth = createHash('sha256').update(accessToken).digest('base64url');
      if (ath !== computedAth) {
        return res.status(401).json({ error: 'dpop_ath_mismatch' });
      }

      // 6. Compute JWK thumbprint and verify against access token cnf.jkt
      const calculatedJkt = await jose.calculateJwkThumbprint(header.jwk, 'sha256');
      // Verify access token and ensure token.cnf.jkt === calculatedJkt
      res.locals.dpopThumbprint = calculatedJkt;
      res.locals.rawAccessToken = accessToken;

      return next();
    } catch (err) {
      return res.status(401).json({ error: 'dpop_verification_failed' });
    }
  };
}
```

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: RFC 9449 DPoP Ephemeral Proof Nonce-Clamping and Replay Prevention Guardrail

RFC 9449 DPoP Ephemeral Proof Nonce-Clamping and Replay Prevention Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) verification at the API gateway layer. Eliminates distributed token replay attacks by mandating cryptographic thumbprint binding, single-use proof-token jti deduplication via distributed cache, tight clock-skew clamping (max ±5 seconds), and strict ath/htm/htu claims validation. 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: Accepting Unbound Bearer Tokens or Uncached DPoP Proofs with Lenient Clock Skew 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 DriftAccepting Unbound Bearer Tokens or Uncached DPoP Proofs with Lenient Clock SkewCritical
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 verify that the DPoP proof header contains 'typ'

Engineers MUST ALWAYS verify that the DPoP proof header contains 'typ': 'dpop+jwt' and an embedded public key ('jwk') that uses an approved asymmetric algorithm (ES256, ES384, ES512, EdDSA, or PS256); symmetric (HS*) and 'none' algorithms MUST be explicitly rejected.

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 compute the SHA-256 thumbprint of the client-held public JWK ('jkt') and assert its exact match against the 'cnf.jkt' claim embedded within the sender-constrained access token.

Engineers MUST compute the SHA-256 thumbprint of the client-held public JWK ('jkt') and assert its exact match against the 'cnf.jkt' claim embedded within the sender-constrained access token.

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 ALWAYS validate the 'ath' (access token hash) claim within the DPoP proof by computing the base64url-encoded SHA-256 hash of the presented access token when authenticating protected resource requests.

Engineers MUST ALWAYS validate the 'ath' (access token hash) claim within the DPoP proof by computing the base64url-encoded SHA-256 hash of the presented access token when authenticating protected resource requests.

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 atomically record and verify the uniqueness of the DPoP proof's 'jti' claim in a high-speed distributed cache (e.g., Redis via SET NX) with a TTL matching the maximum acceptable drift window

Services MUST atomically record and verify the uniqueness of the DPoP proof's 'jti' claim in a high-speed distributed cache (e.g., Redis via SET NX) with a TTL matching the maximum acceptable drift window; if the 'jti' was already seen, the request MUST be immediately rejected with HTTP 401 Unauthorized.

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 enforce sub-second to maximum 5-second clock skew validation on the 'iat' (issued-at) timestamp relative to gateway time, and MUST mandate a server-provided rotating 'nonce' challenge when 'iat' alone cannot guarantee freshness.

Services MUST enforce sub-second to maximum 5-second clock skew validation on the 'iat' (issued-at) timestamp relative to gateway time, and MUST mandate a server-provided rotating 'nonce' challenge when 'iat' alone cannot guarantee freshness.

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

Engineers MUST ALWAYS validate that the proof's 'htm' (HTTP method) and 'htu' (HTTP target URI normalized without query or fragment) claims match the incoming request exact values.

Engineers MUST ALWAYS validate that the proof's 'htm' (HTTP method) and 'htu' (HTTP target URI normalized without query or fragment) claims match the incoming request exact values.

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

Components NEVER store or persist client private keys server-side

Components NEVER store or persist client private keys server-side; DPoP relies entirely on asymmetric asymmetric proof-of-possession where only the client signs the proof.

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 RFC 9449 DPoP Ephemeral Proof Nonce-Clamping and Replay Prevention Guardrail critical for AI coding assistants?

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) verification at the API gateway layer. Eliminates distributed token replay attacks by mandating cryptographic thumbprint binding, single-use proof-token jti deduplication via distributed cache, tight clock-skew clamping (max ±5 seconds), and strict ath/htm/htu claims validation. 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 (Accepting Unbound Bearer Tokens or Uncached DPoP Proofs with Lenient Clock Skew) 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

RFC