Implementing Security Measures
1. Using Secure WebSockets
| Requirement | Detail |
|---|---|
| TLS 1.2+ (prefer 1.3) | Modern ciphers only |
| HSTS | Inherited from origin |
| Cert pinning | Mobile apps |
| SNI | Required for multi-host |
2. Validating Origin Header
Example: Origin allowlist
const ALLOWED = new Set(["https://app.example.com","https://admin.example.com"]);
new WebSocketServer({
port: 8080,
verifyClient: ({ req }) => ALLOWED.has(req.headers.origin)
});
Warning: Non-browser clients can spoof Origin. Treat as defense-in-depth, not auth.
3. Using TLS Certificates
| Source | Detail |
|---|---|
| Let's Encrypt | Free, auto-renew (certbot) |
| Cloud LB | ACM / Cloud Load Balancer manages |
| Internal CA | mTLS for service-to-service |
4. Validating Input Data
| Validation | Layer |
|---|---|
| Schema (zod/ajv) | Structural |
| Length caps | Memory protection |
| Type narrowing | Prevent eval/proto pollution |
| Sanitization | Domain-specific (HTML, SQL, paths) |
5. Preventing XSS Attacks
Example: DOMPurify on render
import DOMPurify from "dompurify";
el.innerHTML = DOMPurify.sanitize(msg.htmlText);
| Practice | Detail |
|---|---|
Use textContent | Default for untrusted |
| Sanitize HTML | DOMPurify before innerHTML |
| CSP | Restrict script sources |
6. Implementing CSRF Protection
| Approach | Detail |
|---|---|
| SameSite cookie | Lax/Strict — primary defense |
| Origin check | Validate at upgrade |
| CSRF token | Required when using cookie auth |
| Token in WS ticket | Server-issued one-shot |
Warning: Browsers do NOT enforce same-origin policy on WebSocket — your server must validate Origin to prevent CSWSH.
7. Implementing IP Whitelisting
Example: CIDR check
import ipaddr from "ipaddr.js";
const allowed = ["10.0.0.0/8","192.168.1.0/24"].map(c => ipaddr.parseCIDR(c));
function allowedIp(ip) {
const addr = ipaddr.parse(ip);
return allowed.some(([net]) => addr.match([net, /* bits */]));
}
8. Encrypting Messages
| Layer | Use |
|---|---|
| TLS (wss) | In-transit (always) |
| E2E (libsodium) | Server cannot read payload |
| Field-level | Encrypt sensitive fields only |
9. Validating Message Size
| Layer | Limit Recommendation |
|---|---|
| Server WSS | 64 KB (chat), tune for use case |
| App schema | Per-field caps |
| Proxy | Match WSS limit |
10. Implementing Security Headers
| Header | Purpose |
|---|---|
Strict-Transport-Security | Force HTTPS/WSS |
Content-Security-Policy | Use connect-src wss://api |
X-Content-Type-Options: nosniff | HTTP page headers |
Referrer-Policy | Prevent leaking URLs (with tokens) |