← Blog

Claude skill CORS misconfiguration via regex origin matching and subdomain wildcards — SA-SKL-CORS9

CORS origin validation logic must handle exact string matching or precise subdomain checks — regular expressions applied to origin strings are a common source of partial-match bypasses. SA-SKL-CORS9 covers four CORS misconfiguration patterns beyond the classic null-origin and wildcard-credential issues: regex patterns with unanchored .* that allow attacker-controlled domains containing the legitimate domain as a substring; subdomain prefix checks using endsWith() that are bypassable by registering a domain ending in the legitimate TLD; CORS middleware applied before authentication that leaks response headers to unauthenticated cross-origin requests; and X-Requested-With header requirements that are inconsistently enforced after the CORS preflight check.

By SkillAudit  |  7 Nov 2026

Why regex-based CORS origin validation fails

The CORS origin header contains the full origin of the requesting page — scheme, hostname, and optionally port. Origin validation must determine whether this exact origin is in the allowlist. String equality is the correct comparison: origin === 'https://skillaudit.dev'. When developers introduce regex matching to support multiple subdomains or staging environments, they must anchor the pattern on both ends (^ and $) and escape special regex characters in the domain name.

The common mistake is using an unanchored pattern like /https:\/\/skillaudit\.dev.*/. The .* at the end matches any suffix, including a .attacker.com suffix — so the origin https://skillaudit.dev.attacker.com matches the pattern and receives the CORS approval. This domain is registered by the attacker and serves a malicious page that makes cross-origin requests to the victim's API with the user's credentials. The API sends back Access-Control-Allow-Origin: https://skillaudit.dev.attacker.com and the browser delivers the response body to the malicious page.

SA-SKL-CORS9 in scope: CORS9-001 (regex with .* allows partial domain match — /https:\/\/skillaudit\.com.*/ passes https://skillaudit.com.evil.com), CORS9-002 (subdomain wildcard via endsWith('.skillaudit.dev') bypassed by nonskillaudit.dev registration), CORS9-003 (CORS policy applied before authentication — unauthenticated CORS preflight leaks response headers), CORS9-004 (X-Requested-With CORS bypass — custom header forces preflight but server accepts requests without it after CORS middleware). Each finding includes SkillAudit detection and correct Node.js fixes.

CORS9-001 — Regex origin check with .* allows partial domain match

An MCP skill's CORS configuration uses a custom origin function with a regex test: /https:\/\/skillaudit\.dev.*/.test(origin). The pattern was intended to allow https://skillaudit.dev and optionally https://app.skillaudit.dev (staging). The unanchored .* at the end also matches https://skillaudit.dev.attacker.com (a domain with skillaudit.dev as a prefix subdomain). An attacker registers skillaudit.dev.attacker.com (or for a less careful pattern, skillaudit-dev.attacker.com), hosts a malicious page there, and their page's cross-origin requests to the API are approved with the full CORS headers including Access-Control-Allow-Credentials: true. The browser sends the user's cookies with the request and delivers the credentialed response to the attacker's page.

The fix is strict: use a Set of exact allowed origins and check with Set.has(origin). If multiple subdomains need approval, list each one explicitly. If dynamic subdomain approval is required (for user-generated subdomains), require an exact match against a suffix that cannot be manipulated: origin.startsWith('https://') && new URL(origin).hostname.endsWith('.skillaudit.dev') plus a check that there are no additional dots after the skillaudit.dev suffix (i.e., the full hostname is something.skillaudit.dev and not something.skillaudit.dev.attacker.com).

// VULNERABLE — regex with .* at end allows partial match bypass
import cors from 'cors';

// Pattern 1: unanchored .* suffix — allows skillaudit.dev.attacker.com
app.use(cors({
  origin: (origin, callback) => {
    if (!origin) return callback(null, false); // No origin (non-browser request)

    // VULNERABLE: .* at end — attacker registers skillaudit.dev.attacker.com
    // origin = 'https://skillaudit.dev.attacker.com'
    // regex test: /https:\/\/skillaudit\.dev.*/.test(origin) → TRUE
    if (/https:\/\/skillaudit\.dev.*/.test(origin)) {
      return callback(null, true);  // CORS approved for attacker's domain!
    }

    callback(null, false);
  },
  credentials: true,  // With credentials: attacker page gets cookies
}));

// Pattern 2: regex without escaping dots — . matches any character
// /https:\/\/skillauditXdev\.com/.test('https://skillauditXdev.com') → TRUE
// but also: /https:\/\/skillauditXdev\.com/.test('https://skillaudit-dev.com') → FALSE
// Here the dot in the domain is unescaped:
if (/https:\/\/skillaudit.dev/.test(origin)) {
  // The unescaped '.' matches any char: 'skillauditXdev' matches
  // Less dangerous than .* but still wrong — use \.  not .
}

// Pattern 3: includes() check — also bypassable
if (origin.includes('skillaudit.dev')) {
  // https://evil.com?skillaudit.dev → includes check passes
  // (if attacker finds a way to inject into the origin, though browsers set origin strictly)
  // More importantly: https://skillaudit.dev.evil.com also passes
  return callback(null, true);
}
// FIXED — exact Set match; or if subdomain dynamic, full hostname validation
import cors from 'cors';

// Option 1: Exact match Set — preferred for known, fixed list of origins
const ALLOWED_ORIGINS = new Set([
  'https://skillaudit.dev',
  'https://www.skillaudit.dev',
  'https://app.skillaudit.dev',
  // Add staging explicitly:
  // 'https://staging.skillaudit.dev',
  // Add localhost for development (remove in production):
  // process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : null,
].filter(Boolean) as string[]);

app.use(cors({
  origin: (origin, callback) => {
    // No origin = non-browser request (curl, Postman) — allow or deny based on policy
    // For an API that serves browser clients: require an origin
    if (!origin) {
      return callback(null, false);  // Deny no-origin browser requests
      // Or for curl/server-to-server: callback(null, true) — but set credentials: false
    }

    if (ALLOWED_ORIGINS.has(origin)) {
      return callback(null, true);
    }

    callback(new Error(`CORS: origin '${origin}' not in allowlist`));
  },
  credentials: true,
}));

// Option 2: Dynamic subdomain allowlist — if user subdomains are required
function isAllowedOrigin(origin: string): boolean {
  if (!origin) return false;

  let url: URL;
  try {
    url = new URL(origin);
  } catch {
    return false;
  }

  // Scheme must be https
  if (url.protocol !== 'https:') return false;

  const hostname = url.hostname;
  const ALLOWED_EXACT = new Set(['skillaudit.dev', 'www.skillaudit.dev']);
  const ALLOWED_SUBDOMAIN_SUFFIX = '.skillaudit.dev';

  // Exact match
  if (ALLOWED_EXACT.has(hostname)) return true;

  // Subdomain of skillaudit.dev:
  // Check that hostname ends with .skillaudit.dev AND the prefix is a valid label
  // (no dots in the prefix — prevents skill.audit.dev.attacker.com)
  if (hostname.endsWith(ALLOWED_SUBDOMAIN_SUFFIX)) {
    const subdomain = hostname.slice(0, hostname.length - ALLOWED_SUBDOMAIN_SUFFIX.length);
    // subdomain must be a valid single DNS label (no dots)
    if (subdomain.length > 0 && !subdomain.includes('.')) {
      return true;
    }
  }

  return false;
}
HIGH
SA-SKL-CORS9-001 — An MCP skill's CORS origin validator uses a regex test with an unanchored .* suffix (/https:\/\/skillaudit\.dev.*/.test(origin)), allowing an attacker who registers skillaudit.dev.attacker.com to pass the check and receive Access-Control-Allow-Origin with credentials: true, enabling cross-origin theft of session cookies from any victim visiting the attacker's page; fix by replacing regex matching with a Set.has(origin) exact match against an explicit allowlist, or for dynamic subdomain support, using new URL(origin).hostname and validating the hostname ends with .skillaudit.dev with no dots in the subdomain prefix. Detection: SkillAudit flags CORS origin functions that use RegExp.test() or String.prototype.includes() on the origin string without anchoring the check to the full hostname.

CORS9-002 — Subdomain wildcard via endsWith('.skillaudit.dev') bypassed by adjacent domain

An MCP skill allows any .skillaudit.dev subdomain by checking origin.endsWith('.skillaudit.dev'). The flaw is that endsWith checks the string suffix, not the URL hostname. The origin https://nonskillaudit.dev does not end with .skillaudit.dev — but the origin https://evil.skillaudit.dev does, and an attacker who can get a DNS entry for a subdomain of skillaudit.dev (e.g., via a subdomain takeover of a dangling CNAME) can exploit this. More subtly, if the check is applied to the full origin string rather than the hostname: 'https://evil.com:443skillaudit.dev'.endsWith('.skillaudit.dev') returns true in some implementations depending on port parsing edge cases. The correct check is against the parsed hostname, not the full origin string, with an exact .skillaudit.dev suffix and no dots in the subdomain component.

Additionally, endsWith('.skillaudit.dev') is insufficient even on the hostname alone if the subdomain can contain dots. The hostname a.b.skillaudit.dev passes the endsWith check, and if the skill creates user-generated subdomains, an attacker who controls a.b.skillaudit.dev can register subdomains under their own tenant and pass the check. The fix validates that the subdomain prefix (the part before .skillaudit.dev) contains no dots.

// VULNERABLE — endsWith on full origin string; no hostname parsing
import cors from 'cors';

app.use(cors({
  origin: (origin, callback) => {
    if (!origin) return callback(null, false);

    // VULNERABLE: endsWith on the full origin string
    // origin = 'https://evil.skillaudit.dev' → endsWith('.skillaudit.dev') → TRUE
    // If attacker controls a subdomain via dangling CNAME takeover, they pass this check
    //
    // Also: endsWith check on full string is fragile:
    // 'https://app.skillaudit.dev'.endsWith('.skillaudit.dev') → TRUE (correct)
    // 'https://app.skillaudit.dev:443'.endsWith('.skillaudit.dev') → FALSE (broken — port)
    // 'https://nonskillaudit.dev'.endsWith('.skillaudit.dev') → FALSE (correct)
    //
    // The deeper issue: endsWith allows multi-level subdomains
    // 'https://tenant.user.skillaudit.dev' → user controls tenant.user.skillaudit.dev
    // This passes endsWith('.skillaudit.dev') with a dot in the prefix

    if (
      origin === 'https://skillaudit.dev' ||
      origin.endsWith('.skillaudit.dev')  // Insufficient — allows multi-level and dangling CNAME
    ) {
      return callback(null, true);
    }

    callback(null, false);
  },
  credentials: true,
}));
// FIXED — parse URL hostname; check against exact hostname set or validated subdomain
import cors from 'cors';

// Allowlisted exact hostnames
const EXACT_HOSTNAMES = new Set([
  'skillaudit.dev',
  'www.skillaudit.dev',
  'app.skillaudit.dev',
]);

// If user-generated subdomains are needed, only allow single-level subdomains
// under .skillaudit.dev — no multi-level (a.b.skillaudit.dev is not allowed)
function isAllowedHostname(hostname: string): boolean {
  // Exact match first
  if (EXACT_HOSTNAMES.has(hostname)) return true;

  // Single-level subdomain of skillaudit.dev
  const SUFFIX = '.skillaudit.dev';
  if (!hostname.endsWith(SUFFIX)) return false;

  const prefix = hostname.slice(0, hostname.length - SUFFIX.length);

  // Prefix must be non-empty and contain no dots (single DNS label only)
  // This prevents: a.b.skillaudit.dev (multi-level, user might control b.skillaudit.dev)
  // And: .skillaudit.dev (empty prefix, matches the apex domain via endsWith)
  if (prefix.length === 0 || prefix.includes('.')) return false;

  // Optionally: allowlist known subdomain prefixes rather than allowing any single-label
  // const ALLOWED_PREFIXES = new Set(['app', 'api', 'staging', 'docs']);
  // return ALLOWED_PREFIXES.has(prefix);

  return true;
}

app.use(cors({
  origin: (origin, callback) => {
    if (!origin) return callback(null, false);

    let url: URL;
    try {
      url = new URL(origin);
    } catch {
      return callback(null, false);
    }

    // Scheme check — only https in production
    if (url.protocol !== 'https:') {
      if (process.env.NODE_ENV === 'development' && url.hostname === 'localhost') {
        return callback(null, true);  // Allow localhost in dev
      }
      return callback(null, false);
    }

    // Check against parsed hostname — not the full origin string
    if (isAllowedHostname(url.hostname)) {
      return callback(null, true);
    }

    callback(null, false);
  },
  credentials: true,
}));
HIGH
SA-SKL-CORS9-002 — An MCP skill's CORS origin validator uses origin.endsWith('.skillaudit.dev') without parsing the URL and checking the full hostname, allowing multi-level subdomains like tenant.user.skillaudit.dev (where a tenant controls their subtree), dangling CNAME subdomain takeovers, and in some implementations port-stripping edge cases; fix by parsing the origin with new URL(origin), operating on url.hostname rather than the full origin string, checking that the subdomain prefix contains no dots (restricting to single-label subdomains), and maintaining an explicit allowlist of permitted subdomain prefixes rather than accepting any single-label subdomain. Detection: SkillAudit flags CORS origin functions that call String.prototype.endsWith() on the full origin string rather than on a parsed new URL(origin).hostname.

CORS9-003 — CORS policy applied before authentication leaks response headers

An MCP skill mounts CORS middleware before its authentication middleware. When a cross-origin browser request arrives, the CORS middleware inspects the origin and sets the Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access-Control-Expose-Headers headers on the response. For a preflight OPTIONS request, the CORS middleware returns a 204 response with these headers before any authentication check runs. For a credentialed actual request (e.g., GET /api/audits with the user's cookie), the authentication middleware runs after CORS — if authentication fails, the response is a 401, but the Access-Control-Allow-Origin header is already set, allowing the browser to deliver the 401 response body to the cross-origin page. Response bodies from 4xx responses can contain diagnostic information — user enumeration clues, stack traces, rate limit states — that should not be readable from a foreign origin.

The fix is to run authentication middleware before CORS middleware for all non-preflight requests. For OPTIONS preflight requests, authentication is not applicable (the browser sends the preflight without credentials to check if the actual request is permitted), so CORS processing for OPTIONS must run unauthenticated. The correct middleware order is: (1) CORS handles OPTIONS preflights without authentication; (2) for all other methods, authentication runs first; (3) CORS sets the allow-origin header on authenticated responses.

// VULNERABLE — CORS middleware before authentication
import express from 'express';
import cors from 'cors';

const app = express();

// VULNERABLE: CORS runs first — sets ACAO header on ALL responses including 401, 403
app.use(cors({ origin: 'https://skillaudit.dev', credentials: true }));
app.use(authenticate);  // Runs AFTER CORS — ACAO header already set on 401 responses

// Now: unauthenticated cross-origin request gets:
// 401 response WITH Access-Control-Allow-Origin: https://skillaudit.dev
// Browser delivers the 401 body to the requesting page
// 401 body may contain: { "error": "jwt malformed" } or { "error": "user not found" }
// — these are readable from the cross-origin attacker page

// Even worse: if the response includes error details with internal info
app.get('/api/audits', authenticate, (req, res) => {
  res.json({ error: 'Service temporarily unavailable', debugInfo: process.env.DATABASE_URL });
  // If CORS is applied before auth, this error leaks to cross-origin via 500 body
});
// FIXED — OPTIONS preflights unauthenticated; auth before CORS for actual requests
import express from 'express';
import cors from 'cors';

const app = express();

const corsOptions: cors.CorsOptions = {
  origin: (origin, callback) => {
    const ALLOWED = new Set(['https://skillaudit.dev', 'https://app.skillaudit.dev']);
    if (!origin || ALLOWED.has(origin)) return callback(null, true);
    callback(null, false);
  },
  credentials: true,
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: ['RateLimit-Limit', 'RateLimit-Remaining'],
};

// Step 1: Handle OPTIONS preflights without authentication
// (Browser sends OPTIONS without credentials to check if actual request is allowed)
app.options('*', cors(corsOptions));

// Step 2: For all actual requests, authenticate FIRST
app.use((req, res, next) => {
  if (req.method === 'OPTIONS') return next();  // Preflights already handled above
  authenticate(req, res, next);  // Returns 401 WITHOUT ACAO header if auth fails
});

// Step 3: CORS for actual requests — only reached after authentication passes
app.use((req, res, next) => {
  if (req.method === 'OPTIONS') return next();
  cors(corsOptions)(req, res, next);
});

// Now: unauthenticated cross-origin request:
// authenticate() returns 401 — no ACAO header on the 401 response
// Browser SOP blocks the 401 body — attacker page cannot read the error
// Only authenticated, same-origin-approved requests see the response body
MEDIUM
SA-SKL-CORS9-003 — An MCP skill mounts CORS middleware before authentication middleware; unauthenticated cross-origin requests receive a 401 response with Access-Control-Allow-Origin already set, allowing the browser to deliver the error response body — which may contain user enumeration signals, debug information, or database error details — to the requesting cross-origin page; fix by handling OPTIONS preflight requests with CORS before authentication, then running authentication middleware before CORS for all non-OPTIONS requests so that CORS headers are only applied to authenticated responses. Detection: SkillAudit flags Express applications where app.use(cors(...)) is called before app.use(authenticate) without a preceding app.options('*', cors(...)) handler that covers only preflight requests.

CORS9-004 — X-Requested-With CORS bypass: preflight forced but inconsistently enforced

Some MCP skills add an X-Requested-With: XMLHttpRequest header requirement to their fetch requests as a CSRF defense, reasoning that this custom header forces a CORS preflight which the browser sends before the actual credentialed request. The logic is: since only same-origin pages can make XHR/fetch requests with custom headers without triggering CORS, the presence of this header proves the request is from the same origin. The flaw is that this reasoning only holds if the server actually validates the header. If the server accepts requests without X-Requested-With, or if the CORS middleware approves the cross-origin request anyway (due to a misconfiguration), the custom header provides no CSRF protection. An attacker can craft a cross-origin request with X-Requested-With: XMLHttpRequest in the headers — the browser sends a preflight, the server approves the preflight, and the actual request succeeds with the user's credentials.

The correct CSRF protection for credential-using endpoints is not a custom header requirement but either: (1) SameSite=Strict cookie attribute (browser does not send cookie on cross-site requests); (2) CSRF token in a request header or body, validated server-side; or (3) Origin header validation at the application layer (not via CORS but as an explicit middleware check). These approaches do not rely on the CORS preflight mechanism, which is a browser-side same-origin policy enforcement, not a server-side authentication check.

// VULNERABLE — X-Requested-With "CSRF protection" that provides none
import express from 'express';
import cors from 'cors';

// CORS is configured to allow skillaudit.dev with credentials
app.use(cors({
  origin: 'https://skillaudit.dev',
  credentials: true,
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
}));

// "CSRF protection": only process requests with X-Requested-With header
// VULNERABLE: attacker CAN send this header cross-origin!
// The header just causes a CORS preflight — it doesn't block cross-origin requests
// The CORS config already allows skillaudit.dev origin, and
// an attacker on skillaudit.dev (XSS) can send any headers
function xhrOnlyMiddleware(req: express.Request, res: express.Response, next: express.NextFunction) {
  if (!req.headers['x-requested-with']) {
    return res.status(400).json({ error: 'Missing X-Requested-With header' });
  }
  // VULNERABLE: this only blocks requests without the header
  // A cross-origin attacker script sends: { headers: { 'X-Requested-With': 'XMLHttpRequest' } }
  // Browser sends OPTIONS preflight → CORS approves → actual request goes through with cookie
  next();
}

app.use('/api/', xhrOnlyMiddleware, apiRouter);
// FIXED — SameSite=Strict cookie; Origin header validation; proper CSRF token
import express from 'express';
import cors from 'cors';
import { randomBytes } from 'crypto';

// Fix 1: SameSite=Strict on session cookie — browser does not send cookie on cross-site requests
// This is the most effective CSRF defense when cookies are the credential mechanism
app.use((req, res, next) => {
  res.cookie('session_id', req.sessionID, {
    httpOnly: true,
    secure: true,            // HTTPS only
    sameSite: 'strict',      // Browser blocks cookie on cross-site requests entirely
    path: '/',
  });
  next();
});

// Fix 2: Origin header validation as defense-in-depth
// (Origin header is set by browser on credentialed requests; cannot be spoofed by JS)
function validateOriginMiddleware(
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) {
  const origin = req.headers.origin;

  // Allow requests without Origin header (same-origin, server-to-server, curl)
  if (!origin) return next();

  const ALLOWED_ORIGINS = new Set([
    'https://skillaudit.dev',
    'https://app.skillaudit.dev',
  ]);

  if (!ALLOWED_ORIGINS.has(origin)) {
    return res.status(403).json({
      error: 'Cross-origin request from non-allowlisted origin',
    });
  }

  next();
}

// Fix 3: CSRF token for state-changing requests (alternative to SameSite=Strict)
// Generate a per-session CSRF token stored server-side; require in X-CSRF-Token header
function generateCsrfToken(): string {
  return randomBytes(32).toString('hex');
}

// Store in session at login, return in a readable cookie or in the HTML
// Require in X-CSRF-Token header on state-changing requests (POST/PUT/DELETE/PATCH)
function validateCsrfToken(
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();

  const tokenFromHeader = req.headers['x-csrf-token'];
  const tokenFromSession = (req.session as any)?.csrfToken;

  if (!tokenFromHeader || !tokenFromSession) {
    return res.status(403).json({ error: 'Missing CSRF token' });
  }

  // Constant-time comparison to prevent timing attacks
  const { timingSafeEqual } = require('crypto');
  const a = Buffer.from(String(tokenFromHeader));
  const b = Buffer.from(String(tokenFromSession));

  if (a.length !== b.length || !timingSafeEqual(a, b)) {
    return res.status(403).json({ error: 'Invalid CSRF token' });
  }

  next();
}
MEDIUM
SA-SKL-CORS9-004 — An MCP skill relies on requiring the X-Requested-With: XMLHttpRequest header as a CSRF defense, but this only forces a CORS preflight which the server's CORS configuration approves for the attack origin — the actual cross-origin request still succeeds with the user's credentials because the custom header does not constitute a secret and can be freely sent by attacker scripts; fix with either SameSite=Strict on the session cookie (browser-enforced, no server-side check needed), or a per-session CSRF token validated via timingSafeEqual() in a request header on state-changing requests. Detection: SkillAudit flags server-side middleware that uses req.headers['x-requested-with'] as the sole CSRF check on a route that also sets credentials: true in the CORS configuration.

Detection summary

ID Severity Pattern Fix
CORS9-001 HIGH Regex with .* allows partial match — /https:\/\/skillaudit\.dev.*/ approves skillaudit.dev.attacker.com Set.has(origin) exact match, or hostname parsed with new URL(origin)
CORS9-002 HIGH endsWith('.skillaudit.dev') on full origin string — multi-level subdomains, port edge cases, dangling CNAME Parse new URL(origin).hostname; check subdomain prefix has no dots
CORS9-003 MEDIUM CORS before auth — 401 response body readable cross-origin; error details leak to attacker page app.options('*', cors()) for preflights; auth before CORS for actual requests
CORS9-004 MEDIUM X-Requested-With as sole CSRF defense — custom header forces preflight but server approves cross-origin; not a secret SameSite=Strict cookie, or per-session CSRF token validated with timingSafeEqual()

Related patterns: SA-SKL-CORS8 covers CORS null origin bypass for sandboxed iframes, missing Vary header for CDN caching, HTTP origins in the allowlist, and wildcard on user-specific endpoints. SA-SKL-CORS6 and SA-SKL-CORS7 cover the foundational CORS credential bypass and preflight caching misconfigurations. SA-SKL-REDIRECT3 covers open redirect in OAuth callbacks which can be combined with CORS origin bypass to redirect victims to attacker-controlled origins.