Implementing Security Measures

1. Using Secure WebSockets

RequirementDetail
TLS 1.2+ (prefer 1.3)Modern ciphers only
HSTSInherited from origin
Cert pinningMobile apps
SNIRequired 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

SourceDetail
Let's EncryptFree, auto-renew (certbot)
Cloud LBACM / Cloud Load Balancer manages
Internal CAmTLS for service-to-service

4. Validating Input Data

ValidationLayer
Schema (zod/ajv)Structural
Length capsMemory protection
Type narrowingPrevent eval/proto pollution
SanitizationDomain-specific (HTML, SQL, paths)

5. Preventing XSS Attacks

Example: DOMPurify on render

import DOMPurify from "dompurify";
el.innerHTML = DOMPurify.sanitize(msg.htmlText);
PracticeDetail
Use textContentDefault for untrusted
Sanitize HTMLDOMPurify before innerHTML
CSPRestrict script sources

6. Implementing CSRF Protection

ApproachDetail
SameSite cookieLax/Strict — primary defense
Origin checkValidate at upgrade
CSRF tokenRequired when using cookie auth
Token in WS ticketServer-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

LayerUse
TLS (wss)In-transit (always)
E2E (libsodium)Server cannot read payload
Field-levelEncrypt sensitive fields only

9. Validating Message Size

Example: Server limit

new WebSocketServer({ port: 8080, maxPayload: 64 * 1024 }); // 64 KB
LayerLimit Recommendation
Server WSS64 KB (chat), tune for use case
App schemaPer-field caps
ProxyMatch WSS limit

10. Implementing Security Headers

HeaderPurpose
Strict-Transport-SecurityForce HTTPS/WSS
Content-Security-PolicyUse connect-src wss://api
X-Content-Type-Options: nosniffHTTP page headers
Referrer-PolicyPrevent leaking URLs (with tokens)