This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: w3c-dbsc-hardware-key-invariant

W3C DBSC Hardware-Bound Session Credential Verification

Enforces strict W3C Device Bound Session Credentials (DBSC) protocol semantics to eradicate token theft and session hijacking. Requires edge and identity layers to bind short-lived session cookies directly to client TPM or Secure Enclave asymmetric key pairs, validating hardware-signed challenge-response proofs on session renewal and mutating authorization state.

Prohibited Anti-Pattern: Trusting Bearer Session Cookies Without Cryptographic Proof of Device Key Possession

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: W3C DBSC Hardware-Bound Session Credential Verification - Enforces strict W3C Device Bound Session Credentials (DBSC) protocol semantics to eradicate token theft and session hijacking. Requires edge and identity layers to bind short-lived session cookies directly to client TPM or Secure Enclave asymmetric key pairs, validating hardware-signed challenge-response proofs on session renewal and mutating authorization state.
globs: src/auth/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/server/**/*.{ts,js}, src/security/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/w3c-dbsc-hardware-key-invariant"
---

# W3C DBSC Hardware-Bound Session Credential Verification

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting Bearer Session Cookies Without Cryptographic Proof of Device Key Possession

## System Constraints
You are a Principal Engineer enforcing the W3C DBSC (Device Bound Session Credentials) Hardware Key Invariant. Mandate that every session refresh and privileged state transition strictly validates hardware-backed cryptographic proofs (TPM/Secure Enclave) supplied in the `Sec-Session-Response` header. Never allow session extensions via bearer cookies alone, eliminate long-lived edge cookies, and ensure challenge nonces and origin parameters strictly bind to the registered device public key.

## Strict Guidelines
- Engineers MUST ALWAYS require and verify the `Sec-Session-Response` JWT header signed by the client's hardware-backed private key during session refresh endpoints.
- Services MUST NEVER issue edge session cookies with a TTL greater than 120 seconds; all continuous sessions must rely on periodic DBSC challenge-response refreshes.
- Code MUST validate that the DBSC proof payload contains the exact cryptographic challenge nonce previously issued, matches the server origin, and matches the stored device public key.
- Engineers MUST NOT fallback to pure bearer cookie authentication when a session has been designated as device-bound; missing or invalid DBSC signatures must trigger immediate session termination.
- Services MUST invalidate the active session state immediately if the public key presented in a refresh assertion does not match the device key registered at session initialization.
- Components NEVER expose or attempt to export client-side private keys; registration must mandate non-exportable hardware flags (`extractable: false`).

## Bad vs Good Implementations
### DBSC Session Refresh and Hardware Key Proof Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The session refresh endpoint merely validates a standard signed JWT cookie. If the cookie is exfiltrated via malware, Infostealers, or proxy interception, the attacker can indefinitely renew and hijack the session without possessing the physical device or TPM key.
```typescript
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';

// VULNERABLE: Refreshing session relying entirely on ambient bearer cookie
// An attacker with an exfiltrated cookie can sustain the session indefinitely.
export async function handleSessionRefresh(req: Request, res: Response) {
  const sessionCookie = req.cookies['session_token'];
  if (!sessionCookie) {
    return res.status(401).json({ error: 'Missing session cookie' });
  }

  try {
    const decoded = jwt.verify(sessionCookie, process.env.JWT_SECRET!) as { userId: string };
    
    // Issuing a new 24h bearer cookie without proving hardware key possession
    const newCookie = jwt.sign({ userId: decoded.userId }, process.env.JWT_SECRET!, { expiresIn: '24h' });
    res.cookie('session_token', newCookie, { httpOnly: true, secure: true });
    return res.status(200).json({ status: 'refreshed' });
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements the W3C DBSC specification by verifying that the `Sec-Session-Response` header contains a valid signature from the hardware key (TPM/Secure Enclave) registered to the session. Validates challenge nonce, origin audience, enforces a strict 120-second TTL on edge cookies, and issues the next challenge nonce.
```typescript
import { Request, Response } from 'express';
import { importJWK, jwtVerify } from 'jose';
import crypto from 'node:crypto';
import { getStoredDeviceSession, updateSessionChallenge } from './sessionStore';

interface DBSCProofClaims {
  nonce: string;
  aud: string;
  iat: number;
}

export async function handleSessionRefresh(req: Request, res: Response) {
  const sessionId = req.cookies['dbsc_session_id'];
  const dbscResponse = req.header('Sec-Session-Response');

  if (!sessionId || !dbscResponse) {
    return res.status(401).json({ error: 'Missing session credentials or DBSC proof' });
  }

  const session = await getStoredDeviceSession(sessionId);
  if (!session || !session.publicKeyJwk) {
    return res.status(401).json({ error: 'Invalid or revoked device session' });
  }

  try {
    const devicePublicKey = await importJWK(session.publicKeyJwk, session.publicKeyJwk.alg || 'ES256');
    const expectedOrigin = process.env.EXPECTED_ORIGIN!;

    // Cryptographically verify the hardware-signed assertion using the registered TPM/SE key
    const { payload } = await jwtVerify(dbscResponse, devicePublicKey, {
      audience: expectedOrigin,
      algorithms: ['ES256', 'RS256']
    });

    const claims = payload as unknown as DBSCProofClaims;

    // Verify anti-replay nonce and recency
    if (claims.nonce !== session.pendingChallenge) {
      return res.status(403).json({ error: 'DBSC challenge nonce mismatch' });
    }

    const nextChallenge = crypto.randomBytes(32).toString('base64url');
    await updateSessionChallenge(sessionId, nextChallenge);

    // Issue ephemeral, short-lived edge cookie bound to this verified hardware device
    res.cookie('session_token', session.token, {
      httpOnly: true,
      secure: true,
      sameSite: 'strict',
      maxAge: 120 * 1000 // 120 seconds TTL strictly enforced
    });

    res.setHeader('Sec-Session-Challenge', `"${nextChallenge}"; id="${sessionId}"`);
    return res.status(200).json({ status: 'device_verified' });
  } catch (err) {
    // Hardware proof failure triggers immediate invalidation to stop hijacked token use
    return res.status(401).json({ error: 'DBSC hardware verification failed' });
  }
}
```

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: W3C DBSC Hardware-Bound Session Credential Verification

W3C DBSC Hardware-Bound Session Credential Verification defines an industrial-grade behavioral standard for security engineering. Enforces strict W3C Device Bound Session Credentials (DBSC) protocol semantics to eradicate token theft and session hijacking. Requires edge and identity layers to bind short-lived session cookies directly to client TPM or Secure Enclave asymmetric key pairs, validating hardware-signed challenge-response proofs on session renewal and mutating authorization state. 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: Trusting Bearer Session Cookies Without Cryptographic Proof of Device Key Possession 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 DriftTrusting Bearer Session Cookies Without Cryptographic Proof of Device Key PossessionCritical
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 require and verify the `Sec-Session-Response` JWT header signed by the client's hardware-backed private key during session refresh endpoints.

Engineers MUST ALWAYS require and verify the `Sec-Session-Response` JWT header signed by the client's hardware-backed private key during session refresh endpoints.

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

Services MUST NEVER issue edge session cookies with a TTL greater than 120 seconds

Services MUST NEVER issue edge session cookies with a TTL greater than 120 seconds; all continuous sessions must rely on periodic DBSC challenge-response refreshes.

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 validate that the DBSC proof payload contains the exact cryptographic challenge nonce previously issued, matches the server origin, and matches the stored device public key.

Code MUST validate that the DBSC proof payload contains the exact cryptographic challenge nonce previously issued, matches the server origin, and matches the stored device public key.

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

Engineers MUST NOT fallback to pure bearer cookie authentication when a session has been designated as device-bound

Engineers MUST NOT fallback to pure bearer cookie authentication when a session has been designated as device-bound; missing or invalid DBSC signatures must trigger immediate session termination.

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

Services MUST invalidate the active session state immediately if the public key presented in a refresh assertion does not match the device key registered at session initialization.

Services MUST invalidate the active session state immediately if the public key presented in a refresh assertion does not match the device key registered at session initialization.

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 expose or attempt to export client-side private keys

Components NEVER expose or attempt to export client-side private keys; registration must mandate non-exportable hardware flags (`extractable: false`).

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 W3C DBSC Hardware-Bound Session Credential Verification critical for AI coding assistants?

Enforces strict W3C Device Bound Session Credentials (DBSC) protocol semantics to eradicate token theft and session hijacking. Requires edge and identity layers to bind short-lived session cookies directly to client TPM or Secure Enclave asymmetric key pairs, validating hardware-signed challenge-response proofs on session renewal and mutating authorization state. 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 (Trusting Bearer Session Cookies Without Cryptographic Proof of Device Key Possession) 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

W3C