Hardening: helmet/CSP, rate limits, secure session config, timeouts
This commit is contained in:
parent
48f8046a33
commit
b9590a2f63
9 changed files with 132 additions and 17 deletions
|
|
@ -14,6 +14,13 @@ MANAGEMENT_PORT=8080
|
|||
|
||||
# This app
|
||||
PORT=3000
|
||||
LISTEN_HOST=127.0.0.1
|
||||
# Behind nginx: 1 (one proxy hop). Direct local dev: 0.
|
||||
TRUST_PROXY=1
|
||||
# auto|true|false. Use true behind HTTPS reverse proxy.
|
||||
COOKIE_SECURE=auto
|
||||
# Session lifetime in hours.
|
||||
SESSION_MAX_AGE_HOURS=24
|
||||
# Web API devId/key - see planning.md open question 2 / M0.
|
||||
DEV_ID=your-web-api-key
|
||||
# Long random string for cookie signing.
|
||||
|
|
|
|||
29
README.md
29
README.md
|
|
@ -46,12 +46,31 @@ Open `http://localhost:3000` (or your configured `PORT`).
|
|||
| `MANAGEMENT_PORT` | Management API port | `8080` |
|
||||
| `PORT` | App listen port | `3000` |
|
||||
| `LISTEN_HOST` | App bind host | `127.0.0.1` |
|
||||
| `TRUST_PROXY` | Proxy hops in front of app | `1` |
|
||||
| `COOKIE_SECURE` | `auto`/`true`/`false` session cookie | `auto` |
|
||||
| `SESSION_MAX_AGE_HOURS` | Session lifetime | `24` |
|
||||
| `DEV_ID` | Optional Web API devId/key | unset |
|
||||
| `SESSION_SECRET` | Cookie signing secret | required |
|
||||
|
||||
## Notes
|
||||
## Public deployment (nginx)
|
||||
|
||||
- Group chat/invites require a working TOC connection.
|
||||
- User search needs Management API access; otherwise open IMs by screen name.
|
||||
- Sessions are in memory (restart logs users out).
|
||||
- Review security/hardening before exposing publicly.
|
||||
- Bind app to `127.0.0.1` and expose only through HTTPS nginx.
|
||||
- Set `TRUST_PROXY=1`, `COOKIE_SECURE=true`, strong `SESSION_SECRET`, and `0600` permissions on `.env`.
|
||||
- Nginx should redirect HTTP->HTTPS, set HSTS, forward `X-Forwarded-*`, and disable buffering for SSE:
|
||||
|
||||
```nginx
|
||||
location /api/events {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection '';
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 1h;
|
||||
}
|
||||
```
|
||||
|
||||
- App includes Helmet headers/CSP, JSON-only mutating API checks, Origin checks, and rate limits. Still review before public use.
|
||||
- Sessions are in-memory (single process only; restart logs users out). For heavier public use, move to a persistent session store.
|
||||
14
package-lock.json
generated
14
package-lock.json
generated
|
|
@ -10,7 +10,8 @@
|
|||
"dependencies": {
|
||||
"express": "^4.21.2",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"express-session": "^1.18.1"
|
||||
"express-session": "^1.18.1",
|
||||
"helmet": "^8.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"playwright": "^1.65.2"
|
||||
|
|
@ -411,6 +412,17 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/helmet": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz",
|
||||
"integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/EvanHahn"
|
||||
}
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@
|
|||
"dependencies": {
|
||||
"express": "^4.21.2",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"express-session": "^1.18.1"
|
||||
"express-session": "^1.18.1",
|
||||
"helmet": "^8.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"playwright": "^1.65.2"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,23 @@ function port(name, fallback) {
|
|||
return n;
|
||||
}
|
||||
|
||||
function int(name, fallback, { min = 0, max = Number.MAX_SAFE_INTEGER } = {}) {
|
||||
const raw = process.env[name] ?? String(fallback);
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < min || n > max) {
|
||||
throw new Error(`${name} must be an integer ${min}-${max}, got: ${raw}`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function bool(name, fallback) {
|
||||
const raw = process.env[name];
|
||||
if (raw == null || raw === '') return fallback;
|
||||
if (['1', 'true', 'yes', 'on'].includes(raw.toLowerCase())) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(raw.toLowerCase())) return false;
|
||||
throw new Error(`${name} must be boolean, got: ${raw}`);
|
||||
}
|
||||
|
||||
const host = (name, fallback) => process.env[name] || fallback;
|
||||
const required = (name) => {
|
||||
const value = process.env[name];
|
||||
|
|
@ -28,10 +45,20 @@ export const SESSION_SECRET = () => required('SESSION_SECRET');
|
|||
|
||||
// Bind address for this app. Default localhost; set 0.0.0.0 only behind nginx.
|
||||
export const LISTEN_HOST = host('LISTEN_HOST', '127.0.0.1');
|
||||
export const TRUST_PROXY = int('TRUST_PROXY', 1, { min: 0, max: 10 });
|
||||
export const COOKIE_SECURE = (() => {
|
||||
const raw = (process.env.COOKIE_SECURE ?? 'auto').toLowerCase();
|
||||
if (['auto', 'true', 'false'].includes(raw)) return raw;
|
||||
throw new Error(`COOKIE_SECURE must be auto|true|false, got: ${raw}`);
|
||||
})();
|
||||
export const SESSION_MAX_AGE_MS = int('SESSION_MAX_AGE_HOURS', 24, { min: 1, max: 24 * 30 }) * 60 * 60 * 1000;
|
||||
export const NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
export function logStartupConfig() {
|
||||
// Never log DEV_ID or SESSION_SECRET.
|
||||
console.log(`[config] Web API: ${WEBAPI_BASE}`);
|
||||
console.log(`[config] Management API: ${MANAGEMENT_BASE}`);
|
||||
console.log(`[config] App listen: http://${LISTEN_HOST}:${PORT}`);
|
||||
console.log(`[config] trust proxy: ${TRUST_PROXY}`);
|
||||
console.log(`[config] cookie secure: ${COOKIE_SECURE}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,11 +27,11 @@ function redactParams(params) {
|
|||
}
|
||||
|
||||
// Call a Web API endpoint and unwrap the { response: { statusCode, statusText, data } } envelope.
|
||||
async function call(path, params = {}, { base = WEBAPI_BASE, method = 'GET', formBody = null } = {}) {
|
||||
async function call(path, params = {}, { base = WEBAPI_BASE, method = 'GET', formBody = null, timeoutMs = 15000 } = {}) {
|
||||
const url = new URL(path, base);
|
||||
url.search = new URLSearchParams({ f: 'json', ...params }).toString();
|
||||
|
||||
const opts = { method };
|
||||
const opts = { method, signal: AbortSignal.timeout(timeoutMs) };
|
||||
if (formBody) {
|
||||
opts.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
|
||||
opts.body = new URLSearchParams(formBody).toString();
|
||||
|
|
@ -96,7 +96,7 @@ export async function fetchEvents(aimsid, seqNum, { timeout = 25000 } = {}) {
|
|||
aimsid,
|
||||
seqNum,
|
||||
timeout,
|
||||
});
|
||||
}, { timeoutMs: timeout + 10000 });
|
||||
}
|
||||
|
||||
export async function endSession(aimsid) {
|
||||
|
|
|
|||
|
|
@ -41,12 +41,15 @@ export async function logoutSession(req) {
|
|||
}
|
||||
|
||||
authRouter.post('/login', async (req, res) => {
|
||||
const screenName = sanitizeScreenName(req.body?.screenName);
|
||||
const screenName = sanitizeScreenName(req.body?.screenName).slice(0, 64);
|
||||
const password = String(req.body?.password || '');
|
||||
|
||||
if (!screenName || !password) {
|
||||
return res.status(400).json({ error: 'screenName and password are required' });
|
||||
}
|
||||
if (password.length > 256) {
|
||||
return res.status(400).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// If this browser session already has an OSCAR session, clean it up first.
|
||||
const existing = sessions.getSession(req.session.id);
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ async function getUserNames() {
|
|||
}
|
||||
|
||||
usersRouter.get('/users', requireLogin, async (req, res) => {
|
||||
const q = String(req.query?.q || '').trim().toLowerCase();
|
||||
const q = String(req.query?.q || '').trim().toLowerCase().slice(0, 64);
|
||||
try {
|
||||
const names = await getUserNames();
|
||||
const filtered = (q ? names.filter((n) => n.toLowerCase().includes(q)) : names)
|
||||
|
|
|
|||
|
|
@ -2,11 +2,12 @@
|
|||
import express from 'express';
|
||||
import session from 'express-session';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
import { PORT, LISTEN_HOST, SESSION_SECRET, logStartupConfig } from './config.js';
|
||||
import { PORT, LISTEN_HOST, SESSION_SECRET, TRUST_PROXY, COOKIE_SECURE, SESSION_MAX_AGE_MS, NODE_ENV, logStartupConfig } from './config.js';
|
||||
import * as oscar from './oscar.js';
|
||||
import { bus } from './bus.js';
|
||||
import { broadcast } from './poller.js';
|
||||
|
|
@ -21,10 +22,29 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|||
const publicDir = path.resolve(__dirname, '../public');
|
||||
|
||||
const app = express();
|
||||
app.set('trust proxy', 1); // behind nginx
|
||||
app.set('trust proxy', TRUST_PROXY);
|
||||
app.disable('x-powered-by');
|
||||
|
||||
app.use(express.json({ limit: '32kb' }));
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
useDefaults: true,
|
||||
directives: {
|
||||
"default-src": ["'self'"],
|
||||
"base-uri": ["'self'"],
|
||||
"frame-ancestors": ["'none'"],
|
||||
"form-action": ["'self'"],
|
||||
"img-src": ["'self'", 'data:'],
|
||||
"script-src": ["'self'"],
|
||||
"style-src": ["'self'"],
|
||||
"connect-src": ["'self'"],
|
||||
"object-src": ["'none'"],
|
||||
},
|
||||
},
|
||||
referrerPolicy: { policy: 'no-referrer' },
|
||||
}));
|
||||
|
||||
app.use(express.json({ limit: '16kb' }));
|
||||
app.use(express.urlencoded({ extended: false, limit: '16kb' }));
|
||||
|
||||
// CSRF-lite: for POSTs, require JSON content-type and verify Origin when present.
|
||||
app.use((req, res, next) => {
|
||||
|
|
@ -43,26 +63,52 @@ app.use((req, res, next) => {
|
|||
next();
|
||||
});
|
||||
|
||||
const cookieSecure = COOKIE_SECURE === 'true' ? true : COOKIE_SECURE === 'false' ? false : 'auto';
|
||||
app.use(session({
|
||||
name: 'oscar.sid',
|
||||
secret: SESSION_SECRET(),
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
proxy: TRUST_PROXY > 0,
|
||||
cookie: {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: 'auto', // set true behind HTTPS proxy via trust proxy
|
||||
secure: cookieSecure,
|
||||
maxAge: SESSION_MAX_AGE_MS,
|
||||
},
|
||||
}));
|
||||
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 30,
|
||||
limit: 20,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many login attempts, try again later.' },
|
||||
});
|
||||
const apiLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
limit: 120,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many requests, slow down.' },
|
||||
});
|
||||
const sendLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
limit: 30,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many messages, slow down.' },
|
||||
});
|
||||
|
||||
app.use('/api', apiLimiter);
|
||||
app.use('/api/login', loginLimiter);
|
||||
app.use('/api/im', sendLimiter);
|
||||
app.use('/api/chat', sendLimiter);
|
||||
|
||||
app.use('/api', (_req, res, next) => {
|
||||
res.set('Cache-Control', 'no-store');
|
||||
next();
|
||||
});
|
||||
|
||||
app.get('/api/health', (_req, res) => res.json({ ok: true }));
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue