This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: nextjs-15-server-actions-cryptographic-host-validation

Next.js 15 Server Actions Cryptographic Host and Origin Validation Barrier

Enforces deterministic origin verification and HMAC-signed cryptographic host token validation for Next.js 15 Server Actions across distributed edge deployments. Prevents cross-site action invocation (CSAI), DNS rebinding, and host-header injection across multi-region reverse proxies by binding incoming action requests to cryptographically signed edge ingress contexts.

Prohibited Anti-Pattern: Trusting raw headers or unvalidated Host/Origin headers in Server Actions across distributed proxies

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Server Actions Cryptographic Host and Origin Validation Barrier - Enforces deterministic origin verification and HMAC-signed cryptographic host token validation for Next.js 15 Server Actions across distributed edge deployments. Prevents cross-site action invocation (CSAI), DNS rebinding, and host-header injection across multi-region reverse proxies by binding incoming action requests to cryptographically signed edge ingress contexts.
globs: src/app/**/*.{ts,tsx}, src/actions/**/*.{ts,tsx}, src/middleware.ts, next.config.{js,mjs,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-server-actions-cryptographic-host-validation"
---

# Next.js 15 Server Actions Cryptographic Host and Origin Validation Barrier

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting raw headers or unvalidated Host/Origin headers in Server Actions across distributed proxies

## System Constraints
You are a Principal Software Architect enforcing zero-trust boundaries for Next.js 15 Server Actions. Distributed edge architectures, CDNs, and custom domains create vulnerabilities where Host, X-Forwarded-Host, and Origin headers can be forged or decoupled from the authenticated session context. You must enforce invariant cryptographic binding between incoming server action invocations, the validated ingress host, and the client origin before any server action mutation executes.

## Strict Guidelines
- Engineers MUST ALWAYS configure `experimental.serverActions.allowedOrigins` or production `serverActions.allowedOrigins` in `next.config.ts` with explicit, fully-qualified domain names.
- Engineers MUST NOT trust raw `headers().get('host')` or `headers().get('x-forwarded-host')` directly in Server Actions without validating against a cryptographically signed host token.
- Engineers MUST implement a constant-time cryptographic verification barrier (e.g., HMAC-SHA256 via Web Crypto API) comparing the incoming origin/host tuple against a signed ingress proof issued by the trusted edge runtime.
- Services MUST reject Server Action invocations immediately with HTTP 403 / ForbiddenActionError if the cryptographic host token is absent, expired, or tampered with.
- Components NEVER execute state mutations or database writes directly inside unshielded Server Actions without passing through an authenticated, origin-verified barrier wrapper.

## Bad vs Good Implementations
### Cryptographic Host & Origin Verification Barrier for Server Actions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on permissive substring validation on the `origin` header, fails to validate `host` against edge signatures, and permits cross-tenant and cross-origin invocation if reverse proxies forward untrusted headers.
```typescript
// Vulnerable Server Action relying on mutable or unverified Host/Origin headers
'use server';

import { headers } from 'next/headers';

export async function updateTenantBilling(tenantId: string, amount: number) {
  const headerList = await headers();
  const host = headerList.get('host');
  const origin = headerList.get('origin');

  // VULNERABLE: Direct string check or missing verification against host-poisoning in proxy topologies
  if (origin && !origin.includes('example.com')) {
    throw new Error('Unauthorized origin');
  }

  // Mutation occurs under potentially forged or rebinding Host context
  return await db.billing.update({ where: { tenantId, host }, data: { amount } });
}
```

#### Production Standard (Correct)
> **Standard**: Implements strict host-origin matching against an explicit allowlist and verifies an HMAC-SHA256 signature issued by the edge proxy using Web Crypto API. Rejects any spoofed host, cross-origin invocation, or DNS-rebound request prior to state execution.
```typescript
// Production Guardrail: Cryptographic Host & Origin Barrier
'use server';

import { headers } from 'next/headers';
import { timingSafeEqual } from 'node:crypto';

const EDGE_SIGNING_SECRET = process.env.EDGE_INGRESS_HMAC_SECRET!;
const ALLOWED_HOSTS = new Set(['app.enterprise.io', 'billing.enterprise.io']);

async function verifyCryptographicHostBarrier(): Promise<void> {
  const headerList = await headers();
  const host = headerList.get('x-forwarded-host') ?? headerList.get('host');
  const origin = headerList.get('origin');
  const hostSignature = headerList.get('x-edge-host-signature');

  if (!host || !origin || !hostSignature) {
    throw new Error('Security Violation: Missing required edge provenance headers');
  }

  const parsedOrigin = new URL(origin);
  if (parsedOrigin.host !== host || !ALLOWED_HOSTS.has(host)) {
    throw new Error('Security Violation: Origin-Host mismatch or domain not allowed');
  }

  // Verify HMAC-SHA256 signature generated at trusted ingress (CDN / Edge Gateway)
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(EDGE_SIGNING_SECRET),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify']
  );

  const signatureBytes = Uint8Array.from(Buffer.from(hostSignature, 'hex'));
  const payloadBytes = encoder.encode(`${host}:${origin}`);

  const isValid = await crypto.subtle.verify(
    'HMAC',
    key,
    signatureBytes,
    payloadBytes
  );

  if (!isValid) {
    throw new Error('Security Violation: Cryptographic host signature invalid');
  }
}

export async function updateTenantBilling(tenantId: string, amount: number) {
  await verifyCryptographicHostBarrier();
  
  return await db.billing.update({
    where: { tenantId },
    data: { amount }
  });
}
```

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: Next.js 15 Server Actions Cryptographic Host and Origin Validation Barrier

Next.js 15 Server Actions Cryptographic Host and Origin Validation Barrier defines an industrial-grade behavioral standard for security engineering. Enforces deterministic origin verification and HMAC-signed cryptographic host token validation for Next.js 15 Server Actions across distributed edge deployments. Prevents cross-site action invocation (CSAI), DNS rebinding, and host-header injection across multi-region reverse proxies by binding incoming action requests to cryptographically signed edge ingress contexts. 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 raw headers or unvalidated Host/Origin headers in Server Actions across distributed proxies 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 raw headers or unvalidated Host/Origin headers in Server Actions across distributed proxiesCritical
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 configure `experimental.serverActions.allowedOrigins` or production `serverActions.allowedOrigins` in `next.config.ts` with explicit, fully-qualified domain names.

Engineers MUST ALWAYS configure `experimental.serverActions.allowedOrigins` or production `serverActions.allowedOrigins` in `next.config.ts` with explicit, fully-qualified domain names.

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 trust raw `headers().get('host')` or `headers().get('x-forwarded-host')` directly in Server Actions without validating against a cryptographically signed host token.

Engineers MUST NOT trust raw `headers().get('host')` or `headers().get('x-forwarded-host')` directly in Server Actions without validating against a cryptographically signed host token.

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 implement a constant-time cryptographic verification barrier (e.g., HMAC-SHA256 via Web Crypto API) comparing the incoming origin/host tuple against a signed ingress proof issued by the trusted edge runtime.

Engineers MUST implement a constant-time cryptographic verification barrier (e.g., HMAC-SHA256 via Web Crypto API) comparing the incoming origin/host tuple against a signed ingress proof issued by the trusted edge runtime.

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 Server Action invocations immediately with HTTP 403 / ForbiddenActionError if the cryptographic host token is absent, expired, or tampered with.

Services MUST reject Server Action invocations immediately with HTTP 403 / ForbiddenActionError if the cryptographic host token is absent, expired, or tampered with.

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 execute state mutations or database writes directly inside unshielded Server Actions without passing through an authenticated, origin-verified barrier wrapper.

Components NEVER execute state mutations or database writes directly inside unshielded Server Actions without passing through an authenticated, origin-verified barrier wrapper.

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 Next.js 15 Server Actions Cryptographic Host and Origin Validation Barrier critical for AI coding assistants?

Enforces deterministic origin verification and HMAC-signed cryptographic host token validation for Next.js 15 Server Actions across distributed edge deployments. Prevents cross-site action invocation (CSAI), DNS rebinding, and host-header injection across multi-region reverse proxies by binding incoming action requests to cryptographically signed edge ingress contexts. 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 raw headers or unvalidated Host/Origin headers in Server Actions across distributed proxies) 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

Next.js