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

RFC 9449 DPoP Edge Nonce Replay-Proof Synchronization Boundary

Enforces sub-millisecond distributed nonce validation and cryptographic binding verification for sender-constrained OAuth 2.0 DPoP access tokens across multi-region stateless edge gateways. Mandates atomic consumption, single-use guarantees, and high-entropy sliding-window nonce generation to completely prevent replay attacks across globally replicated datastores.

Prohibited Anti-Pattern: Stateless In-Memory or Asynchronous Nonce Caching Allowing Cross-Region DPoP Replay Windows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9449 DPoP Edge Nonce Replay-Proof Synchronization Boundary - Enforces sub-millisecond distributed nonce validation and cryptographic binding verification for sender-constrained OAuth 2.0 DPoP access tokens across multi-region stateless edge gateways. Mandates atomic consumption, single-use guarantees, and high-entropy sliding-window nonce generation to completely prevent replay attacks across globally replicated datastores.
globs: src/security/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9449-dpop-edge-nonce-replay-boundary"
---

# RFC 9449 DPoP Edge Nonce Replay-Proof Synchronization Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stateless In-Memory or Asynchronous Nonce Caching Allowing Cross-Region DPoP Replay Windows

## System Constraints
You are a Principal Security Architect enforcing RFC 9449 (OAuth 2.0 Demonstrating Proof of Possession at the Application Layer) across multi-region edge gateways. You must ensure all DPoP proof assertions are verified with strict single-use nonce validation, sub-millisecond atomic state invalidation, public-key thumbprint binding (ath), and synchronous replay protection before fulfilling upstream requests.

## Strict Guidelines
- Engineers MUST ALWAYS enforce atomic compare-and-swap or transactional consumption of the DPoP nonce in distributed storage prior to fulfilling the downstream resource request.
- Engineers MUST ALWAYS verify that the DPoP proof's 'htm' (HTTP method) and 'htu' (HTTP target URI normalized without query/fragment) match the inbound request exactly.
- Engineers MUST ALWAYS validate the 'ath' (access token hash) claim via base64url-encoded SHA-256 of the presented bearer/sender-constrained credential whenever a resource access token is accompanied by a DPoP proof.
- Engineers MUST NOT validate DPoP nonces using local node memory or eventually consistent caches that permit multi-region cross-edge race replay windows.
- Services MUST respond with HTTP 401, 'use_dpop_nonce' error code, and a fresh cryptographically signed DPoP-Nonce header immediately when a nonce is missing, invalid, or already consumed.
- Nonce tokens MUST be generated using cryptographically secure PRNGs with at least 128 bits of entropy and bounded by a strict sliding-window TTL not exceeding 60 seconds.

## Bad vs Good Implementations
### Sub-Millisecond Atomic Distributed Nonce Consumption and Replay Shield

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Vulnerable to distributed replay attacks: local in-memory sets cannot synchronize across stateless edge regions, non-atomic verification introduces a race window, and the 'ath' (access token hash) and signature invariants are ignored.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'crypto';

// ANTI-PATTERN: In-memory set or non-atomic check-then-set prone to multi-region race conditions
const localNonceCache = new Set<string>();

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

  // Decode DPoP JWT payload without verifying crypto or atomic nonce
  const [, payloadB64] = dpopHeader.split('.');
  const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf8'));

  // Check-then-act race vulnerability across edge instances
  if (localNonceCache.has(payload.nonce)) {
    return res.status(401).setHeader('DPoP-Nonce', 'new-nonce').json({ error: 'use_dpop_nonce' });
  }
  localNonceCache.add(payload.nonce);
  next();
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 compliance by atomically consuming distributed nonces in Redis, verifying full cryptographic signatures using JOSE, checking matching HTTP method/target URI invariants, and enforcing timing-safe validation of the 'ath' hash.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash, timingSafeEqual, randomBytes } from 'crypto';
import { importJWK, jwtVerify } from 'jose';
import type { Redis } from 'ioredis';

interface EdgeDPoPConfig {
  redis: Redis;
  nonceTtlSeconds: number;
}

export function createDPoPVerifier({ redis, nonceTtlSeconds = 60 }: EdgeDPoPConfig) {
  return async function verifyDPoP(req: Request, res: Response, next: NextFunction): Promise<void> {
    const dpopHeader = req.headers['dpop'] as string | undefined;
    const authHeader = req.headers['authorization'] as string | undefined;

    const generateNonce = (): string => randomBytes(24).toString('base64url');

    if (!dpopHeader) {
      res.setHeader('DPoP-Nonce', generateNonce());
      res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'Missing DPoP header' });
      return;
    }

    try {
      const [headerB64] = dpopHeader.split('.');
      const protectedHeader = JSON.parse(Buffer.from(headerB64, 'base64url').toString('utf8'));
      
      if (protectedHeader.typ !== 'dpop+jwt' || !protectedHeader.jwk) {
        throw new Error('Invalid DPoP header typ or missing jwk');
      }

      const jwk = await importJWK(protectedHeader.jwk, protectedHeader.alg);
      const expectedHtu = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
      
      const { payload } = await jwtVerify(dpopHeader, jwk, {
        algorithms: ['ES256', 'EdDSA', 'RS256'],
        maxTokenAge: '60s'
      });

      if (payload.htm !== req.method || payload.htu !== expectedHtu) {
        res.status(400).json({ error: 'invalid_dpop_proof', error_description: 'HTTP method or URI mismatch' });
        return;
      }

      if (typeof payload.nonce !== 'string') {
        res.setHeader('DPoP-Nonce', generateNonce());
        res.status(401).json({ error: 'use_dpop_nonce', error_description: 'Nonce required' });
        return;
      }

      // RFC 9449 Section 4.3: Distributed atomic consumption via Redis Lua (Single Round-Trip)
      // Keys: dpop:nonce:{nonce} | Returns 1 if valid & consumed, 0 if replayed or missing
      const nonceConsumptionScript = `
        local key = KEYS[1]
        if redis.call('EXISTS', key) == 1 then
          redis.call('DEL', key)
          return 1
        else
          return 0
        end
      `;
      
      const consumed = await redis.eval(nonceConsumptionScript, 1, `dpop:nonce:${payload.nonce}`);
      if (consumed !== 1) {
        res.setHeader('DPoP-Nonce', generateNonce());
        res.status(401).json({ error: 'use_dpop_nonce', error_description: 'Nonce invalid or replayed' });
        return;
      }

      if (authHeader && authHeader.startsWith('DPoP ')) {
        const token = authHeader.slice(5).trim();
        const expectedAth = createHash('sha256').update(token).digest('base64url');
        if (!payload.ath || typeof payload.ath !== 'string' || !timingSafeEqual(Buffer.from(payload.ath), Buffer.from(expectedAth))) {
          res.status(400).json({ error: 'invalid_grant', error_description: 'Access token hash (ath) mismatch' });
          return;
        }
      }

      next();
    } catch (err: unknown) {
      res.setHeader('DPoP-Nonce', generateNonce());
      res.status(401).json({ error: 'invalid_dpop_proof', error_description: (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: RFC 9449 DPoP Edge Nonce Replay-Proof Synchronization Boundary

RFC 9449 DPoP Edge Nonce Replay-Proof Synchronization Boundary defines an industrial-grade behavioral standard for security engineering. Enforces sub-millisecond distributed nonce validation and cryptographic binding verification for sender-constrained OAuth 2.0 DPoP access tokens across multi-region stateless edge gateways. Mandates atomic consumption, single-use guarantees, and high-entropy sliding-window nonce generation to completely prevent replay attacks across globally replicated datastores. 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 In-Memory or Asynchronous Nonce Caching Allowing Cross-Region DPoP Replay Windows 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 In-Memory or Asynchronous Nonce Caching Allowing Cross-Region DPoP Replay WindowsCritical
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 enforce atomic compare-and-swap or transactional consumption of the DPoP nonce in distributed storage prior to fulfilling the downstream resource request.

Engineers MUST ALWAYS enforce atomic compare-and-swap or transactional consumption of the DPoP nonce in distributed storage prior to fulfilling the downstream resource request.

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 verify that the DPoP proof's 'htm' (HTTP method) and 'htu' (HTTP target URI normalized without query/fragment) match the inbound request exactly.

Engineers MUST ALWAYS verify that the DPoP proof's 'htm' (HTTP method) and 'htu' (HTTP target URI normalized without query/fragment) match the inbound request exactly.

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 via base64url-encoded SHA-256 of the presented bearer/sender-constrained credential whenever a resource access token is accompanied by a DPoP proof.

Engineers MUST ALWAYS validate the 'ath' (access token hash) claim via base64url-encoded SHA-256 of the presented bearer/sender-constrained credential whenever a resource access token is accompanied by a DPoP 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.
4

Engineers MUST NOT validate DPoP nonces using local node memory or eventually consistent caches that permit multi-region cross-edge race replay windows.

Engineers MUST NOT validate DPoP nonces using local node memory or eventually consistent caches that permit multi-region cross-edge race replay windows.

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 respond with HTTP 401, 'use_dpop_nonce' error code, and a fresh cryptographically signed DPoP-Nonce header immediately when a nonce is missing, invalid, or already consumed.

Services MUST respond with HTTP 401, 'use_dpop_nonce' error code, and a fresh cryptographically signed DPoP-Nonce header immediately when a nonce is missing, invalid, or already consumed.

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

Nonce tokens MUST be generated using cryptographically secure PRNGs with at least 128 bits of entropy and bounded by a strict sliding-window TTL not exceeding 60 seconds.

Nonce tokens MUST be generated using cryptographically secure PRNGs with at least 128 bits of entropy and bounded by a strict sliding-window TTL not exceeding 60 seconds.

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 Edge Nonce Replay-Proof Synchronization Boundary critical for AI coding assistants?

Enforces sub-millisecond distributed nonce validation and cryptographic binding verification for sender-constrained OAuth 2.0 DPoP access tokens across multi-region stateless edge gateways. Mandates atomic consumption, single-use guarantees, and high-entropy sliding-window nonce generation to completely prevent replay attacks across globally replicated datastores. 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 In-Memory or Asynchronous Nonce Caching Allowing Cross-Region DPoP Replay Windows) 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