This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth21-dpop-replay-barrier-guardrail

OAuth 2.1 DPoP Cryptographic Proof and Distributed Nonce Replay Barrier

Enforces strict RFC 9449 OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) verification across all resource servers. Validates cryptographic thumbprint binding (jkt/ath), enforces bounded clock skew (±60s), and guarantees atomicity of single-use nonces and JTI claims via distributed atomic sliding-window cache primitives to eliminate replay and token export vulnerabilities.

Prohibited Anti-Pattern: Stateless DPoP Proof Verification Without Atomic Distributed Nonce / JTI Tracking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 DPoP Cryptographic Proof and Distributed Nonce Replay Barrier - Enforces strict RFC 9449 OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) verification across all resource servers. Validates cryptographic thumbprint binding (jkt/ath), enforces bounded clock skew (±60s), and guarantees atomicity of single-use nonces and JTI claims via distributed atomic sliding-window cache primitives to eliminate replay and token export vulnerabilities.
globs: src/auth/**/*.ts, src/middleware/**/*.ts, src/security/**/*.ts, src/gateway/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth21-dpop-replay-barrier-guardrail"
---

# OAuth 2.1 DPoP Cryptographic Proof and Distributed Nonce Replay Barrier

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stateless DPoP Proof Verification Without Atomic Distributed Nonce / JTI Tracking

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 Demonstrating Proof-of-Possession (DPoP, RFC 9449) compliance. You must mandate strict cryptographic sender-constraining on every protected endpoint. Never permit DPoP proofs to be accepted without verifying JWT header parameters (typ='dpop+jwt'), public key thumbprint binding (jkt), hash matching of the access token (ath), strict HTTP method and URI matching (htm, htu), bounded lifetime (iat within 60s), and distributed atomic single-use tracking of jti identifiers.

## Strict Guidelines
- Services MUST extract the DPoP proof from the HTTP 'DPoP' header and verify that the JOSE header contains 'typ': 'dpop+jwt' and an embedded JWK ('jwk') without private key material.
- Services MUST compute the SHA-256 thumbprint (RFC 7638) of the public key in 'jwk' and strictly verify it matches the 'cnf.jkt' claim embedded within the sender-constrained access token.
- Services MUST verify that the proof's 'htm' and 'htu' claims strictly match the incoming HTTP request method and canonical request URL (ignoring query strings and fragments).
- Services MUST verify the 'ath' (access token hash) claim in the DPoP proof against the SHA-256 base64url-encoded digest of the presented Bearer/DPoP access token.
- Services MUST enforce an atomic check-and-set operation (e.g., Redis 'SET key val NX EX ttl') on the DPoP 'jti' claim across a distributed cluster; requests MUST be rejected with HTTP 401/400 if the 'jti' has already been recorded within the sliding window.
- Engineers MUST NOT rely on in-memory Node.js Maps or Sets for DPoP JTI tracking in distributed, multi-instance, or serverless deployments.
- Services MUST reject DPoP proofs where 'iat' deviates by more than 60 seconds from the server's NTP-synchronized clock.
- When nonces are enforced by the authorization server or resource server, the 'nonce' claim MUST match the server-issued ephemeral challenge and immediately cycle.

## Bad vs Good Implementations
### Validate DPoP Proof with Atomic Distributed Replay Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decodes the DPoP JWT without cryptographic signature verification against the embedded JWK, omits 'typ', 'ath', 'htm', and 'htu' validation, and uses an in-memory Set that permits immediate replay attacks across horizontally scaled instances.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

const seenJtis = new Set<string>();

export async function badDpopMiddleware(req: Request, res: Response, next: NextFunction) {
  const dpopHeader = req.headers['dpop'] as string;
  if (!dpopHeader) return res.status(401).json({ error: 'missing_dpop' });

  // INSECURE: Decodes without verifying signature against embedded jwk,
  // uses local in-memory Set (fails horizontally), ignores ath/htm/htu checks
  const decoded = jwt.decode(dpopHeader) as any;
  if (seenJtis.has(decoded.jti)) {
    return res.status(401).json({ error: 'token_replayed' });
  }
  seenJtis.add(decoded.jti);
  return next();
}
```

#### Production Standard (Correct)
> **Standard**: Implements full RFC 9449 compliance: validates JOSE 'typ', imports the sender's public key, verifies digital signature and bounded lifetime, checks 'htm' and 'htu' consistency, verifies 'ath' against the presented token, and executes an atomic SET NX distributed barrier in Redis to guarantee single-use JTI replay protection.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import { importJWK, jwtVerify, calculateJwkThumbprint } from 'jose';
import type { Redis } from 'ioredis';

interface AuthenticatedDPoPRequest extends Request {
  dpopJkt?: string;
}

export function createDPoPMiddleware(redis: Redis, maxClockSkewSeconds = 60) {
  return async (req: AuthenticatedDPoPRequest, res: Response, next: NextFunction): Promise<void> => {
    const dpopHeader = req.header('dpop');
    const authHeader = req.header('authorization');

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

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

    try {
      const [rawHeader] = dpopHeader.split('.');
      const headerJson = JSON.parse(Buffer.from(rawHeader, 'base64url').toString('utf8'));

      if (headerJson.typ !== 'dpop+jwt' || !headerJson.jwk) {
        res.status(400).json({ error: 'invalid_dpop_header' });
        return;
      }

      const publicKey = await importJWK(headerJson.jwk, headerJson.alg);
      const { payload } = await jwtVerify(dpopHeader, publicKey, {
        typ: 'dpop+jwt',
        algorithms: ['ES256', 'ES384', 'ES512', 'PS256', 'EdDSA'],
        clockTolerance: `${maxClockSkewSeconds}s`,
      });

      const expectedHtu = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
      if (payload.htm !== req.method || payload.htu !== expectedHtu) {
        res.status(400).json({ error: 'invalid_dpop_target' });
        return;
      }

      const expectedAth = createHash('sha256').update(rawAccessToken).digest('base64url');
      if (payload.ath !== expectedAth) {
        res.status(400).json({ error: 'invalid_token_binding' });
        return;
      }

      if (!payload.jti) {
        res.status(400).json({ error: 'missing_jti' });
        return;
      }

      // Atomic single-use replay barrier in distributed cache
      const cacheKey = `dpop:jti:${payload.jti}`;
      const acquired = await redis.set(cacheKey, '1', 'EX', maxClockSkewSeconds * 2, 'NX');
      if (!acquired) {
        res.status(401).setHeader('WWW-Authenticate', 'DPoP error="use_dpop_nonce"').json({ error: 'dpop_proof_replayed' });
        return;
      }

      req.dpopJkt = await calculateJwkThumbprint(headerJson.jwk, 'sha256');
      next();
    } catch (err) {
      res.status(401).json({ error: 'invalid_dpop_proof', message: (err as Error).message });
    }
  };
}
```

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: OAuth 2.1 DPoP Cryptographic Proof and Distributed Nonce Replay Barrier

OAuth 2.1 DPoP Cryptographic Proof and Distributed Nonce Replay Barrier defines an industrial-grade behavioral standard for security engineering. Enforces strict RFC 9449 OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) verification across all resource servers. Validates cryptographic thumbprint binding (jkt/ath), enforces bounded clock skew (±60s), and guarantees atomicity of single-use nonces and JTI claims via distributed atomic sliding-window cache primitives to eliminate replay and token export vulnerabilities. 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: Stateless DPoP Proof Verification Without Atomic Distributed Nonce / JTI Tracking 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 DriftStateless DPoP Proof Verification Without Atomic Distributed Nonce / JTI TrackingCritical
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 extract the DPoP proof from the HTTP 'DPoP' header and verify that the JOSE header contains 'typ'

Services MUST extract the DPoP proof from the HTTP 'DPoP' header and verify that the JOSE header contains 'typ': 'dpop+jwt' and an embedded JWK ('jwk') without private key material.

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

Services MUST compute the SHA-256 thumbprint (RFC 7638) of the public key in 'jwk' and strictly verify it matches the 'cnf.jkt' claim embedded within the sender-constrained access token.

Services MUST compute the SHA-256 thumbprint (RFC 7638) of the public key in 'jwk' and strictly verify it matches 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

Services MUST verify that the proof's 'htm' and 'htu' claims strictly match the incoming HTTP request method and canonical request URL (ignoring query strings and fragments).

Services MUST verify that the proof's 'htm' and 'htu' claims strictly match the incoming HTTP request method and canonical request URL (ignoring query strings and fragments).

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 the 'ath' (access token hash) claim in the DPoP proof against the SHA-256 base64url-encoded digest of the presented Bearer/DPoP access token.

Services MUST verify the 'ath' (access token hash) claim in the DPoP proof against the SHA-256 base64url-encoded digest of the presented Bearer/DPoP 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.
5

Services MUST enforce an atomic check-and-set operation (e.g., Redis 'SET key val NX EX ttl') on the DPoP 'jti' claim across a distributed cluster

Services MUST enforce an atomic check-and-set operation (e.g., Redis 'SET key val NX EX ttl') on the DPoP 'jti' claim across a distributed cluster; requests MUST be rejected with HTTP 401/400 if the 'jti' has already been recorded within the sliding window.

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 NOT rely on in-memory Node.js Maps or Sets for DPoP JTI tracking in distributed, multi-instance, or serverless deployments.

Engineers MUST NOT rely on in-memory Node.js Maps or Sets for DPoP JTI tracking in distributed, multi-instance, or serverless deployments.

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

Services MUST reject DPoP proofs where 'iat' deviates by more than 60 seconds from the server's NTP-synchronized clock.

Services MUST reject DPoP proofs where 'iat' deviates by more than 60 seconds from the server's NTP-synchronized clock.

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

When nonces are enforced by the authorization server or resource server, the 'nonce' claim MUST match the server-issued ephemeral challenge and immediately cycle.

When nonces are enforced by the authorization server or resource server, the 'nonce' claim MUST match the server-issued ephemeral challenge and immediately cycle.

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 OAuth 2.1 DPoP Cryptographic Proof and Distributed Nonce Replay Barrier critical for AI coding assistants?

Enforces strict RFC 9449 OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) verification across all resource servers. Validates cryptographic thumbprint binding (jkt/ath), enforces bounded clock skew (±60s), and guarantees atomicity of single-use nonces and JTI claims via distributed atomic sliding-window cache primitives to eliminate replay and token export vulnerabilities. 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 (Stateless DPoP Proof Verification Without Atomic Distributed Nonce / JTI Tracking) 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

OAuth