WebSocket Connection Violations
WebSocket Connection Violations
WebSocket connections require specific CSP configurations:
// Common Error: WebSocket blocked
// Console: Refused to connect to 'ws://localhost:8080/socket' because it violates
// the following Content Security Policy directive: "connect-src 'self'"
// SOLUTION 1: Add WebSocket URLs to connect-src
Content-Security-Policy:
default-src 'self';
connect-src 'self' ws://localhost:8080 wss://production.example.com;
// SOLUTION 2: Dynamic WebSocket CSP
class WebSocketCSPManager {
generateConnectSrc(environment) {
const base = ["'self'"];
switch (environment) {
case 'development':
base.push('ws://localhost:*', 'ws://127.0.0.1:*');
break;
case 'staging':
base.push('wss://staging-ws.example.com');
break;
case 'production':
base.push('wss://ws.example.com', 'wss://ws-backup.example.com');
break;
}
return base.join(' ');
}
// WebSocket wrapper with CSP compliance
createSecureWebSocket(url, protocols) {
// Validate WebSocket URL against CSP
if (!this.isAllowedWebSocketUrl(url)) {
throw new Error(`WebSocket URL ${url} violates CSP`);
}
const ws = new WebSocket(url, protocols);
// Add security event handling
ws.addEventListener('error', (event) => {
if (event.message && event.message.includes('Content Security Policy')) {
console.error('WebSocket blocked by CSP:', url);
this.handleCSPViolation(url);
}
});
return ws;
}
isAllowedWebSocketUrl(url) {
const allowedOrigins = [
'ws://localhost:8080',
'wss://ws.example.com'
];
return allowedOrigins.some(allowed => url.startsWith(allowed));
}
}