This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: post-quantum-mldsa-dual-signature-webhook-validation

Mandatory Hybrid Post-Quantum ML-DSA-65 and Classical ECDSA Dual-Signature Invariant

Enforces hybrid quantum-resilient verification on asynchronous ingestion channels by pairing classical ECDSA (P-384/secp256r1) with post-quantum ML-DSA-65 (FIPS 204). Guards webhook payloads against Harvest-Now-Decrypt/Forge-Later (HNDL/HNFL) adversaries targeting critical webhook ingestion pipelines. Payload deserialization is strictly blocked until both mathematical signatures independently verify the raw unparsed octet stream bound to tamper-proof headers.

Prohibited Anti-Pattern: Accepting classical-only ECDSA signatures or parsing payloads prior to dual-signature verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandatory Hybrid Post-Quantum ML-DSA-65 and Classical ECDSA Dual-Signature Invariant - Enforces hybrid quantum-resilient verification on asynchronous ingestion channels by pairing classical ECDSA (P-384/secp256r1) with post-quantum ML-DSA-65 (FIPS 204). Guards webhook payloads against Harvest-Now-Decrypt/Forge-Later (HNDL/HNFL) adversaries targeting critical webhook ingestion pipelines. Payload deserialization is strictly blocked until both mathematical signatures independently verify the raw unparsed octet stream bound to tamper-proof headers.
globs: src/**/webhooks/**/*.{ts,tsx,js}, src/**/middleware/**/*.{ts,tsx,js}, src/**/security/**/*.{ts,tsx,js}, src/**/ingestion/**/*.{ts,tsx,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/post-quantum-mldsa-dual-signature-webhook-validation"
---

# Mandatory Hybrid Post-Quantum ML-DSA-65 and Classical ECDSA Dual-Signature Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting classical-only ECDSA signatures or parsing payloads prior to dual-signature verification

## System Constraints
You are a Principal Security Architect and Cryptographic Rules Author enforcing post-quantum zero-trust invariants. Mandate hybrid dual-signature verification using both classical ECDSA and NIST FIPS 204 ML-DSA-65 (formerly Dilithium3) on all asynchronous ingestion and webhook transport layers. Any implementation that parses, processes, or branches on unverified payload bodies prior to dual cryptographic attestation violates security invariants and must be flagged immediately.

## Strict Guidelines
- Engineers MUST ALWAYS enforce raw byte stream verification over canonicalized context: signing string MUST strictly concatenate `v1:${timestamp}:${nonce}:${rawBodyHash}`.
- Engineers MUST ALWAYS verify BOTH classical ECDSA (P-384 or secp256r1) AND post-quantum ML-DSA-65 signatures in a fail-closed sequence before delegating to JSON parsers.
- Engineers MUST NOT parse the JSON payload body into an Object or AST before both cryptographic signature checks have passed successfully.
- Services MUST reject payloads where timestamp drift exceeds +/- 300 seconds (clock skew protection) or when the nonce has already been observed in the replay-cache window.
- Components NEVER fall back to classical-only verification if ML-DSA verification fails or if the `X-Signature-ML-DSA-65` header is absent.

## Bad vs Good Implementations
### Vulnerable Classical-Only Single Signature Verification Prior to Parsing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Parses JSON prior to authentication, exposing the service to parser exploits and canonicalization discrepancies. Verifies only classical ECDSA, leaving the webhook pipeline vulnerable to quantum-harvesting forgery. Lacks nonce/replay-defense binding and omits ML-DSA-65 post-quantum guarantees entirely.
```typescript
import express, { Request, Response } from 'express';
import crypto from 'node:crypto';

const app = express();
app.use(express.json()); // ANTI-PATTERN: Parses JSON before verifying raw signatures

app.post('/api/v1/webhook', (req: Request, res: Response) => {
  const ecdsaSig = req.header('x-signature-ecdsa');
  if (!ecdsaSig) {
    return res.status(401).send('Missing signature');
  }

  // VULNERABILITY 1: Harvest-Now-Forge-Later risk (classical-only signature)
  // VULNERABILITY 2: Verifies serialized/re-stringified JSON which can diverge (malleability)
  const verifier = crypto.createVerify('SHA256');
  verifier.update(JSON.stringify(req.body));
  
  const isValid = verifier.verify(process.env.CLASSICAL_PUBLIC_KEY!, ecdsaSig, 'hex');
  if (!isValid) {
    return res.status(403).send('Invalid signature');
  }

  return res.status(200).json({ processed: true });
});
```

#### Production Standard (Correct)
> **Standard**: Enforces strict fail-closed dual verification with both classical ECDSA-SHA384 and ML-DSA-65 over unparsed raw bytes. Context-binds timestamp and nonce into the authenticated envelope to block replay attacks, defeating Harvest-Now-Forge-Later vectors.
```typescript
import { Request, Response, NextFunction } from 'express';
import crypto from 'node:crypto';
import { mldsa65 } from '@noble/post-quantum/ml-dsa';

interface VerifiedSecureRequest extends Request {
  rawPayloadBuffer: Buffer;
}

const TOLERANCE_WINDOW_SECONDS = 300;

export async function verifyHybridPostQuantumWebhook(
  req: VerifiedSecureRequest,
  res: Response,
  next: NextFunction
): Promise<void> {
  const ecdsaSigHex = req.header('X-Signature-ECDSA-SHA384');
  const mldsaSigHex = req.header('X-Signature-ML-DSA-65');
  const timestampHeader = req.header('X-Signature-Timestamp');
  const nonce = req.header('X-Signature-Nonce');

  if (!ecdsaSigHex || !mldsaSigHex || !timestampHeader || !nonce) {
    res.status(401).json({ error: 'Missing mandatory hybrid PQC signature headers' });
    return;
  }

  const nowEpoch = Math.floor(Date.now() / 1000);
  const timestamp = Number.parseInt(timestampHeader, 10);
  if (Number.isNaN(timestamp) || Math.abs(nowEpoch - timestamp) > TOLERANCE_WINDOW_SECONDS) {
    res.status(403).json({ error: 'Signature expired or excessive clock drift' });
    return;
  }

  // Raw buffer must be captured before any stream transformation or parsing
  const rawBody = req.rawPayloadBuffer;
  if (!rawBody || rawBody.length === 0) {
    res.status(400).json({ error: 'Empty payload buffer rejected' });
    return;
  }

  const rawBodyHash = crypto.createHash('sha384').update(rawBody).digest('hex');
  const messageToVerify = Buffer.from(`v1:${timestamp}:${nonce}:${rawBodyHash}`, 'utf-8');

  // 1. Classical Verification (ECDSA P-384)
  const classicalVerifier = crypto.createVerify('SHA384');
  classicalVerifier.update(messageToVerify);
  const isClassicalValid = classicalVerifier.verify(
    process.env.ECDSA_PUBLIC_KEY!,
    Buffer.from(ecdsaSigHex, 'hex')
  );

  if (!isClassicalValid) {
    res.status(403).json({ error: 'Classical signature validation failed' });
    return;
  }

  // 2. Post-Quantum Verification (ML-DSA-65 / FIPS 204)
  const mldsaPublicKeyBytes = Buffer.from(process.env.ML_DSA_65_PUBLIC_KEY_HEX!, 'hex');
  const mldsaSignatureBytes = Buffer.from(mldsaSigHex, 'hex');
  
  const isPqcValid = mldsa65.verify(
    mldsaPublicKeyBytes,
    messageToVerify,
    mldsaSignatureBytes
  );

  if (!isPqcValid) {
    res.status(403).json({ error: 'Post-quantum ML-DSA-65 signature validation failed' });
    return;
  }

  // Both classical and PQC invariants satisfied; allow processing
  next();
}
```

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: Mandatory Hybrid Post-Quantum ML-DSA-65 and Classical ECDSA Dual-Signature Invariant

Mandatory Hybrid Post-Quantum ML-DSA-65 and Classical ECDSA Dual-Signature Invariant defines an industrial-grade behavioral standard for security engineering. Enforces hybrid quantum-resilient verification on asynchronous ingestion channels by pairing classical ECDSA (P-384/secp256r1) with post-quantum ML-DSA-65 (FIPS 204). Guards webhook payloads against Harvest-Now-Decrypt/Forge-Later (HNDL/HNFL) adversaries targeting critical webhook ingestion pipelines. Payload deserialization is strictly blocked until both mathematical signatures independently verify the raw unparsed octet stream bound to tamper-proof headers. 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 classical-only ECDSA signatures or parsing payloads prior to dual-signature verification 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 classical-only ECDSA signatures or parsing payloads prior to dual-signature verificationCritical
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 raw byte stream verification over canonicalized context

Engineers MUST ALWAYS enforce raw byte stream verification over canonicalized context: signing string MUST strictly concatenate `v1:${timestamp}:${nonce}:${rawBodyHash}`.

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 ALWAYS verify BOTH classical ECDSA (P-384 or secp256r1) AND post-quantum ML-DSA-65 signatures in a fail-closed sequence before delegating to JSON parsers.

Engineers MUST ALWAYS verify BOTH classical ECDSA (P-384 or secp256r1) AND post-quantum ML-DSA-65 signatures in a fail-closed sequence before delegating to JSON parsers.

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

Engineers MUST NOT parse the JSON payload body into an Object or AST before both cryptographic signature checks have passed successfully.

Engineers MUST NOT parse the JSON payload body into an Object or AST before both cryptographic signature checks have passed successfully.

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 reject payloads where timestamp drift exceeds +/- 300 seconds (clock skew protection) or when the nonce has already been observed in the replay-cache window.

Services MUST reject payloads where timestamp drift exceeds +/- 300 seconds (clock skew protection) or when the nonce has already been observed in the replay-cache 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.
5

Components NEVER fall back to classical-only verification if ML-DSA verification fails or if the `X-Signature-ML-DSA-65` header is absent.

Components NEVER fall back to classical-only verification if ML-DSA verification fails or if the `X-Signature-ML-DSA-65` header is absent.

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 Mandatory Hybrid Post-Quantum ML-DSA-65 and Classical ECDSA Dual-Signature Invariant critical for AI coding assistants?

Enforces hybrid quantum-resilient verification on asynchronous ingestion channels by pairing classical ECDSA (P-384/secp256r1) with post-quantum ML-DSA-65 (FIPS 204). Guards webhook payloads against Harvest-Now-Decrypt/Forge-Later (HNDL/HNFL) adversaries targeting critical webhook ingestion pipelines. Payload deserialization is strictly blocked until both mathematical signatures independently verify the raw unparsed octet stream bound to tamper-proof headers. 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 classical-only ECDSA signatures or parsing payloads prior to dual-signature verification) 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

Mandatory