This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-sab-worker-cross-origin-isolation-guardrail

Bun 1.2 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrail

Enforces strict memory isolation, Cross-Origin Isolation HTTP headers (COOP/COEP), and Atomics-based synchronization when leveraging SharedArrayBuffer across worker pools in Bun 1.2. Prevents speculative execution side-channel leaks (Spectre) and unsynchronized data races in high-throughput multi-tenant edge runtimes.

Prohibited Anti-Pattern: Sharing raw SharedArrayBuffer instances across worker threads without cross-origin isolation headers, tenant partition bounds, and Atomics synchronization.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrail - Enforces strict memory isolation, Cross-Origin Isolation HTTP headers (COOP/COEP), and Atomics-based synchronization when leveraging SharedArrayBuffer across worker pools in Bun 1.2. Prevents speculative execution side-channel leaks (Spectre) and unsynchronized data races in high-throughput multi-tenant edge runtimes.
globs: src/**/*.ts, workers/**/*.ts, server/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sab-worker-cross-origin-isolation-guardrail"
---

# Bun 1.2 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Sharing raw SharedArrayBuffer instances across worker threads without cross-origin isolation headers, tenant partition bounds, and Atomics synchronization.

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrails. Mandate non-negotiable invariants: all HTTP responses utilizing or dispatching to threads with SharedArrayBuffer must enforce COOP ('same-origin') and COEP ('require-corp' or 'credentialless') headers; cross-thread shared memory access must exclusively use Atomics; and multi-tenant buffer allocations must enforce isolated memory partitioning, explicit bounds checks, and zero-fill sanitation to prevent side-channel timing and data contamination attacks.

## Strict Guidelines
- HTTP responses in Bun 1.2 serving assets or APIs interacting with SharedArrayBuffer MUST set 'Cross-Origin-Opener-Policy: same-origin' and 'Cross-Origin-Embedder-Policy: require-corp' (or 'credentialless').
- Engineers MUST NEVER mutate SharedArrayBuffer memory across concurrent Worker threads using direct typed array indexing; all cross-thread read/write/wait/notify operations MUST use Atomics.
- Worker pools serving multi-tenant workloads MUST NEVER allow cross-tenant sharing of an unpartitioned SharedArrayBuffer; each tenant MUST be allocated an isolated slice with strict bounds checking.
- Engineers MUST zero-fill ('fill(0)') reused buffer segments prior to reassigning them across tenant tasks in pooled workers to eliminate residual memory leakage.
- Code SHOULD prefer zero-copy ArrayBuffer transfers via postMessage(payload, [payload.buffer]) instead of SharedArrayBuffer unless simultaneous concurrent multi-threaded mutation is explicitly required.

## Bad vs Good Implementations
### Concurrent Worker Synchronization and HTTP Isolation Headers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits mandatory COOP/COEP security headers, allowing speculative execution side-channel leaks. Mutates shared memory via direct array indexing instead of Atomics, causing data races. Shares a monolithic, unpartitioned SharedArrayBuffer across multiple tenants without sanitization.
```typescript
import { serve } from "bun";

// Flaw 1: Missing COOP/COEP headers leaves runtime vulnerable to Spectre side-channel leaks
// Flaw 2: Global SharedArrayBuffer reused directly across multi-tenant requests
const sharedBuffer = new SharedArrayBuffer(1024);
const stateView = scienceWorkerInt32(sharedBuffer);

function scienceWorkerInt32(buf: SharedArrayBuffer): Int32Array {
  return new Int32Array(buf);
}

const worker = new Worker(new URL("./worker.ts", import.meta.url).href);

serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    const tenantId = url.searchParams.get("tenantId") ?? "default";

    // Flaw 3: Direct unsynchronized non-atomic write introduces race conditions and torn reads
    stateView[0] = stateView[0] + 1;
    worker.postMessage({ buffer: sharedBuffer, tenantId });

    return new Response(JSON.stringify({ counter: stateView[0] }), {
      headers: { "Content-Type": "application/json" }
    });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Enforces COOP and COEP headers on every HTTP response, utilizes Atomics.add for thread-safe memory increments, and strictly partitions memory with bounds checks per tenant to prevent cross-tenant data and timing leaks.
```typescript
import { serve } from "bun";

// Invariant 1: Cross-Origin Isolation headers enforced to prevent side-channel timing attacks
const SECURITY_HEADERS = {
  "Content-Type": "application/json",
  "Cross-Origin-Opener-Policy": "same-origin",
  "Cross-Origin-Embedder-Policy": "require-corp"
} as const;

const TENANT_STRIDE_BYTES = 128;
const MAX_TENANTS = 8;
const masterBuffer = new SharedArrayBuffer(MAX_TENANTS * TENANT_STRIDE_BYTES);
const syncRegistry = new Int32Array(masterBuffer);

const worker = new Worker(new URL("./worker.ts", import.meta.url).href);

function getTenantOffset(tenantIndex: number): number {
  if (tenantIndex < 0 || tenantIndex >= MAX_TENANTS) {
    throw new RangeError(`Tenant index ${tenantIndex} out of bounds`);
  }
  return (tenantIndex * TENANT_STRIDE_BYTES) / Int32Array.BYTES_PER_ELEMENT;
}

serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    const tenantIndex = parseInt(url.searchParams.get("tenantIndex") ?? "0", 10);

    if (isNaN(tenantIndex) || tenantIndex < 0 || tenantIndex >= MAX_TENANTS) {
      return new Response(JSON.stringify({ error: "Invalid tenant partition index" }), {
        status: 400,
        headers: SECURITY_HEADERS
      });
    }

    const offset = getTenantOffset(tenantIndex);

    // Invariant 2: Atomics provide race-free synchronization across threads
    const previousValue = Atomics.add(syncRegistry, offset, 1);
    const currentCounter = previousValue + 1;

    // Invariant 3: Forward isolated slice coordinates, preventing cross-tenant boundary inspection
    worker.postMessage({
      buffer: masterBuffer,
      tenantIndex,
      offsetIndex: offset
    });

    return new Response(JSON.stringify({ tenantIndex, counter: currentCounter }), {
      headers: SECURITY_HEADERS
    });
  }
});
```

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: Bun 1.2 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrail

Bun 1.2 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory isolation, Cross-Origin Isolation HTTP headers (COOP/COEP), and Atomics-based synchronization when leveraging SharedArrayBuffer across worker pools in Bun 1.2. Prevents speculative execution side-channel leaks (Spectre) and unsynchronized data races in high-throughput multi-tenant edge runtimes. 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: Sharing raw SharedArrayBuffer instances across worker threads without cross-origin isolation headers, tenant partition bounds, and Atomics synchronization. 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 DriftSharing raw SharedArrayBuffer instances across worker threads without cross-origin isolation headers, tenant partition bounds, and Atomics synchronization.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

HTTP responses in Bun 1.2 serving assets or APIs interacting with SharedArrayBuffer MUST set 'Cross-Origin-Opener-Policy

HTTP responses in Bun 1.2 serving assets or APIs interacting with SharedArrayBuffer MUST set 'Cross-Origin-Opener-Policy: same-origin' and 'Cross-Origin-Embedder-Policy: require-corp' (or 'credentialless').

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 NEVER mutate SharedArrayBuffer memory across concurrent Worker threads using direct typed array indexing

Engineers MUST NEVER mutate SharedArrayBuffer memory across concurrent Worker threads using direct typed array indexing; all cross-thread read/write/wait/notify operations MUST use Atomics.

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

Worker pools serving multi-tenant workloads MUST NEVER allow cross-tenant sharing of an unpartitioned SharedArrayBuffer

Worker pools serving multi-tenant workloads MUST NEVER allow cross-tenant sharing of an unpartitioned SharedArrayBuffer; each tenant MUST be allocated an isolated slice with strict bounds checking.

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 zero-fill ('fill(0)') reused buffer segments prior to reassigning them across tenant tasks in pooled workers to eliminate residual memory leakage.

Engineers MUST zero-fill ('fill(0)') reused buffer segments prior to reassigning them across tenant tasks in pooled workers to eliminate residual memory leakage.

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

Code SHOULD prefer zero-copy ArrayBuffer transfers via postMessage(payload, [payload.buffer]) instead of SharedArrayBuffer unless simultaneous concurrent multi-threaded mutation is explicitly required.

Code SHOULD prefer zero-copy ArrayBuffer transfers via postMessage(payload, [payload.buffer]) instead of SharedArrayBuffer unless simultaneous concurrent multi-threaded mutation is explicitly required.

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 SharedArrayBuffer Worker Pool Cross-Origin Isolation Guardrail critical for AI coding assistants?

Enforces strict memory isolation, Cross-Origin Isolation HTTP headers (COOP/COEP), and Atomics-based synchronization when leveraging SharedArrayBuffer across worker pools in Bun 1.2. Prevents speculative execution side-channel leaks (Spectre) and unsynchronized data races in high-throughput multi-tenant edge runtimes. 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 (Sharing raw SharedArrayBuffer instances across worker threads without cross-origin isolation headers, tenant partition bounds, and Atomics synchronization.) 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