The Complete Production SOP: How to Deploy and Run CORS Access-Control Hardening & Preflight Checks in Autonomous AI Agents
Step-by-step SOP to install and run CORS Access-Control Hardening & Preflight Checks in Codex, Claude Code, and Cursor. Fix preflight leaks and wildcards.
Technical Overview & Architectural Context
Autonomous coding agents like Claude Code, Codex, Cursor, and Windsurf frequently introduce critical security vulnerabilities when implementing Cross-Origin Resource Sharing (CORS). When developers prompt an agent with vague instructions like 'enable CORS for the frontend', LLMs routinely hallucinate quick-fix patterns: returning 'Access-Control-Allow-Origin: *', reflecting untrusted Origin headers blindly, or pairing wildcard origins with 'Access-Control-Allow-Credentials: true'—which causes browser-level failures and severe data-exfiltration attack surfaces. Furthermore, agents often miss handling preflight HTTP OPTIONS requests or fail to emit 'Vary: Origin', poisoning reverse-proxy caches. The 'cors-origin-preflight-hardening' skill provides deterministic guardrails. By encoding exact-match allowlists, enforcing RFC-compliant preflight responses with explicit HTTP 204/200 status codes, restricting allowed methods and headers, and preventing unauthenticated wildcard leaks, this SKILL.md equips agents with an invariant checklist. The agent self-corrects and refuses insecure fallbacks, ensuring robust API boundary security across Node.js, Python, Go, and Rust backends without human intervention.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules.
Agent runtimes such as Claude Code and Cursor scan defined directories for SKILL.md files containing standard frontmatter triggers. By placing the hardened CORS manifest in either ~/.agents/skills/cors-origin-preflight-hardening/SKILL.md or .cursor/skills/cors-origin-preflight-hardening/SKILL.md, the runtime parses the YAML triggers ('configure cors allowlist', 'fix cors preflight error', 'prevent insecure cors wildcard') into the agent's intent-routing table.
mkdir -p ~/.agents/skills/cors-origin-preflight-hardening && curl -fsSL https://askills.dev/api/skills/cors-origin-preflight-hardening/raw -o ~/.agents/skills/cors-origin-preflight-hardening/SKILL.md---
name: "cors-origin-preflight-hardening"
description: "Configure secure Cross-Origin Resource Sharing (CORS) without wildcards or leaks."
metadata:
author: "MDN Web Docs"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "configure cors allowlist"
- "fix cors preflight error"
- "prevent insecure cors wildcard"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# CORS Access-Control Hardening & Preflight Checks
Configures production CORS policies: exact origin matching, validating Origin headers against dynamic allowlists, handling OPTIONS preflights, and preventing Access-Control-Allow-Origin: * with credentials.
## Execution SOP & Rules
1. Match incoming Origin headers against an explicit array of allowed domain strings.
2. Never return Access-Control-Allow-Origin: * when Access-Control-Allow-Credentials is true.
3. Include Vary: Origin in responses when dynamically reflecting allowed origins.
4. Limit Access-Control-Allow-Headers and Access-Control-Allow-Methods strictly to required values.Keep the SKILL.md under 250 tokens; autonomous agents retain procedural checklists far better when triggers and strict invariant negative-rules ('Never return * with credentials') are stated tersely without fluff.
Ensure permissions.fs_write is restricted to 'workspace'. Setting fs_write to 'all' or granting net_access unnecessarily may trigger runtime sandbox isolation rejections in Windsurf and Claude Code.
Environment Secrets & Dependency Validation
Inject allowed origins through deterministic environment configurations rather than hardcoding in source code.
Hardcoding CORS origins into controller code creates operational hazards across staging and production. Ensure the workspace exposes parsed origin allowlists via environment variables (e.g., CORS_ALLOWED_ORIGINS) and make sure the skill instructs the agent to read from process.env or os.environ without checking secrets or sensitive keys into source control.
echo 'CORS_ALLOWED_ORIGINS="https://app.example.com,https://staging.example.com"' >> .env.local && git check-ignore -v .env.local || echo '.env.local' >> .gitignoreconst rawOrigins = process.env.CORS_ALLOWED_ORIGINS || '';
export const ALLOWED_ORIGINS: ReadonlySet<string> = new Set(
rawOrigins.split(',').map((o) => o.trim()).filter(Boolean)
);
export function isOriginAllowed(origin: string | undefined): boolean {
if (!origin) return false;
return ALLOWED_ORIGINS.has(origin);
}Use a ReadonlySet for O(1) lookups. Do not allow regex-based origin validation unless anchor tokens (^ and $) are enforced, as agents frequently write flawed regexes like /example\.com/ that match attacker.example.com.
Never add credentials: true without verifying that the origin isn't undefined or an empty string, or clients will fail on browser preflight.
Intent Matching & Trigger Invocation
Verify deterministic activation using tested natural language prompts.
When invoking Codex, Claude Code, Cursor, or Windsurf, trigger terms must be provided directly in your prompt to activate the skill routing. The skill intercepts the generation process and injects its SOP before the model drafts the middleware.
claude-code "configure cors allowlist and fix cors preflight error for our Express API; prevent insecure cors wildcard"import { Request, Response, NextFunction } from 'express';
import { isOriginAllowed } from '../config/cors';
export function hardenedCors(req: Request, res: Response, next: NextFunction): void {
const origin = req.headers.origin;
if (origin && isOriginAllowed(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
res.setHeader('Access-Control-Max-Age', '86400');
if (req.method === 'OPTIONS') {
res.status(204).end();
return;
}
next();
}Always specify HTTP 204 (No Content) instead of HTTP 200 for OPTIONS preflights to prevent empty body parsing errors in older WebKit clients.
If 'Vary: Origin' is omitted when reflecting dynamic origins, downstream CDNs (e.g., Cloudflare, CloudFront) will cache the response from one origin and serve it to another origin, breaking CORS for subsequent users.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks before accepting agent deliverables.
The skill mandates running local lint and automated integration tests checking for exact origin reflection and rejecting unauthorized origins before concluding the run.
npm test -- --testPathPattern=cors.test.ts && npm run lintimport request from 'supertest';
import app from '../src/app';
describe('Hardened CORS Middleware', () => {
it('reflects authorized origin and appends Vary header', async () => {
const res = await request(app)
.get('/api/health')
.set('Origin', 'https://app.example.com');
expect(res.headers['access-control-allow-origin']).toBe('https://app.example.com');
expect(res.headers['access-control-allow-credentials']).toBe('true');
expect(res.headers['vary']).toContain('Origin');
});
it('rejects unauthorized origin from CORS headers', async () => {
const res = await request(app)
.get('/api/health')
.set('Origin', 'https://malicious-site.com');
expect(res.headers['access-control-allow-origin']).toBeUndefined();
});
it('handles OPTIONS preflight with 204 status', async () => {
const res = await request(app)
.options('/api/health')
.set('Origin', 'https://app.example.com')
.set('Access-Control-Request-Method', 'POST');
expect(res.status).toBe(204);
expect(res.headers['access-control-allow-methods']).toContain('POST');
});
});Instruct the agent to review git diff output to ensure no wildcard '*' slipped back into fallback logic.
Agents running in headless test containers might not have .env loaded; guarantee tests instantiate process.env.CORS_ALLOWED_ORIGINS explicitly in beforeAll hooks.
Real-World Scenario: Remediating High-Severity CORS Wildcard Vulnerability in Express Backend
“Our security audit flagged a vulnerability where 'Access-Control-Allow-Origin: *' is combined with credentials on /api/user. Please configure cors allowlist, prevent insecure cors wildcard, and fix cors preflight error across all routes.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent attempted a lazy fix by setting Access-Control-Allow-Origin: * alongside Access-Control-Allow-Credentials: true, violating the W3C CORS specification.
Replace wildcard with dynamic match: if (isOriginAllowed(req.headers.origin)) { res.setHeader('Access-Control-Allow-Origin', req.headers.origin); res.setHeader('Access-Control-Allow-Credentials', 'true'); }Root Cause: The server responded to an HTTP OPTIONS preflight request with 401/403 or passed it directly to downstream route handlers that require session authorization tokens.
Ensure OPTIONS requests terminate immediately before authentication middlewares: if (req.method === 'OPTIONS') { res.status(204).end(); return; }Frequently Asked Questions (CORS Access-Control Hardening & Preflight Checks SOP)
Q:Can I use CORS Access-Control Hardening & Preflight Checks across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres to the universal SKILL.md specification. You can symlink ~/.agents/skills/cors-origin-preflight-hardening/SKILL.md to .cursor/skills/ or .windsurf/skills/ inside your repository to share the exact same configuration across all tools.
Q:How does CORS Access-Control Hardening & Preflight Checks prevent context window overflow during long agent sessions?
By isolating exact procedural rules in SKILL.md and using targeted triggers, the agent loads CORS constraints only when relevant, rather than bloating persistent system prompts with dozens of pages of API security guidelines.
Q:Does this skill require escalated root or container permissions?
No. The skill is rated 98/100 on security. It requires fs_read: true and fs_write: 'workspace' only, with shell_exec and net_access set to false, ensuring completely safe local execution inside workspace-scoped sandboxes.
Ready to equip your autonomous agent with CORS Access-Control Hardening & Preflight Checks?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.