Claude skill SSE client security — SA-SKL-SSECLIENT
Server-Sent Events (SSE) are a natural fit for MCP skills that need to stream audit progress, real-time analysis results, or live log output to a browser client. The SSE protocol is simpler than WebSockets — a persistent HTTP response with text/event-stream content type — but that simplicity hides four security patterns that SkillAudit finds consistently: the SSE endpoint lacks authentication so any client can subscribe to any user's stream, user-controlled content is injected into the SSE data: field via string interpolation creating event-injection, the event id: field exposes sequential resource IDs enabling enumeration, and the missing retry: field causes all clients to reconnect simultaneously on a server restart. SSECLIENT-001 through SSECLIENT-004 cover each with the specific vulnerable pattern and an auditable fix.
Why SSE security is distinct from WebSocket and REST security
SSE is a unidirectional HTTP streaming protocol — the server pushes events, the client only listens. This one-way nature creates a false sense of security: developers often assume that because clients cannot send data over the SSE channel, the channel itself is low-risk. But the SSE channel carries the server's output, which may include sensitive data from other users if authentication is missing. And the SSE wire format is a text protocol with meaningful field delimiters — a newline followed by a known prefix (data:, event:, id:) — which means that user-controlled content interpolated into event fields can inject synthetic events into the stream, potentially delivering false audit results or admin event types to a victim's browser. These SSE-specific attack surfaces are not covered by REST security tooling.
SA-SKL-SSECLIENT in scope: SSECLIENT-001 (SSE endpoint unauthenticated), SSECLIENT-002 (SSE data field injection via newline), SSECLIENT-003 (sequential event ID leaks enumerable resource IDs), SSECLIENT-004 (missing retry field causes thundering herd). For WebSocket security see SA-SKL-WEBSOCKET.
SSECLIENT-001 — SSE endpoint lacks authentication
An MCP skill adds a GET /events endpoint to stream audit job progress to the browser. The endpoint sets Content-Type: text/event-stream and starts pushing job status events. Because SSE is a GET request, some developers treat it as a "read-only" endpoint and skip authentication — particularly when the same route pattern for static files or public API endpoints is not protected. The result is that any client who knows or guesses an audit job ID can subscribe to its progress stream. In a shared platform, this means any registered user can receive real-time audit results for another user's private repository scan. Combined with the enumerable job IDs in SSECLIENT-003, an attacker can enumerate job IDs and subscribe to all active audit streams without authentication.
// VULNERABLE: SSE endpoint missing authentication middleware
const express = require('express');
const app = express();
// All API routes are protected with authMiddleware...
app.use('/api/', authMiddleware);
// VULNERABLE: /events route is NOT under /api/ — skips authMiddleware entirely
// Any client can subscribe to any job's SSE stream
app.get('/events/:jobId', async (req, res) => {
const { jobId } = req.params;
// Sets SSE headers without checking if the requesting user owns this job
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
// VULNERABLE: streams audit results to anyone who requests this URL
const job = await db.jobs.findOne({ id: jobId });
// No check: does req.user own this job?
const unsubscribe = eventEmitter.on(`job:${jobId}`, (event) => {
res.write(`data: ${JSON.stringify(event)}\n\n`);
});
req.on('close', unsubscribe);
});
// FIXED: SSE endpoint protected by authentication and ownership check
const express = require('express');
// Option 1: Move SSE under /api/ so authMiddleware applies
app.get('/api/events/:jobId', authMiddleware, async (req, res) => {
const { jobId } = req.params;
const userId = req.user.id;
// Verify requesting user owns this job
const job = await db.jobs.findOne({ id: jobId, userId });
if (!job) {
return res.status(404).json({ error: 'Job not found' });
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no'); // Disable Nginx/proxy buffering for SSE
res.flushHeaders();
// Send initial connection confirmation
res.write(`event: connected\ndata: ${JSON.stringify({ jobId, status: job.status })}\n\n`);
const handler = (event) => {
// JSON.stringify prevents newline injection (SSECLIENT-002)
res.write(`id: ${crypto.randomUUID()}\n`); // Random UUID, not sequential ID (SSECLIENT-003)
res.write(`retry: 5000\n`); // 5s reconnect delay (SSECLIENT-004)
res.write(`data: ${JSON.stringify(event)}\n\n`);
};
eventEmitter.on(`job:${jobId}`, handler);
req.on('close', () => {
eventEmitter.off(`job:${jobId}`, handler);
});
});
// Option 2: If SSE must use a separate path, apply auth explicitly
app.get('/events/:jobId', authMiddleware, ownershipCheckMiddleware, sseHandler);
GET /events/:jobId does not apply authentication middleware; because SSE uses a standard GET request, it is frequently omitted from API route groups that apply authMiddleware; any client who knows a job ID can subscribe to its real-time event stream, receiving private audit results, error messages, and job metadata for other users. Fix: include the SSE route under the same route prefix that applies authMiddleware (e.g., /api/events/); add an ownership check verifying the authenticated user owns the requested job ID; return 404 (not 403) on ownership failure to avoid leaking job existence. Detection: SkillAudit flags SSE route handlers (responses with Content-Type: text/event-stream) that do not invoke an authentication function before the first res.write().SSECLIENT-002 — SSE data field injection via user content
The SSE wire format is line-based. Each event is a sequence of field lines (data: ..., event: ..., id: ...) terminated by a blank line (\n\n). The parser splits on newlines and treats each line's field prefix as a field name. If user-controlled content is interpolated into an SSE field via string concatenation rather than JSON serialization, a user can inject a newline followed by a synthetic field: \n\nevent: admin\ndata: {"role":"admin"}. When the client's EventSource parser receives this, it sees a legitimate event: admin event with the attacker-controlled payload. If the client dispatches on event type (e.g., eventSource.addEventListener('admin', ...)), it executes attacker-controlled logic. This is analogous to HTTP response splitting for SSE streams.
// VULNERABLE: user-controlled content interpolated into SSE data field
app.get('/api/events/:jobId', authMiddleware, ownershipCheckMiddleware, (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.flushHeaders();
eventEmitter.on(`job:${req.params.jobId}`, (event) => {
// event.message may contain user-controlled content (e.g., the filename being scanned)
// VULNERABLE: string interpolation — newlines in event.message inject SSE fields
res.write(`data: ${event.message}\n\n`);
// Attack payload: event.message = "scan complete\n\nevent: admin\ndata: {\"isAdmin\":true}"
// Client receives:
// data: scan complete
// (blank line = end of first event)
// event: admin
// data: {"isAdmin":true}
// (blank line = end of second synthetic event)
// eventSource.addEventListener('admin', e => setAdminUI(JSON.parse(e.data))) fires
});
});
// FIXED: JSON.stringify() all event data — newlines become \n escape sequences
app.get('/api/events/:jobId', authMiddleware, ownershipCheckMiddleware, (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders();
eventEmitter.on(`job:${req.params.jobId}`, (event) => {
// FIXED: JSON.stringify converts all newlines to \n escape sequences
// "\n\nevent: admin\ndata: evil" becomes "\"\\n\\nevent: admin\\ndata: evil\""
// The SSE parser sees a single-line data field — no field injection possible
const safeData = JSON.stringify({
type: event.type, // Enum — not user-controlled
status: event.status, // Enum — not user-controlled
message: event.message, // May be user-controlled — safe inside JSON string
progress: event.progress, // Number
});
// Always use JSON.stringify for the data field — never string interpolation
res.write(`data: ${safeData}\n\n`);
});
// Typed event names should come from a server-controlled enum, never user input
// If you use the event: field, only use constants:
// res.write(`event: progress\ndata: ${safeData}\n\n`);
// NOT: res.write(`event: ${event.type}\ndata: ...`);
// event.type must be validated against an allowlist before use in event: field
});
data: field via string interpolation; a user whose audit input (filename, repository name, error message) contains \n\n followed by a valid SSE field prefix can inject synthetic events into the stream; if the client dispatches on event: type, the attacker-controlled event type is executed; the attack is analogous to HTTP response splitting. Fix: always use JSON.stringify() to serialize the entire event payload before writing to the data: field — JSON encoding converts all newlines to \n escape sequences; never use string template literals to construct SSE field values from user-controlled content. Detection: SkillAudit flags res.write() calls where the string argument uses template literals with variables that may contain user-controlled data.SSECLIENT-003 — SSE event ID leaks enumerable resource IDs
The SSE id: field serves two purposes: it identifies the event for client-side deduplication, and it is sent as the Last-Event-ID header on reconnect so the server can resume from the last received event. When developers use the audit job ID or database row ID as the SSE event ID, they inadvertently expose the sequential or enumerable nature of these IDs. A client that receives id: 1042 learns that job ID 1042 exists and that job IDs are sequential integers starting from 1. The client can then enumerate other job IDs (1043, 1044, etc.) and use the Last-Event-ID header to request event streams for jobs it does not own — and if SSECLIENT-001 is also present (no authentication), to read them.
// VULNERABLE: sequential job ID used as SSE event ID
app.get('/api/events/:jobId', authMiddleware, ownershipCheckMiddleware, (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.flushHeaders();
let eventIndex = 0;
eventEmitter.on(`job:${req.params.jobId}`, (event) => {
eventIndex++;
// VULNERABLE 1: using sequential eventIndex as id — reveals event count
res.write(`id: ${eventIndex}\n`);
// VULNERABLE 2: including job's database ID in event data
res.write(`data: ${JSON.stringify({ ...event, jobDbId: event.id })}\n\n`);
// jobDbId reveals sequential database IDs — attackers use these to enumerate other jobs
});
});
// FIXED: random UUID for event ID; opaque job token in data, not sequential DB ID
const { randomUUID } = require('crypto');
app.get('/api/events/:jobId', authMiddleware, ownershipCheckMiddleware, (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.flushHeaders();
eventEmitter.on(`job:${req.params.jobId}`, (event) => {
// FIXED: random UUID for event ID — no information about sequential structure
res.write(`id: ${randomUUID()}\n`);
res.write(`retry: 5000\n`);
// Expose only the opaque job token (UUID) to the client, not the sequential DB ID
res.write(`data: ${JSON.stringify({
type: event.type,
status: event.status,
message: event.message,
progress: event.progress,
jobToken: req.params.jobId, // jobId parameter is a UUID (see below)
// Never include: event.id (database row ID), event.userId, sequential counters
})}\n\n`);
});
});
// Ensuring job IDs are UUIDs, not sequential integers:
// When creating a job, use UUID as the primary identifier exposed to clients:
const createJob = async (userId, repoUrl) => {
const jobToken = randomUUID(); // This is what the client sees in the URL and SSE stream
await db.jobs.create({
id: db.nextId(), // Internal sequential ID — never exposed
token: jobToken, // This is the "jobId" in /api/events/:jobId
userId,
repoUrl,
});
return jobToken;
};
id: field value; the client observes these values and can infer the total count of audit jobs, estimate other users' job IDs, and use Last-Event-ID on reconnect to request streams for other jobs; combined with an unauthenticated SSE endpoint (SSECLIENT-001), this enables full enumeration of all audit jobs. Fix: use crypto.randomUUID() for all SSE event IDs; use UUID tokens (not sequential integer IDs) as the job identifier in both the URL path and event data; never include database row IDs in SSE event payloads. Detection: SkillAudit flags SSE event ID fields that increment numerically or correlate with database entity IDs.SSECLIENT-004 — Missing retry field causes thundering herd
When an SSE connection drops — due to a server restart, network interruption, or load balancer timeout — the browser's EventSource implementation automatically reconnects. The reconnect delay is controlled by the retry: field in the SSE stream. If the server never sends a retry: field, browsers use their default reconnect interval (typically 3 seconds in Chrome, 1 second in Firefox). In a production system under load — particularly during a rolling deployment or an error that affects many connections simultaneously — all disconnected clients reconnect in a 1–3 second window. This thundering herd can overwhelm the server with simultaneous connection and authentication requests at exactly the moment it is restarting or recovering. The retry: field with a backoff value is the standard mitigation — it spreads reconnections over time and allows the server to recover before it is re-inundated.
// VULNERABLE: SSE stream never sends retry: field
// All clients reconnect at browser default interval (1-3 seconds)
// 500 concurrent audit streams → server restart → 500 simultaneous reconnects in 1-3s
app.get('/api/events/:jobId', authMiddleware, ownershipCheckMiddleware, (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.flushHeaders();
// No retry: field sent — browser will use its default (1s Firefox, 3s Chrome)
// On rolling deployment: all 500 clients reconnect within 3 seconds of connection drop
// Authentication middleware runs 500 times → database session lookups → thundering herd
eventEmitter.on(`job:${req.params.jobId}`, (event) => {
res.write(`data: ${JSON.stringify(event)}\n\n`);
// Still no retry: field in event data
});
});
// FIXED: retry: field with jitter spreads reconnections over time
app.get('/api/events/:jobId', authMiddleware, ownershipCheckMiddleware, (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('X-Accel-Buffering', 'no'); // Disable Nginx buffering
res.flushHeaders();
// FIXED: send retry: field immediately on connection
// 5000ms base delay — spreads reconnects over 5 seconds
// This is the minimum; consider 10000-30000ms for large client populations
res.write(`retry: 5000\n\n`);
// Send heartbeat every 30 seconds to prevent proxy/load-balancer connection timeouts
// Also serves as a mechanism to update the retry interval dynamically
const heartbeatInterval = setInterval(() => {
if (res.writableEnded) {
clearInterval(heartbeatInterval);
return;
}
// Update retry interval — increase under load
const retryMs = getAdaptiveRetryMs(); // Returns 5000-30000 based on server load
res.write(`: heartbeat\nretry: ${retryMs}\n\n`);
// ': heartbeat' is a comment line (ignored by EventSource) — just keeps connection alive
}, 30000);
eventEmitter.on(`job:${req.params.jobId}`, (event) => {
if (res.writableEnded) return;
res.write(`id: ${randomUUID()}\n`);
res.write(`retry: 5000\n`); // Remind client of retry interval with each event
res.write(`data: ${JSON.stringify(event)}\n\n`);
});
req.on('close', () => {
clearInterval(heartbeatInterval);
eventEmitter.off(`job:${req.params.jobId}`, handler);
});
});
// getAdaptiveRetryMs() — increase retry delay when server is under load
function getAdaptiveRetryMs() {
const load = os.loadavg()[0]; // 1-minute load average
const cpuCount = os.cpus().length;
const loadRatio = load / cpuCount;
if (loadRatio > 0.8) return 30000; // High load: 30s reconnect
if (loadRatio > 0.5) return 15000; // Medium load: 15s reconnect
return 5000; // Normal: 5s reconnect
}
retry: field; without a server-specified reconnect delay, browsers reconnect at their default interval (1 second in Firefox, 3 seconds in Chrome); in a system with many concurrent SSE connections, a server restart or network event causes all clients to reconnect simultaneously — a thundering herd that can overwhelm authentication middleware and database connection pools at the moment the server is most vulnerable. Fix: send retry: 5000 at connection establishment and with each event; send a heartbeat comment (: heartbeat) every 30 seconds to prevent proxy timeouts; implement adaptive retry delay that increases with server load. Detection: SkillAudit flags SSE handlers that use text/event-stream content type but never write a retry: field to the response.SkillAudit detection summary — SA-SKL-SSECLIENT
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| SSECLIENT-001 | HIGH | Routes with Content-Type: text/event-stream that do not invoke authentication middleware before the first res.write() | Include SSE route under /api/ prefix with auth middleware; add ownership check on job ID |
| SSECLIENT-002 | HIGH | res.write() calls where the SSE data field is constructed via template literals with non-enum variables | JSON.stringify() all event payloads; never string-interpolate user content into SSE fields |
| SSECLIENT-003 | MEDIUM | SSE id: fields that increment numerically or contain database row IDs | crypto.randomUUID() for event IDs; UUID tokens not sequential integers for job IDs |
| SSECLIENT-004 | MEDIUM | SSE handlers that set text/event-stream content type but never write a retry: field | retry: 5000 at connection start and with each event; heartbeat comment every 30s; adaptive delay under load |
Related patterns: For WebSocket security patterns including origin validation and authentication, see SA-SKL-WEBSOCKET. For the CORS configuration needed to allow cross-origin SSE connections, see SA-SKL-CORS3. For log injection via newline sequences in a broader context, see SA-SKL-LOGINJECT.