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:
@@ -6,6 +6,15 @@ LOG_LEVEL=info
|
||||
# Required in production. Generate with: openssl rand -hex 32
|
||||
COOKIE_SECRET=your_cookie_secret_here
|
||||
|
||||
# Set to 1 (or a specific IP/CIDR) when running behind a reverse proxy
|
||||
# (Nginx, Caddy, Traefik) so Express trusts X-Forwarded-For/Proto.
|
||||
# Leave unset if sofarr is exposed directly.
|
||||
# TRUST_PROXY=1
|
||||
|
||||
# Directory for persistent data (SQLite token store + logs)
|
||||
# Defaults to ./data relative to project root
|
||||
# DATA_DIR=/app/data
|
||||
|
||||
# Background polling interval in ms (default: 5000)
|
||||
# Set to 0 or "off" to disable and fetch on-demand instead
|
||||
# POLL_INTERVAL=5000
|
||||
|
||||
15
.env.sample
15
.env.sample
@@ -19,6 +19,21 @@ LOG_LEVEL=info
|
||||
# Generate with: openssl rand -hex 32
|
||||
COOKIE_SECRET=your-cookie-secret-here
|
||||
|
||||
# =============================================================================
|
||||
# REVERSE PROXY & DEPLOYMENT
|
||||
# =============================================================================
|
||||
|
||||
# Set to 1 when running behind a reverse proxy (Nginx, Caddy, Traefik).
|
||||
# This makes Express trust X-Forwarded-For and X-Forwarded-Proto so that
|
||||
# req.ip reflects the real client IP and cookies are marked secure correctly.
|
||||
# Leave unset if sofarr is exposed directly to the internet.
|
||||
# TRUST_PROXY=1
|
||||
|
||||
# Directory for persistent data (SQLite token store, server logs).
|
||||
# Must be writable by the process user (UID 1000 in the container).
|
||||
# Defaults to ./data relative to the project root.
|
||||
# DATA_DIR=/app/data
|
||||
|
||||
# Background polling interval in milliseconds (default: 5000)
|
||||
# sofarr polls all services in the background and caches results so
|
||||
# dashboard requests are near-instant.
|
||||
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
audit:
|
||||
name: npm audit
|
||||
name: Security audit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -16,11 +16,15 @@ jobs:
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run security audit
|
||||
run: npm audit --audit-level=moderate
|
||||
- name: Run security audit (fail on high+)
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
- name: Check for critical vulnerabilities
|
||||
run: npm audit --audit-level=critical --json | jq -e '.metadata.vulnerabilities.critical == 0' || (echo "Critical vulnerabilities found!" && exit 1)
|
||||
continue-on-error: false
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -5,3 +5,7 @@ build/
|
||||
.DS_Store
|
||||
*.log
|
||||
**/*.log
|
||||
data/
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
43
Dockerfile
43
Dockerfile
@@ -1,4 +1,18 @@
|
||||
FROM node:18-alpine
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage 1 — deps: install production dependencies only
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-alpine AS deps
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy manifests and install production deps only (no devDependencies)
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --ignore-scripts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage 2 — runtime image (minimal attack surface)
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-alpine AS runtime
|
||||
|
||||
LABEL org.opencontainers.image.title="sofarr"
|
||||
LABEL org.opencontainers.image.description="Personal media download dashboard for *arr services"
|
||||
@@ -9,18 +23,31 @@ LABEL org.opencontainers.image.vendor="Gordon Bolton"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
LABEL custom.hardware.requirement="None - runs on any Docker-supported platform including ARM and x86_64"
|
||||
|
||||
# Use the built-in non-root 'node' user (UID 1000) from the official image
|
||||
# The /app directory is owned by root; data directory is owned by node
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files and install dependencies
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
# Copy production deps from deps stage
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
|
||||
# Copy application source
|
||||
COPY server/ ./server/
|
||||
COPY public/ ./public/
|
||||
# Copy application source owned by root (read-only at runtime)
|
||||
COPY --chown=root:root server/ ./server/
|
||||
COPY --chown=root:root public/ ./public/
|
||||
COPY --chown=root:root package.json ./
|
||||
|
||||
# Persistent data directory owned by node user (SQLite token store, logs)
|
||||
RUN mkdir -p /app/data && chown node:node /app/data
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV DATA_DIR=/app/data
|
||||
|
||||
# Drop to non-root user for all subsequent operations
|
||||
USER node
|
||||
|
||||
EXPOSE 3001
|
||||
|
||||
ENV NODE_ENV=production
|
||||
# HEALTHCHECK — Docker will restart the container if this fails 3 times
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD wget -qO- http://localhost:3001/health || exit 1
|
||||
|
||||
CMD ["node", "server/index.js"]
|
||||
|
||||
148
SECURITY.md
Normal file
148
SECURITY.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# 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
|
||||
@@ -1,17 +1,45 @@
|
||||
version: "3"
|
||||
services:
|
||||
sofarr:
|
||||
image: docker.i3omb.com/sofarr:latest
|
||||
container_name: sofarr
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3001:3001"
|
||||
- "127.0.0.1:3001:3001" # bind to loopback only — expose via reverse proxy
|
||||
environment:
|
||||
- PORT=3001
|
||||
- NODE_ENV=production
|
||||
- LOG_LEVEL=info
|
||||
# Set to 1 when running behind a reverse proxy (Nginx, Caddy, Traefik)
|
||||
# so Express trusts X-Forwarded-For and X-Forwarded-Proto headers.
|
||||
- TRUST_PROXY=1
|
||||
# --- Replace placeholders with real values or use Docker secrets ---
|
||||
- COOKIE_SECRET=change-me-generate-with-openssl-rand-hex-32
|
||||
- EMBY_URL=https://emby.example.com
|
||||
- EMBY_API_KEY=your-emby-api-key
|
||||
- SONARR_INSTANCES=[{"name":"main","url":"https://sonarr.example.com","apiKey":"your-sonarr-api-key"}]
|
||||
- RADARR_INSTANCES=[{"name":"main","url":"https://radarr.example.com","apiKey":"your-radarr-api-key"}]
|
||||
- SABNZBD_INSTANCES=[{"name":"main","url":"https://sabnzbd.example.com","apiKey":"your-sabnzbd-api-key"}]
|
||||
- QBITTORRENT_INSTANCES=[{"name":"main","url":"https://qbittorrent.example.com","username":"admin","password":"your-password"}]
|
||||
- LOG_LEVEL=info
|
||||
volumes:
|
||||
# Persistent volume for SQLite token store and log file
|
||||
- sofarr-data:/app/data
|
||||
# Run as the built-in non-root 'node' user (UID/GID 1000)
|
||||
user: "1000:1000"
|
||||
# Read-only root filesystem; only the data volume is writable
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp # Node.js needs a writable /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true # prevent privilege escalation via setuid binaries
|
||||
cap_drop:
|
||||
- ALL # drop all Linux capabilities
|
||||
cap_add: [] # add back none — Node.js needs no special caps
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:3001/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
volumes:
|
||||
sofarr-data:
|
||||
|
||||
717
package-lock.json
generated
717
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
@@ -7,17 +7,18 @@
|
||||
"dev": "nodemon server/index.js",
|
||||
"start": "node server/index.js",
|
||||
"install:all": "npm install",
|
||||
"audit": "npm audit --audit-level=moderate",
|
||||
"audit:fix": "npm audit fix"
|
||||
"audit": "npm audit --audit-level=high",
|
||||
"audit:fix": "npm audit fix",
|
||||
"audit:critical": "npm audit --audit-level=critical"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.6.0",
|
||||
"better-sqlite3": "^9.0.0",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^6.7.0",
|
||||
"helmet": "^4.6.0"
|
||||
"express-rate-limit": "^7.0.0",
|
||||
"helmet": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^7.6.0",
|
||||
|
||||
@@ -4,6 +4,7 @@ let refreshInterval = null;
|
||||
let currentRefreshRate = 5000; // default 5 seconds
|
||||
let isAdmin = false;
|
||||
let showAll = false;
|
||||
let csrfToken = null; // double-submit CSRF token, sent as X-CSRF-Token on mutating requests
|
||||
const SPLASH_MIN_MS = 1200; // minimum splash display time
|
||||
|
||||
// Apply saved theme immediately (before DOMContentLoaded to avoid flash)
|
||||
@@ -118,9 +119,15 @@ function dismissSplash(startTime) {
|
||||
async function checkAuthentication() {
|
||||
const splashStart = Date.now();
|
||||
try {
|
||||
const response = await fetch('/api/auth/me');
|
||||
const data = await response.json();
|
||||
|
||||
// Fetch both auth state and a fresh CSRF token in parallel
|
||||
const [meRes, csrfRes] = await Promise.all([
|
||||
fetch('/api/auth/me'),
|
||||
fetch('/api/auth/csrf')
|
||||
]);
|
||||
const data = await meRes.json();
|
||||
const csrfData = await csrfRes.json();
|
||||
if (csrfData.csrfToken) csrfToken = csrfData.csrfToken;
|
||||
|
||||
if (data.authenticated) {
|
||||
currentUser = data.user;
|
||||
isAdmin = !!data.user.isAdmin;
|
||||
@@ -160,6 +167,8 @@ async function handleLogin(e) {
|
||||
if (data.success) {
|
||||
currentUser = data.user;
|
||||
isAdmin = !!data.user.isAdmin;
|
||||
// Store CSRF token returned by login for use in subsequent requests
|
||||
if (data.csrfToken) csrfToken = data.csrfToken;
|
||||
// Fade out login, then show splash while loading data.
|
||||
// requestAnimationFrame ensures the browser paints the splash at
|
||||
// opacity:1 before dismissSplash adds fade-out, so the CSS
|
||||
@@ -185,9 +194,11 @@ async function handleLogout() {
|
||||
try {
|
||||
stopAutoRefresh();
|
||||
await fetch('/api/auth/logout', {
|
||||
method: 'POST'
|
||||
method: 'POST',
|
||||
headers: csrfToken ? { 'X-CSRF-Token': csrfToken } : {}
|
||||
});
|
||||
currentUser = null;
|
||||
csrfToken = null;
|
||||
downloads = [];
|
||||
showLogin();
|
||||
} catch (err) {
|
||||
|
||||
197
server/index.js
197
server/index.js
@@ -2,6 +2,8 @@ const express = require('express');
|
||||
const path = require('path');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const helmet = require('helmet');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
require('dotenv').config();
|
||||
|
||||
@@ -10,7 +12,29 @@ require('dotenv').config();
|
||||
const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
|
||||
const currentLevel = LOG_LEVELS[(process.env.LOG_LEVEL || 'info').toLowerCase()] || 1;
|
||||
|
||||
const logFile = fs.createWriteStream(path.join(__dirname, '../server.log'), { flags: 'a' });
|
||||
// Log file lives in DATA_DIR so the non-root container user can write to it
|
||||
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '../data');
|
||||
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
|
||||
const LOG_PATH = path.join(DATA_DIR, 'server.log');
|
||||
const LOG_MAX_BYTES = 10 * 1024 * 1024; // 10 MB per file
|
||||
const LOG_KEEP = 3; // keep 3 rotated files
|
||||
|
||||
function rotateLogIfNeeded() {
|
||||
try {
|
||||
const stat = fs.statSync(LOG_PATH);
|
||||
if (stat.size < LOG_MAX_BYTES) return;
|
||||
for (let i = LOG_KEEP - 1; i >= 1; i--) {
|
||||
const src = `${LOG_PATH}.${i}`;
|
||||
const dst = `${LOG_PATH}.${i + 1}`;
|
||||
if (fs.existsSync(src)) fs.renameSync(src, dst);
|
||||
}
|
||||
fs.renameSync(LOG_PATH, `${LOG_PATH}.1`);
|
||||
} catch { /* ignore rotation errors — don't crash the server */ }
|
||||
}
|
||||
|
||||
rotateLogIfNeeded();
|
||||
const logFile = fs.createWriteStream(LOG_PATH, { flags: 'a' });
|
||||
const originalConsoleLog = console.log;
|
||||
const originalConsoleError = console.error;
|
||||
const originalConsoleWarn = console.warn;
|
||||
@@ -54,35 +78,173 @@ const radarrRoutes = require('./routes/radarr');
|
||||
const embyRoutes = require('./routes/emby');
|
||||
const dashboardRoutes = require('./routes/dashboard');
|
||||
const authRoutes = require('./routes/auth');
|
||||
const verifyCsrf = require('./middleware/verifyCsrf');
|
||||
const { startPoller, POLL_INTERVAL, POLLING_ENABLED } = require('./utils/poller');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Startup environment validation
|
||||
// ---------------------------------------------------------------------------
|
||||
const cookieSecret = process.env.COOKIE_SECRET;
|
||||
if (!cookieSecret && process.env.NODE_ENV === 'production') {
|
||||
console.error('[Security] COOKIE_SECRET is not set in production — aborting.');
|
||||
process.exit(1);
|
||||
} else if (!cookieSecret) {
|
||||
console.warn('[Security] COOKIE_SECRET not set — unsigned cookies (dev only)');
|
||||
}
|
||||
if (!process.env.EMBY_URL && process.env.NODE_ENV === 'production') {
|
||||
console.error('[Config] EMBY_URL is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: false // SPA uses inline scripts; CSP requires a nonce/hash strategy
|
||||
}));
|
||||
|
||||
const cookieSecret = process.env.COOKIE_SECRET;
|
||||
if (!cookieSecret && process.env.NODE_ENV === 'production') {
|
||||
console.error('[Security] COOKIE_SECRET is not set in production — cookies are unsigned and can be tampered with!');
|
||||
process.exit(1);
|
||||
} else if (!cookieSecret) {
|
||||
console.warn('[Security] COOKIE_SECRET is not set — using unsigned cookies (acceptable for development only)');
|
||||
// ---------------------------------------------------------------------------
|
||||
// Trust proxy — required when behind Nginx/Caddy/Traefik so that
|
||||
// req.ip reflects the real client IP (not 127.0.0.1) and
|
||||
// req.secure is true when the upstream TLS is terminated by the proxy.
|
||||
// Set TRUST_PROXY=1 (or a specific IP/CIDR) via env.
|
||||
// ---------------------------------------------------------------------------
|
||||
if (process.env.TRUST_PROXY) {
|
||||
const trustValue = /^\d+$/.test(process.env.TRUST_PROXY)
|
||||
? parseInt(process.env.TRUST_PROXY, 10)
|
||||
: process.env.TRUST_PROXY;
|
||||
app.set('trust proxy', trustValue);
|
||||
}
|
||||
app.use(cookieParser(cookieSecret || undefined));
|
||||
app.use(express.json());
|
||||
app.use(express.static(path.join(__dirname, '../public')));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helmet v7 — security response headers
|
||||
// CSP uses a per-request nonce injected into index.html so inline scripts
|
||||
// and styles are allowed only with a valid nonce, not blanket unsafe-inline.
|
||||
// ---------------------------------------------------------------------------
|
||||
app.use((req, res, next) => {
|
||||
// Generate a fresh nonce for every request
|
||||
res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
|
||||
next();
|
||||
});
|
||||
|
||||
app.use((req, res, next) => {
|
||||
helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
|
||||
styleSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
|
||||
imgSrc: ["'self'", 'data:', 'blob:'],
|
||||
fontSrc: ["'self'", 'data:'],
|
||||
connectSrc: ["'self'"],
|
||||
objectSrc: ["'none'"],
|
||||
baseUri: ["'self'"],
|
||||
frameAncestors: ["'none'"],
|
||||
formAction: ["'self'"],
|
||||
upgradeInsecureRequests: process.env.NODE_ENV === 'production' ? [] : null
|
||||
}
|
||||
},
|
||||
hsts: {
|
||||
maxAge: 31536000, // 1 year
|
||||
includeSubDomains: true,
|
||||
preload: true
|
||||
},
|
||||
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
|
||||
crossOriginEmbedderPolicy: false // not needed for this SPA
|
||||
})(req, res, next);
|
||||
});
|
||||
|
||||
// Permissions-Policy — disable powerful browser features not needed by the app
|
||||
app.use((req, res, next) => {
|
||||
res.setHeader(
|
||||
'Permissions-Policy',
|
||||
'camera=(), microphone=(), geolocation=(), payment=(), usb=()'
|
||||
);
|
||||
next();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// General API rate limiter — applies to all /api/* routes
|
||||
// More specific limiters (e.g. login) apply on top of this.
|
||||
// ---------------------------------------------------------------------------
|
||||
const apiLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 300, // 300 requests per IP per window (generous for polling)
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many requests, please try again later' }
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Body parsing & cookies
|
||||
// ---------------------------------------------------------------------------
|
||||
app.use(cookieParser(cookieSecret || undefined));
|
||||
app.use(express.json({ limit: '64kb' })); // prevent oversized JSON payloads
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Health / readiness endpoints (no auth, no rate-limit)
|
||||
// Used by Docker HEALTHCHECK and orchestrators.
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', uptime: process.uptime() });
|
||||
});
|
||||
|
||||
app.get('/ready', (req, res) => {
|
||||
// Confirm critical config is present
|
||||
const ready = !!(process.env.EMBY_URL);
|
||||
if (ready) {
|
||||
res.json({ status: 'ready' });
|
||||
} else {
|
||||
res.status(503).json({ status: 'not ready', reason: 'EMBY_URL not configured' });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Static files — served before API routes
|
||||
// index.html is served manually so we can inject the CSP nonce
|
||||
// ---------------------------------------------------------------------------
|
||||
const PUBLIC_DIR = path.join(__dirname, '../public');
|
||||
const INDEX_HTML = path.join(PUBLIC_DIR, 'index.html');
|
||||
|
||||
// Serve all static assets (js, css, images, icons) except index.html
|
||||
app.use(express.static(PUBLIC_DIR, { index: false }));
|
||||
|
||||
// Serve index.html with nonce injected into the <script> and <link> tags
|
||||
function serveIndex(req, res) {
|
||||
fs.readFile(INDEX_HTML, 'utf8', (err, html) => {
|
||||
if (err) return res.status(500).send('Internal Server Error');
|
||||
const nonce = res.locals.cspNonce;
|
||||
// Inject nonce into <script> and <link rel="stylesheet"> tags
|
||||
const patched = html
|
||||
.replace(/<script([^>]*)>/gi, `<script nonce="${nonce}"$1>`)
|
||||
.replace(/<link([^>]*rel=["']stylesheet["'][^>]*)>/gi, `<link nonce="${nonce}"$1>`);
|
||||
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
res.send(patched);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API routes (rate-limited; auth routes exempt CSRF for login/csrf endpoints)
|
||||
// CSRF protection applies to all state-changing /api/* requests except
|
||||
// /api/auth/login (pre-auth) and /api/auth/csrf (issues the token).
|
||||
// ---------------------------------------------------------------------------
|
||||
app.use('/api', apiLimiter);
|
||||
app.use('/api/auth', authRoutes);
|
||||
|
||||
// All routes below this point require CSRF validation on mutating methods
|
||||
app.use('/api', verifyCsrf);
|
||||
app.use('/api/sabnzbd', sabnzbdRoutes);
|
||||
app.use('/api/sonarr', sonarrRoutes);
|
||||
app.use('/api/radarr', radarrRoutes);
|
||||
app.use('/api/emby', embyRoutes);
|
||||
app.use('/api/dashboard', dashboardRoutes);
|
||||
app.use('/api/auth', authRoutes);
|
||||
|
||||
app.get('/', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, '../public/index.html'));
|
||||
// SPA catch-all — serve index.html for any unmatched path
|
||||
app.get('*', serveIndex);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Global error handler — never leak stack traces to clients
|
||||
// ---------------------------------------------------------------------------
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('[Server] Unhandled error:', err.message);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
@@ -91,6 +253,7 @@ app.listen(PORT, () => {
|
||||
console.log(` Server running on port ${PORT}`);
|
||||
console.log(` Log level: ${process.env.LOG_LEVEL || 'info'}`);
|
||||
console.log(` Polling: ${POLLING_ENABLED ? POLL_INTERVAL + 'ms' : 'disabled (on-demand)'}`);
|
||||
console.log(` Trust proxy: ${process.env.TRUST_PROXY || 'disabled'}`);
|
||||
console.log(`=================================`);
|
||||
startPoller();
|
||||
});
|
||||
|
||||
42
server/middleware/verifyCsrf.js
Normal file
42
server/middleware/verifyCsrf.js
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* CSRF protection using the double-submit cookie pattern.
|
||||
*
|
||||
* On login the server issues a random `csrf_token` cookie (httpOnly:false
|
||||
* so JS can read it). The SPA must send the same value in the
|
||||
* `X-CSRF-Token` request header for every state-changing request (POST,
|
||||
* PUT, PATCH, DELETE).
|
||||
*
|
||||
* Because the `sameSite: strict` session cookie already provides strong
|
||||
* protection in modern browsers, this acts as defence-in-depth for
|
||||
* older browsers and any edge cases.
|
||||
*
|
||||
* Safe methods (GET, HEAD, OPTIONS) are exempted.
|
||||
*/
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
|
||||
function verifyCsrf(req, res, next) {
|
||||
if (SAFE_METHODS.has(req.method)) return next();
|
||||
|
||||
const cookieToken = req.cookies.csrf_token;
|
||||
const headerToken = req.headers['x-csrf-token'];
|
||||
|
||||
if (!cookieToken || !headerToken) {
|
||||
return res.status(403).json({ error: 'CSRF token missing' });
|
||||
}
|
||||
|
||||
// Constant-time comparison to prevent timing attacks
|
||||
if (cookieToken.length !== headerToken.length) {
|
||||
return res.status(403).json({ error: 'CSRF token invalid' });
|
||||
}
|
||||
|
||||
const a = Buffer.from(cookieToken);
|
||||
const b = Buffer.from(headerToken);
|
||||
if (!require('crypto').timingSafeEqual(a, b)) {
|
||||
return res.status(403).json({ error: 'CSRF token invalid' });
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = verifyCsrf;
|
||||
@@ -4,30 +4,19 @@ const crypto = require('crypto');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const router = express.Router();
|
||||
|
||||
// Persistent SQLite-backed token store — survives restarts
|
||||
const { storeToken, getToken, clearToken } = require('../utils/tokenStore');
|
||||
|
||||
const EMBY_URL = process.env.EMBY_URL;
|
||||
|
||||
// Server-side token store: userId -> { accessToken }
|
||||
// Keeps AccessToken off the client; required for logout revocation.
|
||||
const tokenStore = new Map();
|
||||
|
||||
function storeToken(userId, accessToken) {
|
||||
tokenStore.set(userId, { accessToken });
|
||||
}
|
||||
|
||||
function getToken(userId) {
|
||||
return tokenStore.get(userId) || null;
|
||||
}
|
||||
|
||||
function clearToken(userId) {
|
||||
tokenStore.delete(userId);
|
||||
}
|
||||
|
||||
|
||||
// Strict login limiter: 10 attempts per 15 min, then locked for the window
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: 10,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
skipSuccessfulRequests: true, // only count failures toward the limit
|
||||
message: { success: false, error: 'Too many login attempts, please try again later' }
|
||||
});
|
||||
|
||||
@@ -35,15 +24,23 @@ const loginLimiter = rateLimit({
|
||||
router.post('/login', loginLimiter, async (req, res) => {
|
||||
try {
|
||||
const { username, password, rememberMe } = req.body;
|
||||
|
||||
// Input validation — reject obviously invalid inputs before hitting Emby
|
||||
if (typeof username !== 'string' || username.trim().length === 0 || username.length > 128) {
|
||||
return res.status(400).json({ success: false, error: 'Invalid username' });
|
||||
}
|
||||
if (typeof password !== 'string' || password.length === 0 || password.length > 256) {
|
||||
return res.status(400).json({ success: false, error: 'Invalid password' });
|
||||
}
|
||||
|
||||
console.log(`[Auth] Attempting login for user: ${username}`);
|
||||
console.log(`[Auth] Attempting login for user: ${username.trim()}`);
|
||||
|
||||
// Authenticate with Emby using a stable DeviceId derived from the username.
|
||||
// Using a deterministic DeviceId causes Emby to reuse the existing session
|
||||
// for this device rather than creating a new one on each login.
|
||||
const stableDeviceId = 'sofarr-' + crypto.createHash('sha256').update(username.toLowerCase()).digest('hex').slice(0, 16);
|
||||
const stableDeviceId = 'sofarr-' + crypto.createHash('sha256').update(username.trim().toLowerCase()).digest('hex').slice(0, 16);
|
||||
const authResponse = await axios.post(`${EMBY_URL}/Users/authenticatebyname`, {
|
||||
Username: username,
|
||||
Username: username.trim(),
|
||||
Pw: password
|
||||
}, {
|
||||
headers: {
|
||||
@@ -70,22 +67,36 @@ router.post('/login', loginLimiter, async (req, res) => {
|
||||
// Set authentication cookie (signed when COOKIE_SECRET is set).
|
||||
// rememberMe=true → persistent cookie, expires in 30 days
|
||||
// rememberMe=false → session cookie, expires when browser closes
|
||||
// secure is always true — the app should sit behind HTTPS in production;
|
||||
// behind a reverse proxy set TRUST_PROXY=1 so req.secure works correctly.
|
||||
const cookiePayload = JSON.stringify({ id: user.Id, name: user.Name, isAdmin });
|
||||
const signed = !!process.env.COOKIE_SECRET;
|
||||
const cookieOptions = {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'strict',
|
||||
signed
|
||||
signed,
|
||||
path: '/'
|
||||
};
|
||||
if (rememberMe) {
|
||||
cookieOptions.maxAge = 30 * 24 * 60 * 60 * 1000; // 30 days
|
||||
}
|
||||
res.cookie('emby_user', cookiePayload, cookieOptions);
|
||||
|
||||
// Issue a CSRF token tied to this session so state-changing endpoints
|
||||
// can validate the double-submit cookie pattern
|
||||
const csrfToken = crypto.randomBytes(32).toString('hex');
|
||||
res.cookie('csrf_token', csrfToken, {
|
||||
httpOnly: false, // intentionally readable by JS for the double-submit pattern
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'strict',
|
||||
path: '/'
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
user: { id: user.Id, name: user.Name, isAdmin }
|
||||
user: { id: user.Id, name: user.Name, isAdmin },
|
||||
csrfToken
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`[Auth] Login failed:`, error.message);
|
||||
@@ -122,6 +133,19 @@ router.get('/me', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
// CSRF token refresh — lets the SPA get a new token without re-logging-in
|
||||
// (e.g. after a page reload where the JS variable was lost)
|
||||
router.get('/csrf', (req, res) => {
|
||||
const csrfToken = crypto.randomBytes(32).toString('hex');
|
||||
res.cookie('csrf_token', csrfToken, {
|
||||
httpOnly: false,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'strict',
|
||||
path: '/'
|
||||
});
|
||||
res.json({ csrfToken });
|
||||
});
|
||||
|
||||
// Logout
|
||||
router.post('/logout', async (req, res) => {
|
||||
const user = parseSessionCookie(req);
|
||||
@@ -143,7 +167,14 @@ router.post('/logout', async (req, res) => {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'strict',
|
||||
signed: !!process.env.COOKIE_SECRET
|
||||
signed: !!process.env.COOKIE_SECRET,
|
||||
path: '/'
|
||||
});
|
||||
res.clearCookie('csrf_token', {
|
||||
httpOnly: false,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'strict',
|
||||
path: '/'
|
||||
});
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
const API_KEY_PATTERN = /([?&]apikey=)[^&\s]*/gi;
|
||||
const TOKEN_PATTERN = /([?&]token=)[^&\s]*/gi;
|
||||
const HEADER_PATTERN = /x-(?:api-key|mediabrowser-token|emby-authorization):[^\s,]*/gi;
|
||||
// Query-param secrets (SABnzbd apikey, generic token/password params)
|
||||
const QUERY_SECRET_PATTERN = /([?&](?:apikey|token|password|api_key|key|secret)=)[^&\s#]*/gi;
|
||||
// HTTP auth header values (X-Api-Key, X-MediaBrowser-Token, Authorization, X-Emby-Authorization)
|
||||
const HEADER_PATTERN = /(?:x-api-key|x-mediabrowser-token|x-emby-authorization|authorization)\s*:\s*\S+/gi;
|
||||
// Bearer tokens
|
||||
const BEARER_PATTERN = /bearer\s+[A-Za-z0-9\-._~+/]+=*/gi;
|
||||
// Basic auth credentials in URLs (http://user:pass@host)
|
||||
const BASIC_AUTH_URL_PATTERN = /\/\/[^:@/\s]+:[^@/\s]+@/gi;
|
||||
|
||||
function sanitizeError(err) {
|
||||
let msg = err.message || String(err);
|
||||
// Redact API keys in URLs (SABnzbd passes apikey as query param)
|
||||
msg = msg.replace(API_KEY_PATTERN, '$1[REDACTED]');
|
||||
msg = msg.replace(TOKEN_PATTERN, '$1[REDACTED]');
|
||||
// Redact auth header values if they appear in the message
|
||||
msg = msg.replace(HEADER_PATTERN, (m) => m.split(':')[0] + ':[REDACTED]');
|
||||
let msg = (err && err.message) ? err.message : String(err);
|
||||
msg = msg.replace(QUERY_SECRET_PATTERN, '$1[REDACTED]');
|
||||
msg = msg.replace(HEADER_PATTERN, (m) => m.split(/[\s:]/)[0] + ':[REDACTED]');
|
||||
msg = msg.replace(BEARER_PATTERN, 'bearer [REDACTED]');
|
||||
msg = msg.replace(BASIC_AUTH_URL_PATTERN, '//[REDACTED]@');
|
||||
// Never leak stack traces to API responses
|
||||
return msg;
|
||||
}
|
||||
|
||||
|
||||
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