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

RFC 9449 DPoP Ephemeral Cryptographic Proof-of-Possession Enforcement

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the Application Layer to cryptographically bind OAuth 2.1 access and refresh tokens to client-held asymmetric key pairs. Private keys MUST be non-extractable and ephemeral, generated within isolated hardware or WebCrypto subsystems to prevent exfiltration. All outbound requests and resource verifications MUST strictly validate HTTP method ('htm'), HTTP URI ('htu'), access token hash ('ath'), unique token ID ('jti'), and server-issued nonces to eliminate replay attacks.

Prohibited Anti-Pattern: Bearer Token Degradation and Insecure DPoP Proof Construction with Extractable Keys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9449 DPoP Ephemeral Cryptographic Proof-of-Possession Enforcement - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the Application Layer to cryptographically bind OAuth 2.1 access and refresh tokens to client-held asymmetric key pairs. Private keys MUST be non-extractable and ephemeral, generated within isolated hardware or WebCrypto subsystems to prevent exfiltration. All outbound requests and resource verifications MUST strictly validate HTTP method ('htm'), HTTP URI ('htu'), access token hash ('ath'), unique token ID ('jti'), and server-issued nonces to eliminate replay attacks.
globs: src/**/*.{ts,tsx,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9449-dpop-ephemeral-key-guardrail"
---

# RFC 9449 DPoP Ephemeral Cryptographic Proof-of-Possession Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Bearer Token Degradation and Insecure DPoP Proof Construction with Extractable Keys

## System Constraints
You are a Principal Security Architect enforcing the RFC 9449 DPoP (Demonstrating Proof-of-Possession at the Application Layer) standard across all OAuth 2.1 authentication and resource-access layers. Mandate that every access token request and resource server interaction utilizes asymmetric cryptographic key binding. Never permit static, exportable, or shared private keys. Require mandatory SHA-256 hashing of access tokens ('ath') in resource requests, strictly enforce server-directed nonce challenges ('use_dpop_nonce'), and ensure replay protection using strictly monotonic or cryptographically unique jti tracking.

## Strict Guidelines
- Engineers MUST ALWAYS generate DPoP asymmetric key pairs using WebCrypto ('SubtleCrypto') or native hardware APIs with 'extractable: false' (e.g., ECDSA with P-256 or Ed25519).
- Engineers MUST NOT store private keys in browser local storage, cookies, session storage, or any unhardened file system layer.
- Code MUST include the 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query and fragment) claims in every generated DPoP proof JWT.
- Services MUST enforce server-provided 'DPoP-Nonce' challenges and automatically retry exactly once upon receiving HTTP 401 with an 'use_dpop_nonce' error response.
- Code MUST compute and include the 'ath' (Access Token Hash) claim in DPoP proofs when presenting a DPoP-bound access token to a protected resource.
- Components NEVER accept Bearer authentication fallback when RFC 9449 DPoP configuration is active for the client profile.

## Bad vs Good Implementations
### Vulnerable Client Request: Exportable Private Key and Incomplete DPoP Proof Claims

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The private key is raw and extractable, the authorization scheme falls back to Bearer, the 'ath' claim is omitted (allowing stolen access tokens to be re-bound), the URI is un-normalized, and server nonces are completely ignored.
```typescript
import { sign } from 'jsonwebtoken';

// ANTI-PATTERN: Private key is extractable and stored insecurely in memory or storage
const insecurePrivateKey = '-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg...\n-----END PRIVATE KEY-----';

export async function callProtectedResource(url: string, accessToken: string) {
  // Insecure: Hand-rolled DPoP proof missing 'ath', hardcoded method, no nonce tracking
  const dpopPayload = {
    jti: Math.random().toString(),
    htm: 'GET',
    htu: url, // May contain un-normalized query params/fragments
    iat: Math.floor(Date.now() / 1000)
  };

  const dpopProof = sign(dpopPayload, insecurePrivateKey, { algorithm: 'ES256' });

  return fetch(url, {
    headers: {
      Authorization: `Bearer ${accessToken}`, // Anti-pattern: Sending 'Bearer' instead of 'DPoP'
      DPoP: dpopProof
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 fully: non-extractable WebCrypto key, accurate 'htu' URI normalization, calculated 'ath' SHA-256 digest, standard 'DPoP' authorization scheme, and automatic retry upon server nonce challenge.
```typescript
interface DPoPKeyPair {
  publicKey: CryptoKey;
  privateKey: CryptoKey;
  publicJwk: JsonWebKey;
}

let clientKeyCache: DPoPKeyPair | null = null;
let lastServerNonce: string | null = null;

async function getOrCreateDPoPKeyPair(): Promise<DPoPKeyPair> {
  if (!clientKeyCache) {
    const pair = await crypto.subtle.generateKey(
      { name: 'ECDSA', namedCurve: 'P-256' },
      false, // Invariant: extractable MUST be false
      ['sign']
    );
    const publicJwk = await crypto.subtle.exportKey('jwk', pair.publicKey);
    clientKeyCache = { publicKey: pair.publicKey, privateKey: pair.privateKey, publicJwk };
  }
  return clientKeyCache;
}

function base64UrlEncode(data: Uint8Array | string): string {
  const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
  let binary = '';
  bytes.forEach((b) => (binary += String.fromCharCode(b)));
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

export async function createDPoPProof(
  method: string,
  targetUrl: string,
  accessToken?: string
): Promise<string> {
  const { privateKey, publicJwk } = await getOrCreateDPoPKeyPair();
  const parsed = new URL(targetUrl);
  const normalizedHtu = `${parsed.protocol}//${parsed.host}${parsed.pathname}`;

  const header = {
    typ: 'dpop+jwt',
    alg: 'ES256',
    jwk: { kty: publicJwk.kty, crv: publicJwk.crv, x: publicJwk.x, y: publicJwk.y }
  };

  let ath: string | undefined;
  if (accessToken) {
    const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(accessToken));
    ath = base64UrlEncode(new Uint8Array(hashBuffer));
  }

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

  const encodedHeader = base64UrlEncode(JSON.stringify(header));
  const encodedPayload = base64UrlEncode(JSON.stringify(payload));
  const message = `${encodedHeader}.${encodedPayload}`;

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

  return `${message}.${base64UrlEncode(new Uint8Array(signature))}`;
}

export async function dpopFetch(url: string, init: RequestInit = {}, accessToken: string): Promise<Response> {
  const method = init.method || 'GET';
  let proof = await createDPoPProof(method, url, accessToken);

  let response = await fetch(url, {
    ...init,
    headers: {
      ...init.headers,
      Authorization: `DPoP ${accessToken}`,
      DPoP: proof
    }
  });

  // Handle server-issued nonce challenge
  const returnedNonce = response.headers.get('DPoP-Nonce');
  if (returnedNonce) {
    lastServerNonce = returnedNonce;
  }

  if (response.status === 401 && returnedNonce) {
    proof = await createDPoPProof(method, url, accessToken);
    response = await fetch(url, {
      ...init,
      headers: {
        ...init.headers,
        Authorization: `DPoP ${accessToken}`,
        DPoP: proof
      }
    });
  }

  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: RFC 9449 DPoP Ephemeral Cryptographic Proof-of-Possession Enforcement

RFC 9449 DPoP Ephemeral Cryptographic Proof-of-Possession Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the Application Layer to cryptographically bind OAuth 2.1 access and refresh tokens to client-held asymmetric key pairs. Private keys MUST be non-extractable and ephemeral, generated within isolated hardware or WebCrypto subsystems to prevent exfiltration. All outbound requests and resource verifications MUST strictly validate HTTP method ('htm'), HTTP URI ('htu'), access token hash ('ath'), unique token ID ('jti'), and server-issued nonces to eliminate replay attacks. 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: Bearer Token Degradation and Insecure DPoP Proof Construction with Extractable Keys 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 DriftBearer Token Degradation and Insecure DPoP Proof Construction with Extractable KeysCritical
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 using WebCrypto ('SubtleCrypto') or native hardware APIs with 'extractable

Engineers MUST ALWAYS generate DPoP asymmetric key pairs using WebCrypto ('SubtleCrypto') or native hardware APIs with 'extractable: false' (e.g., ECDSA with P-256 or Ed25519).

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 store private keys in browser local storage, cookies, session storage, or any unhardened file system layer.

Engineers MUST NOT store private keys in browser local storage, cookies, session storage, or any unhardened file system layer.

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 include the 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query and fragment) claims in every generated DPoP proof JWT.

Code MUST include the 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query and fragment) claims in every generated DPoP proof JWT.

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 enforce server-provided 'DPoP-Nonce' challenges and automatically retry exactly once upon receiving HTTP 401 with an 'use_dpop_nonce' error response.

Services MUST enforce server-provided 'DPoP-Nonce' challenges and automatically retry exactly once upon receiving HTTP 401 with an 'use_dpop_nonce' error response.

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 compute and include the 'ath' (Access Token Hash) claim in DPoP proofs when presenting a DPoP-bound access token to a protected resource.

Code MUST compute and include the 'ath' (Access Token Hash) claim in DPoP proofs when presenting a DPoP-bound access token to a protected resource.

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

Components NEVER accept Bearer authentication fallback when RFC 9449 DPoP configuration is active for the client profile.

Components NEVER accept Bearer authentication fallback when RFC 9449 DPoP configuration is active for the client profile.

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 Ephemeral Cryptographic Proof-of-Possession Enforcement critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the Application Layer to cryptographically bind OAuth 2.1 access and refresh tokens to client-held asymmetric key pairs. Private keys MUST be non-extractable and ephemeral, generated within isolated hardware or WebCrypto subsystems to prevent exfiltration. All outbound requests and resource verifications MUST strictly validate HTTP method ('htm'), HTTP URI ('htu'), access token hash ('ath'), unique token ID ('jti'), and server-issued nonces to eliminate replay attacks. 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 (Bearer Token Degradation and Insecure DPoP Proof Construction with Extractable Keys) 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