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
This commit is contained in:
83
server/utils/tokenStore.js
Normal file
83
server/utils/tokenStore.js
Normal file
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Persistent token store backed by SQLite (better-sqlite3).
|
||||
*
|
||||
* Survives process restarts — Emby tokens remain valid across deploys
|
||||
* and container restarts, so users do not need to re-login after an
|
||||
* update. Tokens are stored in DATA_DIR/tokens.db (default: /app/data
|
||||
* inside the container, or ./data locally).
|
||||
*
|
||||
* Schema: tokens(userId TEXT PK, accessToken TEXT, createdAt INTEGER)
|
||||
*
|
||||
* Expired rows (older than TOKEN_TTL_DAYS) are pruned on startup and
|
||||
* once per hour, preventing unbounded growth.
|
||||
*/
|
||||
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const TOKEN_TTL_DAYS = 31; // slightly longer than max cookie lifetime
|
||||
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '../../data');
|
||||
|
||||
// Ensure data directory exists (non-root writable in container)
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
const DB_PATH = path.join(DATA_DIR, 'tokens.db');
|
||||
const db = new Database(DB_PATH);
|
||||
|
||||
// WAL mode for better concurrent read performance
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
userId TEXT PRIMARY KEY,
|
||||
accessToken TEXT NOT NULL,
|
||||
createdAt INTEGER NOT NULL DEFAULT (strftime('%s','now'))
|
||||
)
|
||||
`);
|
||||
|
||||
const storeToken = db.prepare(
|
||||
`INSERT OR REPLACE INTO tokens (userId, accessToken, createdAt)
|
||||
VALUES (?, ?, strftime('%s','now'))`
|
||||
);
|
||||
|
||||
const getTokenStmt = db.prepare(
|
||||
`SELECT accessToken FROM tokens WHERE userId = ?`
|
||||
);
|
||||
|
||||
const clearTokenStmt = db.prepare(
|
||||
`DELETE FROM tokens WHERE userId = ?`
|
||||
);
|
||||
|
||||
const pruneStmt = db.prepare(
|
||||
`DELETE FROM tokens WHERE createdAt < strftime('%s','now') - ?`
|
||||
);
|
||||
|
||||
const TTL_SECONDS = TOKEN_TTL_DAYS * 24 * 60 * 60;
|
||||
|
||||
function prune() {
|
||||
const result = pruneStmt.run(TTL_SECONDS);
|
||||
if (result.changes > 0) {
|
||||
console.log(`[TokenStore] Pruned ${result.changes} expired token(s)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Prune on startup and every hour
|
||||
prune();
|
||||
setInterval(prune, 60 * 60 * 1000).unref();
|
||||
|
||||
module.exports = {
|
||||
storeToken(userId, accessToken) {
|
||||
storeToken.run(userId, accessToken);
|
||||
},
|
||||
getToken(userId) {
|
||||
const row = getTokenStmt.get(userId);
|
||||
return row ? { accessToken: row.accessToken } : null;
|
||||
},
|
||||
clearToken(userId) {
|
||||
clearTokenStmt.run(userId);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user