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

OAuth 2.0 DPoP (RFC 9449) Ephemeral Key & Nonce Synchronization Boundary

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) standards across client application layers to eliminate token-theft and replay vulnerabilities. Mandates non-extractable WebCrypto asymmetric keys, canonicalized proof claims, and atomic single-retry nonce synchronization boundaries.

Prohibited Anti-Pattern: Persisting Extractable DPoP Private Keys to Web Storage with Unsynchronized Nonce Race Conditions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 DPoP (RFC 9449) Ephemeral Key & Nonce Synchronization Boundary - Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) standards across client application layers to eliminate token-theft and replay vulnerabilities. Mandates non-extractable WebCrypto asymmetric keys, canonicalized proof claims, and atomic single-retry nonce synchronization boundaries.
globs: src/**/{auth,crypto,api,http,network}/**/*.{ts,tsx}, lib/**/{auth,crypto,api,http}/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-dpop-ephemeral-key-nonce-sync"
---

# OAuth 2.0 DPoP (RFC 9449) Ephemeral Key & Nonce Synchronization Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Extractable DPoP Private Keys to Web Storage with Unsynchronized Nonce Race Conditions

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.0 DPoP (RFC 9449) invariants. Reject any implementation that serializes private keys to persistent storage, omits mandatory JWT header typ: 'dpop+jwt', retains URI query/fragment parameters in the 'htu' claim, or permits recursive retry loops during server-side 'use_dpop_nonce' challenge handling.

## Strict Guidelines
- Engineers MUST ALWAYS generate DPoP asymmetric key pairs (e.g., ECDSA P-256 via WebCrypto) with 'extractable: false' and maintain them strictly in-memory or within hardware-backed security modules.
- Engineers MUST NOT persist private keys to localStorage, sessionStorage, IndexedDB, or cookies under any circumstances.
- Code MUST canonicalize the 'htu' (HTTP URI) claim by stripping query parameters and URI fragments (scheme + authority + path only) and enforce uppercase 'htm' matching the HTTP request method.
- Services MUST generate a cryptographically secure, high-entropy unique identifier (UUID v4 or 128-bit random base64url) for the 'jti' claim on every single generated DPoP proof.
- Components NEVER execute recursive or uncoordinated retry loops when encountering HTTP 401/400 'use_dpop_nonce'; they MUST atomically update the shared nonce state and allow at most one replay attempt per request context.

## Bad vs Good Implementations
### RFC 9449 Compliant DPoP Proof Generator & Nonce Interceptor

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Stores sensitive keys in browser localStorage accessible to XSS, fails to mark keys as non-extractable via WebCrypto, uses symmetric HS256 instead of asymmetric DPoP proofs, leaks query parameters in the htu claim, and lacks RFC 9449 typ: 'dpop+jwt' and nonce synchronization.
```typescript
import { sign } from 'jsonwebtoken';

// ANTI-PATTERN: Extractable keys in localStorage, uncanonicalized htu, missing nonce synchronization
export async function getDPoPToken(url: string, method: string) {
  let privateKey = localStorage.getItem('dpop_private_key');
  let publicKey = localStorage.getItem('dpop_public_key');
  
  if (!privateKey) {
    // Insecure: Storing raw extractable keys in persistent web storage
    privateKey = 'raw-insecure-pem-or-secret';
    localStorage.setItem('dpop_private_key', privateKey);
  }

  // Flaw: htu contains query params, jti lacks entropy, typ header is generic JWT
  return sign(
    {
      htu: url, // Violates RFC 9449: must not include query string or hash
      htm: method,
      iat: Math.floor(Date.now() / 1000)
    },
    privateKey,
    { algorithm: 'HS256', header: { typ: 'JWT' } }
  );
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to RFC 9449 by generating non-extractable WebCrypto P-256 keys in memory, canonicalizing htu to omit query/hash components, assigning cryptographic UUID jtis, setting typ: 'dpop+jwt', and executing a single-retry nonce synchronization boundary.
```typescript
export interface DPoPKeyManager {
  getPublicKeyJWK(): Promise<JsonWebKey>;
  createProof(method: string, targetUrl: string, nonce?: string): Promise<string>;
}

export class WebCryptoDPoPManager implements DPoPKeyManager {
  private keyPair: Promise<CryptoKeyPair>;
  private currentNonce: string | null = null;

  constructor() {
    // Invariant: Non-extractable, in-memory ECDSA P-256 keypair
    this.keyPair = crypto.subtle.generateKey(
      { name: 'ECDSA', namedCurve: 'P-256' },
      false,
      ['sign', 'verify']
    );
  }

  public setNonce(nonce: string | null): void {
    this.currentNonce = nonce;
  }

  public getNonce(): string | null {
    return this.currentNonce;
  }

  public async getPublicKeyJWK(): Promise<JsonWebKey> {
    const { publicKey } = await this.keyPair;
    const jwk = await crypto.subtle.exportKey('jwk', publicKey);
    return { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
  }

  public async createProof(method: string, targetUrl: string, explicitNonce?: string): Promise<string> {
    const { privateKey } = await this.keyPair;
    const publicJwk = await this.getPublicKeyJWK();

    // RFC 9449 Invariant: Canonicalize htu (strip search & hash)
    const parsed = new URL(targetUrl);
    const htu = `${parsed.origin}${parsed.pathname}`;
    const htm = method.toUpperCase();

    const header = {
      typ: 'dpop+jwt',
      alg: 'ES256',
      jwk: publicJwk
    };

    const payload: Record<string, unknown> = {
      jti: crypto.randomUUID(),
      htm,
      htu,
      iat: Math.floor(Date.now() / 1000)
    };

    const nonceToUse = explicitNonce ?? this.currentNonce;
    if (nonceToUse) {
      payload.nonce = nonceToUse;
    }

    const enc = new TextEncoder();
    const b64Url = (bytes: Uint8Array) =>
      btoa(String.fromCharCode(...bytes))
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');

    const encodedHeader = b64Url(enc.encode(JSON.stringify(header)));
    const encodedPayload = b64Url(enc.encode(JSON.stringify(payload)));
    const signingInput = enc.encode(`${encodedHeader}.${encodedPayload}`);

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

    return `${encodedHeader}.${encodedPayload}.${b64Url(new Uint8Array(signature))}`;
  }
}

// Secure fetch wrapper handling DPoP Nonce challenge synchronization
export async function dpopFetch(
  input: string,
  init: RequestInit,
  dpopManager: WebCryptoDPoPManager
): Promise<Response> {
  const method = (init.method || 'GET').toUpperCase();
  const initialProof = await dpopManager.createProof(method, input);

  const headers = new Headers(init.headers);
  headers.set('DPoP', initialProof);

  let response = await fetch(input, { ...init, headers });

  const serverNonce = response.headers.get('DPoP-Nonce');
  if (serverNonce) {
    dpopManager.setNonce(serverNonce);
  }

  // Atomic single-retry boundary on nonce challenge
  if (response.status === 401 && serverNonce) {
    const retryProof = await dpopManager.createProof(method, input, serverNonce);
    headers.set('DPoP', retryProof);
    response = await fetch(input, { ...init, headers });
    
    const nextNonce = response.headers.get('DPoP-Nonce');
    if (nextNonce) {
      dpopManager.setNonce(nextNonce);
    }
  }

  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) Ephemeral Key & Nonce Synchronization Boundary

OAuth 2.0 DPoP (RFC 9449) Ephemeral Key & Nonce Synchronization Boundary defines an industrial-grade behavioral standard for security engineering. Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) standards across client application layers to eliminate token-theft and replay vulnerabilities. Mandates non-extractable WebCrypto asymmetric keys, canonicalized proof claims, and atomic single-retry nonce synchronization boundaries. 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: Persisting Extractable DPoP Private Keys to Web Storage with Unsynchronized Nonce Race Conditions 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 DriftPersisting Extractable DPoP Private Keys to Web Storage with Unsynchronized Nonce Race ConditionsCritical
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 asymmetric key pairs (e.g., ECDSA P-256 via WebCrypto) with 'extractable

Engineers MUST ALWAYS generate DPoP asymmetric key pairs (e.g., ECDSA P-256 via WebCrypto) with 'extractable: false' and maintain them strictly in-memory or within hardware-backed security modules.

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 NOT persist private keys to localStorage, sessionStorage, IndexedDB, or cookies under any circumstances.

Engineers MUST NOT persist private keys to localStorage, sessionStorage, IndexedDB, or cookies under any circumstances.

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 canonicalize the 'htu' (HTTP URI) claim by stripping query parameters and URI fragments (scheme + authority + path only) and enforce uppercase 'htm' matching the HTTP request method.

Code MUST canonicalize the 'htu' (HTTP URI) claim by stripping query parameters and URI fragments (scheme + authority + path only) and enforce uppercase 'htm' matching the HTTP request method.

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 generate a cryptographically secure, high-entropy unique identifier (UUID v4 or 128-bit random base64url) for the 'jti' claim on every single generated DPoP proof.

Services MUST generate a cryptographically secure, high-entropy unique identifier (UUID v4 or 128-bit random base64url) for the 'jti' claim on every single generated 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.
5

Components NEVER execute recursive or uncoordinated retry loops when encountering HTTP 401/400 'use_dpop_nonce'

Components NEVER execute recursive or uncoordinated retry loops when encountering HTTP 401/400 'use_dpop_nonce'; they MUST atomically update the shared nonce state and allow at most one replay attempt per request context.

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) Ephemeral Key & Nonce Synchronization Boundary critical for AI coding assistants?

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) standards across client application layers to eliminate token-theft and replay vulnerabilities. Mandates non-extractable WebCrypto asymmetric keys, canonicalized proof claims, and atomic single-retry nonce synchronization boundaries. 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 (Persisting Extractable DPoP Private Keys to Web Storage with Unsynchronized Nonce Race Conditions) 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