This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: sd-jwt-claim-disclosure-invariant

SD-JWT (RFC 9528) Selective Disclosure Cryptographic Integrity & Minimization Standard

Enforces strict compliance with RFC 9528 for Selective Disclosure JSON Web Tokens (SD-JWT). Guarantees that selective disclosures are cryptographically hashed using collision-resistant digest algorithms matching the _sd_alg header, prevents leaking raw salt or plaintext identity claims in presentation payloads, and strictly rejects undecoded or malformed disclosure frames during token verification.

Prohibited Anti-Pattern: Leaking Raw Disclosures or Salt Entropy in Verifier Payloads and Skipping Disclosure Digest Recalculation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SD-JWT (RFC 9528) Selective Disclosure Cryptographic Integrity & Minimization Standard - Enforces strict compliance with RFC 9528 for Selective Disclosure JSON Web Tokens (SD-JWT). Guarantees that selective disclosures are cryptographically hashed using collision-resistant digest algorithms matching the _sd_alg header, prevents leaking raw salt or plaintext identity claims in presentation payloads, and strictly rejects undecoded or malformed disclosure frames during token verification.
globs: src/**/identity/**/*.{ts,js}, src/**/credentials/**/*.{ts,js}, src/**/auth/**/*.{ts,js}, src/**/verification/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/sd-jwt-claim-disclosure-invariant"
---

# SD-JWT (RFC 9528) Selective Disclosure Cryptographic Integrity & Minimization Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Leaking Raw Disclosures or Salt Entropy in Verifier Payloads and Skipping Disclosure Digest Recalculation

## System Constraints
You are a Principal Security Architect enforcing RFC 9528 (SD-JWT) cryptographic standards. Ensure every token issuance and verification pipeline validates cryptographic digests of selectively disclosable claims, enforces strict entropy requirements on disclosure salts (minimum 128-bit CSPRNG), validates the '_sd_alg' parameter against an approved cryptographic registry, and prevents unintentional exposure of undisclosed claims and raw salts during presentation and parsing phases.

## Strict Guidelines
- Engineers MUST ALWAYS enforce that salts used in disclosures contain a minimum of 128 bits of cryptographic entropy generated via a secure CSPRNG (e.g., crypto.randomBytes(16)).
- Engineers MUST NOT allow unhashed disclosure payloads to be embedded directly within the SD-JWT claims body; only base64url-encoded cryptographic digests of disclosures MUST appear in the '_sd' array.
- Code MUST strictly validate the '_sd_alg' property within the SD-JWT header/payload and MUST restrict acceptable digest algorithms to approved algorithms (e.g., 'sha-256', 'sha-384', 'sha-512'), rejecting weak algorithms or algorithm confusion attacks.
- Services MUST recalculate disclosure digests during verification by computing Base64URL(Hash(Raw_Disclosure_String)) and verifying strict presence in the SD-JWT '_sd' array before admitting claims into the validated identity context.
- Components NEVER include undisclosed claims or internal salt values in decoded identity contexts passed to downstream application business logic.

## Bad vs Good Implementations
### SD-JWT Disclosure Verification and Claim Reconstitution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example decodes disclosure frames and blindly injects claims into the resolved identity context without computing the cryptographic hash of the raw disclosure frame to match against the payload's '_sd' digest array. It also exposes the raw disclosure salt to application logic, violating claim minimization and opening the verifier up to arbitrary claim injection.
```typescript
import { createHash } from 'node:crypto';

interface SDJWTPayload {
  _sd?: string[];
  _sd_alg?: string;
  [key: string]: unknown;
}

// INSECURE: Blindly trusts disclosure claims without recomputing digest against _sd array
export function verifyAndExtractClaims(payload: SDJWTPayload, disclosures: string[]): Record<string, unknown> {
  const resolvedClaims: Record<string, unknown> = { ...payload };
  
  for (const rawDisclosure of disclosures) {
    // Decodes base64url without digest verification
    const decoded = Buffer.from(rawDisclosure, 'base64url').toString('utf-8');
    const [salt, claimName, claimValue] = JSON.parse(decoded);
    
    // Blindly assigns claim to context without validating rawDisclosure hash in payload._sd
    resolvedClaims[claimName] = claimValue;
    // LEAK: Exposes raw disclosure salt to application state
    resolvedClaims[`_salt_${claimName}`] = salt;
  }
  
  delete resolvedClaims._sd;
  return resolvedClaims;
}
```

#### Production Standard (Correct)
> **Standard**: The good example rigorously adheres to RFC 9528 by enforcing an allowlist of cryptographic digest algorithms, computing the base64url-encoded digest of each raw disclosure string, verifying membership against the issuer-signed '_sd' array, and discarding raw disclosure salts so identity context is minimized and immutable.
```typescript
import { createHash, timingSafeEqual } from 'node:crypto';

interface SDJWTPayload {
  _sd?: string[];
  _sd_alg?: string;
  [key: string]: unknown;
}

const ALLOWED_DIGEST_ALGORITHMS = new Set(['sha-256', 'sha-384', 'sha-512']);

export function verifyAndExtractClaims(
  payload: SDJWTPayload,
  rawDisclosures: readonly string[]
): Record<string, unknown> {
  const digestAlg = (payload._sd_alg ?? 'sha-256').toLowerCase();
  if (!ALLOWED_DIGEST_ALGORITHMS.has(digestAlg)) {
    throw new SecurityError(`Unsupported or insecure _sd_alg: ${digestAlg}`);
  }

  const validDigests = new Set<string>(payload._sd ?? []);
  const resolvedClaims: Record<string, unknown> = {};

  // Copy non-selective disclosure claims safely
  for (const [key, value] of Object.entries(payload)) {
    if (key !== '_sd' && key !== '_sd_alg') {
      resolvedClaims[key] = value;
    }
  }

  for (const rawDisclosure of rawDisclosures) {
    const computedDigest = createHash(digestAlg)
      .update(rawDisclosure, 'ascii')
      .digest('base64url');

    if (!validDigests.has(computedDigest)) {
      throw new SecurityError('Disclosure digest mismatch: claim not bound to issuer signature');
    }

    const decodedJson = Buffer.from(rawDisclosure, 'base64url').toString('utf-8');
    const parsed: unknown = JSON.parse(decodedJson);

    if (!Array.isArray(parsed) || parsed.length !== 3) {
      throw new SecurityError('Invalid RFC 9528 disclosure structure');
    }

    const [salt, claimName, claimValue] = parsed;
    if (typeof salt !== 'string' || typeof claimName !== 'string' || salt.length < 16) {
      throw new SecurityError('Malformed disclosure payload or insufficient salt entropy');
    }

    // Strictly attach claim name and value; purge salt from verification context
    resolvedClaims[claimName] = claimValue;
    validDigests.delete(computedDigest); // Prevent replay within the same token
  }

  return Object.freeze(resolvedClaims);
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: SD-JWT (RFC 9528) Selective Disclosure Cryptographic Integrity & Minimization Standard

SD-JWT (RFC 9528) Selective Disclosure Cryptographic Integrity & Minimization Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict compliance with RFC 9528 for Selective Disclosure JSON Web Tokens (SD-JWT). Guarantees that selective disclosures are cryptographically hashed using collision-resistant digest algorithms matching the _sd_alg header, prevents leaking raw salt or plaintext identity claims in presentation payloads, and strictly rejects undecoded or malformed disclosure frames during token verification. 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: Leaking Raw Disclosures or Salt Entropy in Verifier Payloads and Skipping Disclosure Digest Recalculation 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 DriftLeaking Raw Disclosures or Salt Entropy in Verifier Payloads and Skipping Disclosure Digest RecalculationCritical
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 enforce that salts used in disclosures contain a minimum of 128 bits of cryptographic entropy generated via a secure CSPRNG (e.g., crypto.randomBytes(16)).

Engineers MUST ALWAYS enforce that salts used in disclosures contain a minimum of 128 bits of cryptographic entropy generated via a secure CSPRNG (e.g., crypto.randomBytes(16)).

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 allow unhashed disclosure payloads to be embedded directly within the SD-JWT claims body

Engineers MUST NOT allow unhashed disclosure payloads to be embedded directly within the SD-JWT claims body; only base64url-encoded cryptographic digests of disclosures MUST appear in the '_sd' array.

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 strictly validate the '_sd_alg' property within the SD-JWT header/payload and MUST restrict acceptable digest algorithms to approved algorithms (e.g., 'sha-256', 'sha-384', 'sha-512'), rejecting weak algorithms or algorithm confusion attacks.

Code MUST strictly validate the '_sd_alg' property within the SD-JWT header/payload and MUST restrict acceptable digest algorithms to approved algorithms (e.g., 'sha-256', 'sha-384', 'sha-512'), rejecting weak algorithms or algorithm confusion 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.
4

Services MUST recalculate disclosure digests during verification by computing Base64URL(Hash(Raw_Disclosure_String)) and verifying strict presence in the SD-JWT '_sd' array before admitting claims into the validated identity context.

Services MUST recalculate disclosure digests during verification by computing Base64URL(Hash(Raw_Disclosure_String)) and verifying strict presence in the SD-JWT '_sd' array before admitting claims into the validated identity 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.
5

Components NEVER include undisclosed claims or internal salt values in decoded identity contexts passed to downstream application business logic.

Components NEVER include undisclosed claims or internal salt values in decoded identity contexts passed to downstream application business logic.

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 SD-JWT (RFC 9528) Selective Disclosure Cryptographic Integrity & Minimization Standard critical for AI coding assistants?

Enforces strict compliance with RFC 9528 for Selective Disclosure JSON Web Tokens (SD-JWT). Guarantees that selective disclosures are cryptographically hashed using collision-resistant digest algorithms matching the _sd_alg header, prevents leaking raw salt or plaintext identity claims in presentation payloads, and strictly rejects undecoded or malformed disclosure frames during token verification. 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 (Leaking Raw Disclosures or Salt Entropy in Verifier Payloads and Skipping Disclosure Digest Recalculation) 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

SD-JWT