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

OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Dynamic Nonce Lease Enforcement

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) invariants by binding tokens to non-extractable client asymmetric key pairs. Mandates dynamic server-issued nonce rotation, single-use proof generation with cryptographically secure jti tracking, and mandatory access token hash (ath) verification to eliminate token replay and exfiltration.

Prohibited Anti-Pattern: Reusing Cached DPoP Proofs or Relying on Unbound Bearer Tokens Without Nonce Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Dynamic Nonce Lease Enforcement - Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) invariants by binding tokens to non-extractable client asymmetric key pairs. Mandates dynamic server-issued nonce rotation, single-use proof generation with cryptographically secure jti tracking, and mandatory access token hash (ath) verification to eliminate token replay and exfiltration.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/lib/api/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-dpop-rfc9449-nonce-replay-standard"
---

# OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Dynamic Nonce Lease Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reusing Cached DPoP Proofs or Relying on Unbound Bearer Tokens Without Nonce Verification

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.0 DPoP (RFC 9449) Nonce-Lease Replay Prevention. Enforce non-extractable asymmetric keys, per-request ephemeral DPoP proof generation, strict HTTP method/URI binding, access token hash (ath) validation, and automatic retry handling for server-issued DPoP-Nonce updates.

## Strict Guidelines
- Engineers MUST ALWAYS generate a fresh, unique DPoP proof JWT for every HTTP request using non-extractable client keys (WebCrypto or hardware-backed HSM/Secure Enclave).
- Engineers MUST NEVER persist or cache DPoP proof JWT strings across multiple HTTP requests; every proof MUST contain an ephemeral cryptographically random `jti` and fresh `iat`.
- Code MUST handle HTTP 401 with `error="use_dpop_nonce"` by extracting the server's `DPoP-Nonce` header, updating the in-memory nonce lease, and regenerating a new proof exactly once.
- Services validating DPoP proofs on resource servers MUST verify that `ath` matches the base64url-encoded SHA-256 digest of the presented access token.
- Components MUST validate that `htm` (HTTP method) and `htu` (HTTP URI without query or fragment) in the DPoP proof exactly match the current request parameters.

## Bad vs Good Implementations
### RFC 9449 DPoP Client Request Handler with Dynamic Nonce-Lease Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reuses a static DPoP proof across requests violating `jti` uniqueness and clock freshness (`iat`). Fails to handle server `DPoP-Nonce` rotation (HTTP 401 `use_dpop_nonce`), and mistakenly uses the `Bearer` authorization scheme instead of `DPoP`, negating sender-constraining security.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Reusing a static pre-computed DPoP proof across requests,
// ignoring DPoP-Nonce challenges, and transmitting raw Bearer tokens.
let cachedDPoPProof: string | null = null;

export async function requestResource(url: string, accessToken: string) {
  if (!cachedDPoPProof) {
    // Incorrectly signs proof once and caches it permanently
    cachedDPoPProof = 'eyJhbGciOiJFUzI1NiIsInR5cCI6ImRwb3Arand0In0...static';
  }

  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${accessToken}`, // Flaw: Bearer instead of DPoP
      'DPoP': cachedDPoPProof
    }
  });

  return response.json();
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to RFC 9449: generates a fresh cryptographic proof per request using non-extractable keys, sanitizes URI components (`htu`), binds the `ath` digest to the token, injects unique `jti`, and transparently catches `use_dpop_nonce` challenges to rotate nonces and retry safely.
```typescript
import { calculateJwkThumbprint, SignJWT, generateKeyPair } from 'jose';

interface DPoPContext {
  keyPair: CryptoKeyPair;
  currentNonce?: string;
}

async function createDPoPProof(
  keyPair: CryptoKeyPair,
  httpMethod: string,
  httpUrl: string,
  accessToken?: string,
  nonce?: string
): Promise<string> {
  const cleanUrl = new URL(httpUrl);
  cleanUrl.search = '';
  cleanUrl.hash = '';

  const publicJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
  delete publicJwk.ext;
  delete publicJwk.key_ops;

  let ath: string | undefined;
  if (accessToken) {
    const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(accessToken));
    ath = Buffer.from(hash).toString('base64url');
  }

  const jwt = new SignJWT({
    htm: httpMethod.toUpperCase(),
    htu: cleanUrl.toString(),
    ...(ath ? { ath } : {}),
    ...(nonce ? { nonce } : {})
  })
    .setProtectedHeader({ alg: 'ES256', typ: 'dpop+jwt', jwk: publicJwk })
    .setIssuedAt()
    .setJti(crypto.randomUUID());

  return jwt.sign(keyPair.privateKey);
}

export async function secureDPoPFetch(
  ctx: DPoPContext,
  inputUrl: string,
  init: RequestInit,
  accessToken: string
): Promise<Response> {
  const method = init.method || 'GET';
  
  const executeRequest = async (nonce?: string) => {
    const proof = await createDPoPProof(ctx.keyPair, method, inputUrl, accessToken, nonce);
    const headers = new Headers(init.headers);
    headers.set('Authorization', `DPoP ${accessToken}`);
    headers.set('DPoP', proof);
    return fetch(inputUrl, { ...init, headers });
  };

  let response = await executeRequest(ctx.currentNonce);

  // Handle dynamic server nonce lease challenge (RFC 9449 Section 4.3)
  if (response.status === 401) {
    const wwwAuth = response.headers.get('WWW-Authenticate') || '';
    const serverNonce = response.headers.get('DPoP-Nonce');
    
    if (serverNonce && wwwAuth.includes('error="use_dpop_nonce"')) {
      ctx.currentNonce = serverNonce;
      response = await executeRequest(ctx.currentNonce);
    }
  }

  return response;
}
```

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.0 DPoP (RFC 9449) Cryptographic Proof & Dynamic Nonce Lease Enforcement

OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Dynamic Nonce Lease Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) invariants by binding tokens to non-extractable client asymmetric key pairs. Mandates dynamic server-issued nonce rotation, single-use proof generation with cryptographically secure jti tracking, and mandatory access token hash (ath) verification to eliminate token replay and exfiltration. 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: Reusing Cached DPoP Proofs or Relying on Unbound Bearer Tokens Without Nonce 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 DriftReusing Cached DPoP Proofs or Relying on Unbound Bearer Tokens Without Nonce VerificationCritical
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 generate a fresh, unique DPoP proof JWT for every HTTP request using non-extractable client keys (WebCrypto or hardware-backed HSM/Secure Enclave).

Engineers MUST ALWAYS generate a fresh, unique DPoP proof JWT for every HTTP request using non-extractable client keys (WebCrypto or hardware-backed HSM/Secure Enclave).

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 NEVER persist or cache DPoP proof JWT strings across multiple HTTP requests

Engineers MUST NEVER persist or cache DPoP proof JWT strings across multiple HTTP requests; every proof MUST contain an ephemeral cryptographically random `jti` and fresh `iat`.

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

Code MUST handle HTTP 401 with `error="use_dpop_nonce"` by extracting the server's `DPoP-Nonce` header, updating the in-memory nonce lease, and regenerating a new proof exactly once.

Code MUST handle HTTP 401 with `error="use_dpop_nonce"` by extracting the server's `DPoP-Nonce` header, updating the in-memory nonce lease, and regenerating a new proof exactly once.

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 validating DPoP proofs on resource servers MUST verify that `ath` matches the base64url-encoded SHA-256 digest of the presented access token.

Services validating DPoP proofs on resource servers MUST verify that `ath` matches the base64url-encoded SHA-256 digest of the presented 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

Components MUST validate that `htm` (HTTP method) and `htu` (HTTP URI without query or fragment) in the DPoP proof exactly match the current request parameters.

Components MUST validate that `htm` (HTTP method) and `htu` (HTTP URI without query or fragment) in the DPoP proof exactly match the current request parameters.

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.0 DPoP (RFC 9449) Cryptographic Proof & Dynamic Nonce Lease Enforcement critical for AI coding assistants?

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) invariants by binding tokens to non-extractable client asymmetric key pairs. Mandates dynamic server-issued nonce rotation, single-use proof generation with cryptographically secure jti tracking, and mandatory access token hash (ath) verification to eliminate token replay and exfiltration. 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 (Reusing Cached DPoP Proofs or Relying on Unbound Bearer Tokens Without Nonce 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

OAuth