Files
sofarr/SECURITY.md
Gronod bdbbcabfbc
All checks were successful
Build and Push Docker Image / build (push) Successful in 1m2s
CI / Security audit (push) Successful in 3m29s
feat(security): production hardening for external deployment
Container (Dockerfile):
- Multi-stage build (deps + runtime) for minimal attack surface
- Upgrade base image from node:18-alpine to node:22-alpine
- Run as non-root 'node' user (UID 1000); source files owned by root
- /app/data directory owned by node for SQLite + logs
- Docker HEALTHCHECK: wget /health every 30s

docker-compose.yaml:
- Port bound to 127.0.0.1 only (expose via reverse proxy)
- read_only: true filesystem; /tmp tmpfs for Node.js
- no-new-privileges:true, cap_drop: ALL
- Named volume sofarr-data for persistent data
- TRUST_PROXY, COOKIE_SECRET, NODE_ENV added

Helmet v7 + CSP nonce:
- Upgrade helmet@4 → helmet@7, express-rate-limit@6 → @7
- CSP with per-request nonce injected into index.html script/link tags
  (replaces blanket unsafe-inline; nonce changes every request)
- HSTS: max-age=1yr, includeSubDomains, preload
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: camera/mic/geolocation/payment/usb all off
- index.html served dynamically with nonce injection; static assets
  served normally via express.static({index:false})

Trust proxy:
- TRUST_PROXY env var configures app.set('trust proxy') so rate
  limiting and secure cookies work correctly behind Nginx/Caddy

Session & auth:
- Token store migrated from in-memory Map to SQLite via better-sqlite3
  (server/utils/tokenStore.js): survives restarts, WAL mode, 31-day TTL
- CSRF double-submit cookie pattern (server/middleware/verifyCsrf.js):
  POST/PUT/PATCH/DELETE on /api/* require X-CSRF-Token header matching
  the csrf_token cookie; timing-safe comparison
- CSRF token issued on login + GET /api/auth/csrf; cleared on logout
- Login input validation: username/password length + type checked before
  hitting Emby
- skipSuccessfulRequests:true on login rate limiter (only count failures)
- express.json({ limit: '64kb' }) to reject oversized payloads

Rate limiting:
- General API limiter: 300 req/15min per IP on all /api/* routes
- Login limiter unchanged (10 failures/15min) but now only counts fails

Logging:
- Log file moved from /app/server.log to DATA_DIR/server.log (writable
  by non-root node user in container)
- Size-based rotation: rotate at 10 MB, keep 3 files (server.log.1-3)
- DATA_DIR defaults to ./data locally, /app/data in container

Error handling:
- Global Express error handler: catches unhandled errors, logs message,
  returns generic 500 (no stack traces to clients)

Health/readiness:
- GET /health: returns {status:'ok', uptime:N} — used by HEALTHCHECK
- GET /ready: returns 503 if EMBY_URL not configured

Error sanitization (sanitizeError.js):
- Added patterns for password= params, bearer tokens, Basic auth in URLs

Supply chain:
- Remove unused cors dependency
- add better-sqlite3@^9
- CI: upgrade to Node 22, raise audit level to --audit-level=high
- .gitignore: add data/, *.db, *.db-wal, *.db-shm

Docs:
- SECURITY.md: threat model, hardening checklist, proxy examples,
  header table, rate limit table, Docker secrets guidance
- .env.example + .env.sample: TRUST_PROXY, DATA_DIR documented
2026-05-17 06:47:25 +01:00

149 lines
4.9 KiB
Markdown

# Security Policy & Hardening Guide
## Supported Versions
| Version | Supported |
|---------|-----------|
| 0.2.x | ✅ Yes |
| 0.1.x | ❌ No |
## Reporting a Vulnerability
Please **do not** open a public issue for security vulnerabilities.
Email: gordon@i3omb.com — expect acknowledgement within 48 hours.
---
## Threat Model
sofarr is a personal dashboard intended for a small trusted group (household/team).
It proxies requests to *arr stack services using stored API keys and authenticates
users via Emby. The primary threat surface when exposed to the public internet:
| Threat | Mitigations |
|--------|-------------|
| Credential brute-force | Rate limiting (10 fails/15 min per IP), account lockout window |
| Session hijacking | HMAC-signed cookies, `httpOnly`, `secure`, `sameSite=strict`, short TTL |
| CSRF | Double-submit cookie pattern (`X-CSRF-Token` header required on all mutations) |
| API key leakage via errors | `sanitizeError()` redacts keys/tokens from all error responses and logs |
| Token theft after logout | Server-side token store; Emby token revoked on logout |
| XSS → token theft | `httpOnly` cookies; CSP with per-request nonce blocks inline injection |
| Clickjacking | `X-Frame-Options: DENY` + CSP `frame-ancestors 'none'` |
| Info disclosure via headers | Helmet v7 removes `X-Powered-By`, sets `noSniff`, `xssFilter`, etc. |
| Privilege escalation (container) | Non-root user (UID 1000), `no-new-privileges`, all caps dropped |
| Unbounded log growth | Size-based rotation: 10 MB cap, 3 rotated files kept |
| Dependency vulnerabilities | `npm audit --audit-level=high` in CI on every push |
---
## Production Deployment Checklist
### Required
- [ ] `COOKIE_SECRET` set to a random 32-byte hex string (`openssl rand -hex 32`)
- [ ] `NODE_ENV=production`
- [ ] `TRUST_PROXY=1` set if behind a reverse proxy
- [ ] sofarr bound to `127.0.0.1` only (not `0.0.0.0`) — expose via proxy
- [ ] HTTPS enforced by the reverse proxy with a valid certificate
- [ ] Firewall rules: only 443/80 open externally; 3001 not directly exposed
### Recommended
- [ ] Reverse proxy: Nginx, Caddy, or Traefik with TLS termination
- [ ] Set `Strict-Transport-Security` at proxy level (sofarr also sends HSTS)
- [ ] `DATA_DIR` on a named Docker volume (not bind-mounted to sensitive host path)
- [ ] Rotate `COOKIE_SECRET` periodically (causes all users to re-login)
- [ ] Enable Docker's `--read-only` flag (already in `docker-compose.yaml`)
- [ ] Monitor `/health` endpoint with an uptime checker
### Docker Secrets (alternative to env vars)
For production environments that support Docker secrets, you can mount secret
files and reference them:
```yaml
secrets:
cookie_secret:
file: ./secrets/cookie_secret.txt
emby_api_key:
file: ./secrets/emby_api_key.txt
services:
sofarr:
secrets:
- cookie_secret
- emby_api_key
environment:
- COOKIE_SECRET_FILE=/run/secrets/cookie_secret
- EMBY_API_KEY_FILE=/run/secrets/emby_api_key
```
> Note: File-based secret loading requires application code support.
> Currently sofarr reads secrets from environment variables only.
> Mounting secrets as env vars (via `environment:` in compose) is the
> current supported approach.
---
## Reverse Proxy Example (Caddy)
```caddy
sofarr.example.com {
reverse_proxy localhost:3001
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-Robots-Tag "noindex, nofollow"
}
}
```
## Reverse Proxy Example (Nginx)
```nginx
server {
listen 443 ssl;
server_name sofarr.example.com;
ssl_certificate /etc/letsencrypt/live/sofarr.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/sofarr.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
---
## Security Headers (emitted by sofarr)
| Header | Value |
|--------|-------|
| `Content-Security-Policy` | `default-src 'self'; script-src 'self' 'nonce-…'; style-src 'self' 'nonce-…'; img-src 'self' data: blob:; object-src 'none'; frame-ancestors 'none'` |
| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` (production only) |
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `DENY` |
| `Referrer-Policy` | `strict-origin-when-cross-origin` |
| `Permissions-Policy` | `camera=(), microphone=(), geolocation=(), payment=(), usb=()` |
---
## Rate Limits
| Endpoint | Limit |
|----------|-------|
| `POST /api/auth/login` | 10 failed attempts per 15 min per IP |
| All `/api/*` routes | 300 requests per 15 min per IP |
---
## Supply Chain
- All dependencies pinned to minor version ranges in `package.json`
- `npm audit --audit-level=high` runs in CI on every push and pull request
- `npm audit fix` should be run when vulnerabilities are reported