This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: bun-strict-tls-alpn-service-mesh-downgrade-defense

Bun 1.2 Strict TLS ALPN Service Mesh Downgrade Defense

Enforces deterministic Application-Layer Protocol Negotiation (ALPN) and post-handshake protocol verification across all internal microservice mTLS sockets in Bun 1.2. Eliminates silent protocol downgrades, TLS stripping, and cross-protocol smuggling by enforcing TLS 1.3, strict mTLS client certificate validation, and zero-tolerance ALPN matching.

Prohibited Anti-Pattern: Permissive mTLS listeners omitting ALPN validation or allowing implicit protocol downgrades in mesh traffic.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Strict TLS ALPN Service Mesh Downgrade Defense - Enforces deterministic Application-Layer Protocol Negotiation (ALPN) and post-handshake protocol verification across all internal microservice mTLS sockets in Bun 1.2. Eliminates silent protocol downgrades, TLS stripping, and cross-protocol smuggling by enforcing TLS 1.3, strict mTLS client certificate validation, and zero-tolerance ALPN matching.
globs: src/**/*.ts, services/**/*.ts, infra/**/*.ts, mesh/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-strict-tls-alpn-service-mesh-downgrade-defense"
---

# Bun 1.2 Strict TLS ALPN Service Mesh Downgrade Defense

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Permissive mTLS listeners omitting ALPN validation or allowing implicit protocol downgrades in mesh traffic.

## System Constraints
You are a Principal Security Architect enforcing strict ALPN (Application-Layer Protocol Negotiation) and mTLS invariants across all Bun 1.2 microservice transport boundaries. You must reject any socket implementation that allows protocol negotiation ambiguity, unauthenticated peer certificates, or missing post-handshake ALPN verification.

## Strict Guidelines
- Engineers MUST ALWAYS declare an explicit, immutable array of supported protocols via `ALPNProtocols` in both `Bun.listen({ tls })` and client `Bun.connect({ tls })` configurations.
- Engineers MUST ALWAYS verify negotiated protocol state post-handshake and immediately call `socket.end()` or `socket.destroy()` if `socket.alpnProtocol` is falsy or not in the authorized whitelist.
- Services MUST enforce strict mutual TLS by setting `requestCert: true`, `rejectUnauthorized: true`, and validating peer certificates against internal mesh Root CAs.
- Services MUST enforce `minVersion: 'TLSv1.3'` across all mesh socket endpoints to mitigate protocol transition attacks and cipher suite downgrades.
- Components NEVER permit implicit fallbacks or empty protocol lists, preventing cross-protocol smuggling between HTTP/1.1, HTTP/2, and raw TCP streams.

## Bad vs Good Implementations
### Mesh Socket Listener with Strict ALPN Negotiation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting ALPNProtocols allows attackers to bypass protocol-level defenses, while rejectUnauthorized: false completely invalidates mTLS trust. The handler processes arbitrary frames without verifying that the negotiated ALPN protocol matches internal service expectations.
```typescript
import { listen } from "bun";

// INSECURE: Omits ALPN enforcement, accepts TLS 1.2 fallbacks,
// and does not assert post-handshake ALPN resolution.
export function startMeshListener(port: number) {
  return listen({
    hostname: "0.0.0.0",
    port,
    tls: {
      cert: Bun.file("/etc/certs/mesh.crt"),
      key: Bun.file("/etc/certs/mesh.key"),
      ca: Bun.file("/etc/certs/mesh-ca.crt"),
      requestCert: true,
      rejectUnauthorized: false // FATAL: Permits unauthenticated connections
    },
    socket: {
      data(socket, data) {
        // Sockets can ingest arbitrary protocol payloads without ALPN verification
        handlePayload(data);
      }
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Configures strict TLSv1.3, mandates mutual TLS authentication (`rejectUnauthorized: true`), explicitly advertises accepted ALPN protocols, and aborts any connection during the `open` lifecycle event if the negotiated protocol does not match the strict internal whitelist.
```typescript
import { listen, type Socket } from "bun";

const PERMITTED_ALPN_PROTOCOLS = Object.freeze(["mesh-rpc/v1", "h2"] as const);
type PermittedProtocol = (typeof PERMITTED_ALPN_PROTOCOLS)[number];

interface MeshSocketData {
  negotiatedProtocol: PermittedProtocol;
}

export function startMeshListener(port: number) {
  return listen<MeshSocketData>({
    hostname: "127.0.0.1",
    port,
    tls: {
      cert: Bun.file("/etc/certs/mesh.crt"),
      key: Bun.file("/etc/certs/mesh.key"),
      ca: Bun.file("/etc/certs/mesh-ca.crt"),
      requestCert: true,
      rejectUnauthorized: true,
      minVersion: "TLSv1.3",
      ALPNProtocols: [...PERMITTED_ALPN_PROTOCOLS]
    },
    socket: {
      open(socket: Socket<MeshSocketData>) {
        const negotiated = socket.alpnProtocol;
        if (!negotiated || !PERMITTED_ALPN_PROTOCOLS.includes(negotiated as PermittedProtocol)) {
          // Immediately terminate on ALPN negotiation failure or unverified downgrade
          socket.end();
          return;
        }
        socket.data = { negotiatedProtocol: negotiated as PermittedProtocol };
      },
      data(socket: Socket<MeshSocketData>, data: Buffer) {
        if (!socket.data?.negotiatedProtocol) {
          socket.end();
          return;
        }
        routeVerifiedMeshFrame(socket.data.negotiatedProtocol, data);
      }
    }
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Strict TLS ALPN Service Mesh Downgrade Defense

Bun 1.2 Strict TLS ALPN Service Mesh Downgrade Defense defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic Application-Layer Protocol Negotiation (ALPN) and post-handshake protocol verification across all internal microservice mTLS sockets in Bun 1.2. Eliminates silent protocol downgrades, TLS stripping, and cross-protocol smuggling by enforcing TLS 1.3, strict mTLS client certificate validation, and zero-tolerance ALPN matching. 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: Permissive mTLS listeners omitting ALPN validation or allowing implicit protocol downgrades in mesh traffic. 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 DriftPermissive mTLS listeners omitting ALPN validation or allowing implicit protocol downgrades in mesh traffic.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 declare an explicit, immutable array of supported protocols via `ALPNProtocols` in both `Bun.listen({ tls })` and client `Bun.connect({ tls })` configurations.

Engineers MUST ALWAYS declare an explicit, immutable array of supported protocols via `ALPNProtocols` in both `Bun.listen({ tls })` and client `Bun.connect({ tls })` configurations.

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 negotiated protocol state post-handshake and immediately call `socket.end()` or `socket.destroy()` if `socket.alpnProtocol` is falsy or not in the authorized whitelist.

Engineers MUST ALWAYS verify negotiated protocol state post-handshake and immediately call `socket.end()` or `socket.destroy()` if `socket.alpnProtocol` is falsy or not in the authorized whitelist.

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

Services MUST enforce strict mutual TLS by setting `requestCert

Services MUST enforce strict mutual TLS by setting `requestCert: true`, `rejectUnauthorized: true`, and validating peer certificates against internal mesh Root CAs.

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 enforce `minVersion

Services MUST enforce `minVersion: 'TLSv1.3'` across all mesh socket endpoints to mitigate protocol transition attacks and cipher suite downgrades.

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 permit implicit fallbacks or empty protocol lists, preventing cross-protocol smuggling between HTTP/1.1, HTTP/2, and raw TCP streams.

Components NEVER permit implicit fallbacks or empty protocol lists, preventing cross-protocol smuggling between HTTP/1.1, HTTP/2, and raw TCP streams.

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 Bun 1.2 Strict TLS ALPN Service Mesh Downgrade Defense critical for AI coding assistants?

Enforces deterministic Application-Layer Protocol Negotiation (ALPN) and post-handshake protocol verification across all internal microservice mTLS sockets in Bun 1.2. Eliminates silent protocol downgrades, TLS stripping, and cross-protocol smuggling by enforcing TLS 1.3, strict mTLS client certificate validation, and zero-tolerance ALPN matching. 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 (Permissive mTLS listeners omitting ALPN validation or allowing implicit protocol downgrades in mesh traffic.) 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

Bun