This module provides security features to protect api-ape connections from common web vulnerabilities, including CSRF protection and duplicate request detection. Origin validation is enabled by default.
- Origin validation is critical — Changes to
origin.jsaffect all connection security; test thoroughly - Domain matching — Use
extractRootDomain.jsfor domain comparisons; don't implement custom logic - Subdomain support — Origin checks must work with subdomains (e.g.,
app.example.comvsexample.com) - No configuration required — Security features should work out-of-the-box with sensible defaults
- Fail secure — When in doubt, reject the connection; false positives are better than security holes
- Localhost exceptions — Development on localhost should work without origin issues
security/
├── extractRootDomain.js # Domain extraction for origin validation
├── origin.js # Origin verification (CSRF protection)
└── reply.js # Duplicate request protection
Origin validation to prevent Cross-Site Request Forgery (CSRF) attacks:
- Validates the
Originheader against theHostheader - Two modes:
root-domain(legacy, ports ignored, Node default) andexact(scheme-normalised host and port, Bun default), plusallowedOriginsandallowedHosts; seeresolveOriginPolicy - Reads headers from Express, Node and Fetch (
Headers.get) requests - Ensures WebSocket connections only come from the same origin
- Automatically rejects cross-origin requests
- Works with both Express.js and raw Node.js servers
- Returns
trueif valid,falseto reject connection
Extracts the root domain from a hostname for flexible origin matching:
- Handles subdomains (e.g.,
app.example.com→example.com) - Handles IP addresses and localhost
- Handles ports in host strings (strips them for comparison)
- Used by
origin.jsfor domain comparison
Duplicate request protection to prevent replay attacks:
- Tracks recently processed
queryIdvalues - Rejects duplicate requests within a configurable time window
- Prevents attackers from replaying captured WebSocket messages
- Automatically cleans up expired entries
- Refuses a
createdAtolder than 10 s, or more thanmaxClockSkewMs(default 5000 ms, 4.5.1) ahead of the server's clock