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

OAuth 2.0 DPoP (RFC 9449) Hardware Enclave Assertion & Distributed Nonce Sync Standard

Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) bound to non-exportable hardware-enclave keys across distributed edge architectures. Enforces server-side stateless cryptographic nonce generation, distributed replay prevention, strict HTTP method/URI verification, and access token hash (ath) validation. Eliminates token interception vulnerabilities, cross-region replay attacks, and asymmetric key extraction risks.

Prohibited Anti-Pattern: Accepting Bearer tokens without cryptographic key-binding or validating DPoP proofs using single-node in-memory nonces vulnerable to edge desynchronization and replay.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 DPoP (RFC 9449) Hardware Enclave Assertion & Distributed Nonce Sync Standard - Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) bound to non-exportable hardware-enclave keys across distributed edge architectures. Enforces server-side stateless cryptographic nonce generation, distributed replay prevention, strict HTTP method/URI verification, and access token hash (ath) validation. Eliminates token interception vulnerabilities, cross-region replay attacks, and asymmetric key extraction risks.
globs: src/middleware/**/*.{ts,tsx}, src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/edge/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/dpop-rfc9449-hardware-enclave-nonce-sync"
---

# OAuth 2.0 DPoP (RFC 9449) Hardware Enclave Assertion & Distributed Nonce Sync Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Bearer tokens without cryptographic key-binding or validating DPoP proofs using single-node in-memory nonces vulnerable to edge desynchronization and replay.

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.0 DPoP (RFC 9449) and Hardware-Enclave Nonce Synchronization standards. Mandate asymmetric cryptographic binding of tokens to client-held private keys isolated within hardware enclaves (TPM, Secure Enclave, HSM, WebCrypto non-extractable keys). Enforce stateless, cryptographically signed edge nonces to prevent distributed replay attacks without requiring inter-region database roundtrips. Ensure strict validation of ath, htm, htu, iat, and jti claims.

## Strict Guidelines
- Engineers MUST ALWAYS isolate DPoP private keys within non-extractable hardware enclaves (WebCrypto `extractable: false`, Secure Enclave, or HSM-backed TPM providers).
- Engineers MUST NOT permit symmetric signing algorithms (e.g., HS256) or unverified 'alg' headers; only NIST-approved asymmetric algorithms (ES256, ES384, Ed25519) are permitted.
- Edge gateways MUST issue and validate cryptographically signed or AEAD-encrypted nonces containing an embedded timestamp and edge cluster signature to guarantee stateless cross-edge synchronization.
- Services MUST validate that the DPoP proof's 'ath' (Access Token Hash) matches the base64url-encoded SHA-256 hash of the presented access token.
- Edge gateways MUST enforce strict HTTP request matching by validating that the 'htm' matches the normalized uppercase HTTP method and 'htu' matches the fully qualified request URI excluding query and fragment components.
- Components NEVER accept DPoP proof tokens with an 'iat' timestamp deviating more than 60 seconds from gateway epoch or with an already observed 'jti' within the active time window.

## Bad vs Good Implementations
### Edge Gateway DPoP RFC 9449 Proof & Distributed Nonce Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example uses a single-node in-memory Set for nonces, which instantly allows replay attacks across distributed edge gateways. It fails to verify the asymmetric enclave public key against the JWT signature, omits the mandatory 'ath' (access token hash) validation, and uses static/unauthenticated nonces.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// Anti-pattern: In-memory nonce cache fails across distributed edge instances;
// private keys are software-extractable; no 'ath' validation; unverified URI normalization.
const usedNonces = new Set<string>();

export async function insecureDPoPMiddleware(req: Request, res: Response, next: NextFunction) {
  const dpopHeader = req.headers['dpop'] as string;
  const authHeader = req.headers['authorization'] as string;

  if (!dpopHeader || !authHeader) {
    return res.status(401).json({ error: 'invalid_dpop_proof' });
  }

  // Flaw: Accepts any decoded token without validating non-extractable enclave JWK
  const decoded = jwt.decode(dpopHeader, { complete: true });
  const nonce = decoded?.payload && typeof decoded.payload === 'object' ? decoded.payload.nonce : null;

  // Flaw: Single-node in-memory store allows replay across other edge regions
  if (!nonce || usedNonces.has(nonce)) {
    return res.status(401).set('DPoP-Nonce', 'static-nonce-123').json({ error: 'use_dpop_nonce' });
  }

  usedNonces.add(nonce);
  // Flaw: Ignores 'ath' matching against Bearer token and does not verify htu/htm strictly
  return next();
}
```

#### Production Standard (Correct)
> **Standard**: This implementation fully enforces RFC 9449: it generates and validates cryptographically signed stateless nonces verifiable across edge regions without centralized DB writes, imports and verifies the public key from the enclave proof, ensures the algorithm is restricted to asymmetric curves (ES256/ES384/EdDSA), validates normalized 'htm' and 'htu', binds the access token via base64url SHA-256 'ath', and guarantees anti-replay using an atomic distributed cache SETNX on the 'jti'.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash, createHmac, timingSafeEqual } from 'crypto';
import * as jose from 'jose';

const NONCE_SECRET = Buffer.from(process.env.DPOP_NONCE_SECRET || '', 'hex');
const NONCE_EXPIRY_MS = 60_000; // 60 seconds
const JTI_TTL_SECONDS = 120;

interface EdgeDistributedCache {
  setNx(key: string, ttl: number): Promise<boolean>;
}
declare const distributedReplayCache: EdgeDistributedCache;

export function generateStatelessEdgeNonce(): string {
  const now = Date.now().toString();
  const signature = createHmac('sha256', NONCE_SECRET).update(now).digest('base64url');
  return `${now}.${signature}`;
}

export function verifyStatelessEdgeNonce(nonce: string): boolean {
  const [timestampStr, signature] = nonce.split('.');
  if (!timestampStr || !signature) return false;

  const issuedAt = parseInt(timestampStr, 10);
  if (Number.isNaN(issuedAt) || Date.now() - issuedAt > NONCE_EXPIRY_MS || Date.now() < issuedAt - 5000) {
    return false;
  }

  const expectedSig = createHmac('sha256', NONCE_SECRET).update(timestampStr).digest('base64url');
  return timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSig));
}

export async function edgeDPoPVerifier(req: Request, res: Response, next: NextFunction) {
  const dpopProof = req.headers['dpop'] as string | undefined;
  const authHeader = req.headers['authorization'] as string | undefined;

  if (!dpopProof || !authHeader || !authHeader.startsWith('DPoP ')) {
    res.setHeader('DPoP-Nonce', generateStatelessEdgeNonce());
    return res.status(401).json({ error: 'invalid_token', error_description: 'DPoP proof required' });
  }

  const accessToken = authHeader.substring(5).trim();

  try {
    // 1. Decode header to extract ephemeral public key embedded by hardware enclave
    const header = jose.decodeProtectedHeader(dpopProof);
    if (header.typ !== 'dpop+jwt' || !header.jwk || !['ES256', 'ES384', 'EdDSA'].includes(header.alg || '')) {
      throw new Error('Unsupported DPoP key algorithm or typ header');
    }

    const clientPublicKey = await jose.importJWK(header.jwk, header.alg);

    // 2. Verify signature and claims (iat, exp)
    const { payload } = await jose.jwtVerify(dpopProof, clientPublicKey, {
      algorithms: ['ES256', 'ES384', 'EdDSA'],
      clockTolerance: '60s',
    });

    // 3. Verify HTTP Method and Normalized HTTP URI
    const fullUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
    if (payload.htm !== req.method.toUpperCase() || payload.htu !== fullUrl) {
      throw new Error('HTTP Method or URI mismatch in DPoP proof');
    }

    // 4. Verify Distributed Stateless Nonce
    if (typeof payload.nonce !== 'string' || !verifyStatelessEdgeNonce(payload.nonce)) {
      res.setHeader('DPoP-Nonce', generateStatelessEdgeNonce());
      return res.status(401).json({ error: 'use_dpop_nonce', error_description: 'Invalid or expired nonce' });
    }

    // 5. Verify Access Token Hash (ath)
    const computedAth = createHash('sha256').update(accessToken).digest('base64url');
    if (payload.ath !== computedAth) {
      throw new Error('Access token hash (ath) mismatch');
    }

    // 6. Distributed anti-replay check on JTI
    if (typeof payload.jti !== 'string') {
      throw new Error('Missing jti claim');
    }
    const isNew = await distributedReplayCache.setNx(`dpop:jti:${payload.jti}`, JTI_TTL_SECONDS);
    if (!isNew) {
      throw new Error('Replayed DPoP proof token (jti already observed)');
    }

    return next();
  } catch (err: unknown) {
    res.setHeader('DPoP-Nonce', generateStatelessEdgeNonce());
    return res.status(401).json({
      error: 'invalid_dpop_proof',
      error_description: err instanceof Error ? err.message : 'Invalid assertion'
    });
  }
}
```

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) Hardware Enclave Assertion & Distributed Nonce Sync Standard

OAuth 2.0 DPoP (RFC 9449) Hardware Enclave Assertion & Distributed Nonce Sync Standard defines an industrial-grade behavioral standard for security engineering. Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) bound to non-exportable hardware-enclave keys across distributed edge architectures. Enforces server-side stateless cryptographic nonce generation, distributed replay prevention, strict HTTP method/URI verification, and access token hash (ath) validation. Eliminates token interception vulnerabilities, cross-region replay attacks, and asymmetric key extraction risks. 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: Accepting Bearer tokens without cryptographic key-binding or validating DPoP proofs using single-node in-memory nonces vulnerable to edge desynchronization and replay. 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 DriftAccepting Bearer tokens without cryptographic key-binding or validating DPoP proofs using single-node in-memory nonces vulnerable to edge desynchronization and replay.Critical
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 isolate DPoP private keys within non-extractable hardware enclaves (WebCrypto `extractable

Engineers MUST ALWAYS isolate DPoP private keys within non-extractable hardware enclaves (WebCrypto `extractable: false`, Secure Enclave, or HSM-backed TPM providers).

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 permit symmetric signing algorithms (e.g., HS256) or unverified 'alg' headers

Engineers MUST NOT permit symmetric signing algorithms (e.g., HS256) or unverified 'alg' headers; only NIST-approved asymmetric algorithms (ES256, ES384, Ed25519) are permitted.

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

Edge gateways MUST issue and validate cryptographically signed or AEAD-encrypted nonces containing an embedded timestamp and edge cluster signature to guarantee stateless cross-edge synchronization.

Edge gateways MUST issue and validate cryptographically signed or AEAD-encrypted nonces containing an embedded timestamp and edge cluster signature to guarantee stateless cross-edge synchronization.

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 validate that the DPoP proof's 'ath' (Access Token Hash) matches the base64url-encoded SHA-256 hash of the presented access token.

Services MUST validate that the DPoP proof's 'ath' (Access Token Hash) matches the base64url-encoded SHA-256 hash 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

Edge gateways MUST enforce strict HTTP request matching by validating that the 'htm' matches the normalized uppercase HTTP method and 'htu' matches the fully qualified request URI excluding query and fragment components.

Edge gateways MUST enforce strict HTTP request matching by validating that the 'htm' matches the normalized uppercase HTTP method and 'htu' matches the fully qualified request URI excluding query and fragment components.

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 DPoP proof tokens with an 'iat' timestamp deviating more than 60 seconds from gateway epoch or with an already observed 'jti' within the active time window.

Components NEVER accept DPoP proof tokens with an 'iat' timestamp deviating more than 60 seconds from gateway epoch or with an already observed 'jti' within the active time window.

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) Hardware Enclave Assertion & Distributed Nonce Sync Standard critical for AI coding assistants?

Mandates RFC 9449 Demonstrating Proof-of-Possession (DPoP) bound to non-exportable hardware-enclave keys across distributed edge architectures. Enforces server-side stateless cryptographic nonce generation, distributed replay prevention, strict HTTP method/URI verification, and access token hash (ath) validation. Eliminates token interception vulnerabilities, cross-region replay attacks, and asymmetric key extraction risks. 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 (Accepting Bearer tokens without cryptographic key-binding or validating DPoP proofs using single-node in-memory nonces vulnerable to edge desynchronization and replay.) 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