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

OAuth 2.1 Sender-Constrained DPoP Nonce-Bound Token Replay Protection

Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) with dynamic server-nonce verification for OAuth 2.1 tokens across web and mobile clients. Prevents token theft and replay attacks arising from client-side XSS by cryptographically binding access tokens to non-extractable client-side asymmetric key pairs. Forbids standard ambient bearer tokens in high-assurance boundary interfaces.

Prohibited Anti-Pattern: Transmitting Unconstrained Bearer Tokens or Omitting Server-Nonce DPoP Proof Handshakes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 Sender-Constrained DPoP Nonce-Bound Token Replay Protection - Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) with dynamic server-nonce verification for OAuth 2.1 tokens across web and mobile clients. Prevents token theft and replay attacks arising from client-side XSS by cryptographically binding access tokens to non-extractable client-side asymmetric key pairs. Forbids standard ambient bearer tokens in high-assurance boundary interfaces.
globs: src/auth/**/*.{ts,tsx}, src/api/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/lib/http/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-dpop-sender-constrained-nonce-replay-guardrail"
---

# OAuth 2.1 Sender-Constrained DPoP Nonce-Bound Token Replay Protection

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting Unconstrained Bearer Tokens or Omitting Server-Nonce DPoP Proof Handshakes

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 Sender-Constrained DPoP (RFC 9449) and cryptographic anti-replay protections. All outbound authenticated requests must generate an asymmetric DPoP proof bound to the exact HTTP method, target URI, ephemeral jti, timestamp, and server-issued nonce. Never store private keys in extractable memory or localStorage; mandate non-extractable WebCrypto CryptoKeyPair instances. Ensure HTTP 401 use_dpop_nonce challenges are handled with bounded retry logic and strict header propagation.

## Strict Guidelines
- Engineers MUST ALWAYS generate DPoP proof JWTs using non-extractable WebCrypto keys (e.g., ECDSA P-256) stored in-memory or IndexedDB with { extractable: false }.
- Engineers MUST ALWAYS include standard RFC 9449 DPoP header claims: 'typ' set to 'dpop+jwt', 'alg' matching key specifications (e.g., 'ES256'), and 'jwk' holding the public key components without private parameters.
- Engineers MUST ALWAYS bind the DPoP payload claims to the canonical request: 'htm' (uppercase HTTP method), 'htu' (target URI without query or fragment parameters), 'jti' (UUIDv4/cryptographically secure random string), and 'iat' (current Unix timestamp).
- Engineers MUST capture and cache the 'DPoP-Nonce' HTTP header returned by authorization servers and resource servers, immediately injecting the latest nonce into subsequent proof JWTs.
- Code MUST handle HTTP 401 challenges returning 'use_dpop_nonce' or an updated 'DPoP-Nonce' header by re-signing the proof with the new nonce and retrying the request exactly once to prevent infinite replay loops.
- Services MUST authorize requests via the 'DPoP <access_token>' Authorization header scheme instead of the conventional 'Bearer <access_token>' scheme.
- Components NEVER store private cryptographic signing keys in localStorage, sessionStorage, or unencrypted persistent cookies.

## Bad vs Good Implementations
### DPoP HTTP Client with Nonce Negotiation and Non-Extractable WebCrypto Keys

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits standard ambient Bearer tokens vulnerable to immediate theft and replay via client-side script injection. Lacks asymmetric proof-of-possession, request URI/method binding, and server nonce anti-replay guarantees.
```typescript
// VULNERABLE: Bearer token transmitted without cryptographic proof-of-possession.
// If an attacker exploits an XSS vulnerability, the token can be exfiltrated and replayed from any machine.
export async function fetchAccountProfile(accessToken: string): Promise<Response> {
  return fetch('https://api.example.com/v1/profile', {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${accessToken}`,
      Accept: 'application/json'
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 sender-constraint logic using non-extractable WebCrypto ECDSA keys. Cryptographically binds method, URL, and dynamic anti-replay nonces while safely managing HTTP 401 nonce challenges with bounded retries.
```typescript
// SECURE: RFC 9449 DPoP Sender-Constrained Request with Dynamic Nonce Challenge Handshake
interface DPoPClientState {
  keyPair: CryptoKeyPair;
  cachedNonce?: string;
}

async function base64UrlEncode(buffer: ArrayBuffer | Uint8Array): Promise<string> {
  const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

async function createDPoPProof(
  keyPair: CryptoKeyPair,
  httpMethod: string,
  httpUrl: string,
  nonce?: string
): Promise<string> {
  const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
  const cleanJwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
  
  const header = {
    typ: 'dpop+jwt',
    alg: 'ES256',
    jwk: cleanJwk
  };

  const urlObj = new URL(httpUrl);
  const canonicalHtu = `${urlObj.origin}${urlObj.pathname}`;

  const payload = {
    jti: crypto.randomUUID(),
    htm: httpMethod.toUpperCase(),
    htu: canonicalHtu,
    iat: Math.floor(Date.now() / 1000),
    ...(nonce ? { nonce } : {})
  };

  const textEncoder = new TextEncoder();
  const encodedHeader = await base64UrlEncode(textEncoder.encode(JSON.stringify(header)));
  const encodedPayload = await base64UrlEncode(textEncoder.encode(JSON.stringify(payload)));
  const signingInput = `${encodedHeader}.${encodedPayload}`;

  const signature = await crypto.subtle.sign(
    { name: 'ECDSA', hash: 'SHA-256' },
    keyPair.privateKey,
    textEncoder.encode(signingInput)
  );

  return `${signingInput}.${await base64UrlEncode(signature)}`;
}

export async function secureDPoPFetch(
  url: string,
  options: RequestInit,
  accessToken: string,
  state: DPoPClientState,
  retryCount = 0
): Promise<Response> {
  const method = options.method ?? 'GET';
  const proof = await createDPoPProof(state.keyPair, method, url, state.cachedNonce);

  const headers = new Headers(options.headers);
  headers.set('Authorization', `DPoP ${accessToken}`);
  headers.set('DPoP', proof);

  const response = await fetch(url, { ...options, headers });

  const returnedNonce = response.headers.get('DPoP-Nonce');
  if (returnedNonce) {
    state.cachedNonce = returnedNonce;
  }

  // Handle initial authorization server or resource server nonce requirement (RFC 9449 Section 4.3)
  if (response.status === 401 && retryCount === 0 && returnedNonce) {
    return secureDPoPFetch(url, options, accessToken, state, retryCount + 1);
  }

  return response;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OAuth 2.1 Sender-Constrained DPoP Nonce-Bound Token Replay Protection

OAuth 2.1 Sender-Constrained DPoP Nonce-Bound Token Replay Protection defines an industrial-grade behavioral standard for security engineering. Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) with dynamic server-nonce verification for OAuth 2.1 tokens across web and mobile clients. Prevents token theft and replay attacks arising from client-side XSS by cryptographically binding access tokens to non-extractable client-side asymmetric key pairs. Forbids standard ambient bearer tokens in high-assurance boundary interfaces. 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: Transmitting Unconstrained Bearer Tokens or Omitting Server-Nonce DPoP Proof Handshakes 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 DriftTransmitting Unconstrained Bearer Tokens or Omitting Server-Nonce DPoP Proof HandshakesCritical
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 DPoP proof JWTs using non-extractable WebCrypto keys (e.g., ECDSA P-256) stored in-memory or IndexedDB with { extractable

Engineers MUST ALWAYS generate DPoP proof JWTs using non-extractable WebCrypto keys (e.g., ECDSA P-256) stored in-memory or IndexedDB with { extractable: false }.

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 include standard RFC 9449 DPoP header claims

Engineers MUST ALWAYS include standard RFC 9449 DPoP header claims: 'typ' set to 'dpop+jwt', 'alg' matching key specifications (e.g., 'ES256'), and 'jwk' holding the public key components without private 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.
3

Engineers MUST ALWAYS bind the DPoP payload claims to the canonical request

Engineers MUST ALWAYS bind the DPoP payload claims to the canonical request: 'htm' (uppercase HTTP method), 'htu' (target URI without query or fragment parameters), 'jti' (UUIDv4/cryptographically secure random string), and 'iat' (current Unix timestamp).

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 capture and cache the 'DPoP-Nonce' HTTP header returned by authorization servers and resource servers, immediately injecting the latest nonce into subsequent proof JWTs.

Engineers MUST capture and cache the 'DPoP-Nonce' HTTP header returned by authorization servers and resource servers, immediately injecting the latest nonce into subsequent proof JWTs.

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

Code MUST handle HTTP 401 challenges returning 'use_dpop_nonce' or an updated 'DPoP-Nonce' header by re-signing the proof with the new nonce and retrying the request exactly once to prevent infinite replay loops.

Code MUST handle HTTP 401 challenges returning 'use_dpop_nonce' or an updated 'DPoP-Nonce' header by re-signing the proof with the new nonce and retrying the request exactly once to prevent infinite replay loops.

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

Services MUST authorize requests via the 'DPoP <access_token>' Authorization header scheme instead of the conventional 'Bearer <access_token>' scheme.

Services MUST authorize requests via the 'DPoP <access_token>' Authorization header scheme instead of the conventional 'Bearer <access_token>' scheme.

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 private cryptographic signing keys in localStorage, sessionStorage, or unencrypted persistent cookies.

Components NEVER store private cryptographic signing keys in localStorage, sessionStorage, or unencrypted persistent cookies.

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 Sender-Constrained DPoP Nonce-Bound Token Replay Protection critical for AI coding assistants?

Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) with dynamic server-nonce verification for OAuth 2.1 tokens across web and mobile clients. Prevents token theft and replay attacks arising from client-side XSS by cryptographically binding access tokens to non-extractable client-side asymmetric key pairs. Forbids standard ambient bearer tokens in high-assurance boundary interfaces. 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 (Transmitting Unconstrained Bearer Tokens or Omitting Server-Nonce DPoP Proof Handshakes) 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