This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: fapi2-dpop-nonce-refresh-boundary-invariants

FAPI 2.0 DPoP Sender-Constrained Nonce Refresh Boundary & Anti-Replay Guardrail

Enforces FAPI 2.0 and RFC 9449 Demonstrating Proof-of-Possession (DPoP) cryptographic sender-constraining and atomic nonce renegotiation across distributed microservices. Mandates single-attempt nonce boundary retry semantics, fresh cryptographically secure JTI generation on every retry, SHA-256 access token hash (ath) binding, and distributed JTI replay defense under clock skew.

Prohibited Anti-Pattern: Replaying Static DPoP Proofs with Stale JTIs Across Nonce Refreshes and Omitting Token Hash Binding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FAPI 2.0 DPoP Sender-Constrained Nonce Refresh Boundary & Anti-Replay Guardrail - Enforces FAPI 2.0 and RFC 9449 Demonstrating Proof-of-Possession (DPoP) cryptographic sender-constraining and atomic nonce renegotiation across distributed microservices. Mandates single-attempt nonce boundary retry semantics, fresh cryptographically secure JTI generation on every retry, SHA-256 access token hash (ath) binding, and distributed JTI replay defense under clock skew.
globs: src/auth/**/*.ts, src/middleware/**/*.ts, src/gateway/**/*.ts, src/clients/**/*.ts, src/security/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fapi2-dpop-nonce-refresh-boundary-invariants"
---

# FAPI 2.0 DPoP Sender-Constrained Nonce Refresh Boundary & Anti-Replay Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Replaying Static DPoP Proofs with Stale JTIs Across Nonce Refreshes and Omitting Token Hash Binding

## System Constraints
You are a Principal Security Architect specializing in FAPI 2.0 Security Profile and RFC 9449 specifications. Enforce strict DPoP (Demonstrating Proof-of-Possession) sender-constraining invariants across all HTTP clients, gateways, and authorization microservices. Defend against token exportability, replay attacks under clock drift, and unbounded retry cascades. Reject any code that reuses DPoP proof JWTs, fails to recalculate JTIs upon nonce challenge, misses the 'ath' claim on resource requests, or allows infinite 401 retry loops.

## Strict Guidelines
- Clients MUST generate a unique, cryptographically random 'jti' (UUIDv4 or 128-bit CSPRNG) for every DPoP proof; proofs MUST NEVER be cached or re-sent across HTTP requests.
- Clients MUST enforce an atomic, maximum 1-retry boundary when receiving HTTP 401 with 'WWW-Authenticate: DPoP error="use_dpop_nonce"'; infinite retry loops or retries without a fresh DPoP-Nonce header MUST immediately fail.
- Clients MUST regenerate the DPoP signature from scratch during a nonce challenge retry, embedding the newly supplied 'DPoP-Nonce', a fresh 'iat' timestamp, a new 'jti', and an exact SHA-256 base64url-encoded 'ath' (access token hash).
- Resource Servers and Gateways MUST validate that the 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query and fragment) strictly match the incoming request envelope.
- Resource Servers MUST verify the 'ath' claim against the presented Bearer/DPoP access token using SHA-256 to prevent token substitution attacks.
- Services MUST reject DPoP proof timestamps ('iat') skewed beyond a strict ±60 second boundary and MUST store observed (jti, client_id) tuples in a distributed cache (e.g., Redis) with a TTL matching the skew window to guarantee single-use replay protection.

## Bad vs Good Implementations
### Client-Side DPoP Nonce Challenge Handler with Atomic Retry Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reuses static DPoP proofs across requests, reuses the 'jti' value during nonce challenge retries, omits the mandatory 'ath' claim for protected resource requests, and lacks a guard against infinite 401 retry amplification loops.
```typescript
import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';

// ANTI-PATTERN: Cached proof reuse, infinite 401 loops, missing 'ath', reused jti on retry
let cachedDPoPProof: string | null = null;

export function setupInsecureDPoPClient(client: AxiosInstance, privateKey: string, accessToken: string) {
  client.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    if (!cachedDPoPProof) {
      // Creating proof once and reusing it - violates RFC 9449 per-request uniqueness
      cachedDPoPProof = signJwt({ jti: 'static-id', htm: config.method, htu: config.url });
    }
    config.headers.set('DPoP', cachedDPoPProof);
    config.headers.set('Authorization', `DPoP ${accessToken}`);
    return config;
  });

  client.interceptors.response.use(undefined, async (error: AxiosError) => {
    // Vulnerable: Blind retry on 401 causes infinite loop; sends identical static proof
    if (error.response?.status === 401) {
      const newNonce = error.response.headers['dpop-nonce'];
      if (newNonce) {
        // Re-signing with the SAME static JTI and failing to bind 'ath'
        cachedDPoPProof = signJwt({ jti: 'static-id', nonce: newNonce });
        return client.request(error.config!);
      }
    }
    return Promise.reject(error);
  });
}

declare function signJwt(payload: Record<string, unknown>): string;
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 and FAPI 2.0 strict sender-constraining: normalizes the HTU URI, computes the SHA-256 base64url 'ath' hash, assigns a fresh CSPRNG 'jti' per signed JWT, inspects the 401 WWW-Authenticate header explicitly for 'use_dpop_nonce', and rigidly clamps retries to at most one recursion.
```typescript
import { createHash, randomUUID } from 'node:crypto';
import { KeyLike, SignJWT } from 'jose';

interface DPoPRequestOptions {
  url: string;
  method: string;
  accessToken: string;
  privateKey: KeyLike;
  publicKeyJwk: Record<string, unknown>;
  cachedNonce?: string;
}

function computeAth(accessToken: string): string {
  return createHash('sha256').update(accessToken, 'ascii').digest('base64url');
}

async function createDPoPProof(
  method: string,
  url: string,
  privateKey: KeyLike,
  publicKeyJwk: Record<string, unknown>,
  accessToken: string,
  nonce?: string
): Promise<string> {
  const normalizedHtu = new URL(url).origin + new URL(url).pathname;
  
  const builder = new SignJWT({
    htm: method.toUpperCase(),
    htu: normalizedHtu,
    ath: computeAth(accessToken)
  })
    .setProtectedHeader({ alg: 'PS256', typ: 'dpop+jwt', jwk: publicKeyJwk })
    .setIssuedAt()
    .setJti(randomUUID()); // Invariant: Fresh cryptographically random JTI on every generation

  if (nonce) {
    builder.setClaim('nonce', nonce);
  }

  return builder.sign(privateKey);
}

export async function fapi2DPoPFetch(
  opts: DPoPRequestOptions,
  hasRetriedNonce = false
): Promise<Response> {
  const proof = await createDPoPProof(
    opts.method,
    opts.url,
    opts.privateKey,
    opts.publicKeyJwk,
    opts.accessToken,
    opts.cachedNonce
  );

  const response = await fetch(opts.url, {
    method: opts.method,
    headers: {
      'Authorization': `DPoP ${opts.accessToken}`,
      'DPoP': proof,
      'Accept': 'application/json'
    }
  });

  // Handle FAPI 2.0 DPoP Nonce Refresh Boundary
  if (response.status === 401 && !hasRetriedNonce) {
    const authHeader = response.headers.get('WWW-Authenticate') || '';
    const serverNonce = response.headers.get('DPoP-Nonce');

    if (authHeader.includes('error="use_dpop_nonce"') && serverNonce) {
      // Enforce strict single-retry boundary with newly provisioned nonce and clean JTI
      return fapi2DPoPFetch(
        { ...opts, cachedNonce: serverNonce },
        true // Prevent recursive re-entry
      );
    }
  }

  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: FAPI 2.0 DPoP Sender-Constrained Nonce Refresh Boundary & Anti-Replay Guardrail

FAPI 2.0 DPoP Sender-Constrained Nonce Refresh Boundary & Anti-Replay Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces FAPI 2.0 and RFC 9449 Demonstrating Proof-of-Possession (DPoP) cryptographic sender-constraining and atomic nonce renegotiation across distributed microservices. Mandates single-attempt nonce boundary retry semantics, fresh cryptographically secure JTI generation on every retry, SHA-256 access token hash (ath) binding, and distributed JTI replay defense under clock skew. 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: Replaying Static DPoP Proofs with Stale JTIs Across Nonce Refreshes and Omitting Token Hash Binding 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 DriftReplaying Static DPoP Proofs with Stale JTIs Across Nonce Refreshes and Omitting Token Hash BindingCritical
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

Clients MUST generate a unique, cryptographically random 'jti' (UUIDv4 or 128-bit CSPRNG) for every DPoP proof

Clients MUST generate a unique, cryptographically random 'jti' (UUIDv4 or 128-bit CSPRNG) for every DPoP proof; proofs MUST NEVER be cached or re-sent across HTTP requests.

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

Clients MUST enforce an atomic, maximum 1-retry boundary when receiving HTTP 401 with 'WWW-Authenticate

Clients MUST enforce an atomic, maximum 1-retry boundary when receiving HTTP 401 with 'WWW-Authenticate: DPoP error="use_dpop_nonce"'; infinite retry loops or retries without a fresh DPoP-Nonce header MUST immediately fail.

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

Clients MUST regenerate the DPoP signature from scratch during a nonce challenge retry, embedding the newly supplied 'DPoP-Nonce', a fresh 'iat' timestamp, a new 'jti', and an exact SHA-256 base64url-encoded 'ath' (access token hash).

Clients MUST regenerate the DPoP signature from scratch during a nonce challenge retry, embedding the newly supplied 'DPoP-Nonce', a fresh 'iat' timestamp, a new 'jti', and an exact SHA-256 base64url-encoded 'ath' (access token hash).

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

Resource Servers and Gateways MUST validate that the 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query and fragment) strictly match the incoming request envelope.

Resource Servers and Gateways MUST validate that the 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query and fragment) strictly match the incoming request envelope.

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

Resource Servers MUST verify the 'ath' claim against the presented Bearer/DPoP access token using SHA-256 to prevent token substitution attacks.

Resource Servers MUST verify the 'ath' claim against the presented Bearer/DPoP access token using SHA-256 to prevent token substitution attacks.

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 reject DPoP proof timestamps ('iat') skewed beyond a strict ±60 second boundary and MUST store observed (jti, client_id) tuples in a distributed cache (e.g., Redis) with a TTL matching the skew window to guarantee single-use replay protection.

Services MUST reject DPoP proof timestamps ('iat') skewed beyond a strict ±60 second boundary and MUST store observed (jti, client_id) tuples in a distributed cache (e.g., Redis) with a TTL matching the skew window to guarantee single-use replay protection.

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 FAPI 2.0 DPoP Sender-Constrained Nonce Refresh Boundary & Anti-Replay Guardrail critical for AI coding assistants?

Enforces FAPI 2.0 and RFC 9449 Demonstrating Proof-of-Possession (DPoP) cryptographic sender-constraining and atomic nonce renegotiation across distributed microservices. Mandates single-attempt nonce boundary retry semantics, fresh cryptographically secure JTI generation on every retry, SHA-256 access token hash (ath) binding, and distributed JTI replay defense under clock skew. 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 (Replaying Static DPoP Proofs with Stale JTIs Across Nonce Refreshes and Omitting Token Hash Binding) 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

FAPI