fix(security): add SPA CSP, drop x-powered-by, strengthen dedupe hash

Address SonarQube security hotspots on the website:

- server/src/app.js: replace `contentSecurityPolicy: false` with a helmet CSP
  tuned for the built React SPA (script-src 'self'; style-src adds 'unsafe-inline'
  for React inline styles + the Google Fonts stylesheet; font-src gstatic; img-src
  allows data:/https: for uploads, embedded body images and BRAND_* assets;
  connect-src 'self' for REST+SSE). upgrade-insecure-requests is intentionally
  omitted (TLS terminates at the proxy; keeps local `npm start` over http working).
  The /api/docs Swagger UI route gets a scoped looser policy (inline script/style)
  since swagger-ui-express injects an inline bootstrap.
- client/vite.config.js: disable the inline module-preload polyfill so code-split
  builds keep `script-src 'self'` valid (RichTextEditor is a separate chunk).
- bot/src/app.js, server/src/internalApp.js: disable x-powered-by on the two
  internal-only listeners (the public app already strips it via helmet).
- shardEvents dedupe key: SHA-1 -> SHA-256 truncated to 40 hex chars (fits the
  existing CHAR(40) column, no migration; it is a content fingerprint, not a
  security value). schema.sql comment updated to match.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NgyHnrNa8WwG3doxvxjuCr
This commit is contained in:
2026-07-20 23:02:11 -05:00
parent 82bf2c972c
commit e1461d9161
6 changed files with 65 additions and 9 deletions

View File

@@ -36,11 +36,38 @@ app.use(trustProxyDebug)
// obvious scanner probes are 404'd immediately without reaching real handlers.
app.use(botScore.guard)
// Security headers. CSP is left off here and will be tuned for the React SPA in
// the frontend phase; the rest of helmet's protections stay enabled.
// Security headers, including a Content-Security-Policy tuned for the built React
// SPA. Notes on each non-'self' allowance:
// • style-src 'unsafe-inline' — React renders pervasive inline `style={{…}}`
// attributes, and CSP style *attributes* cannot be nonce'd; this is required.
// Also whitelists the Google Fonts stylesheet host.
// • font-src — Google Fonts (Cinzel) serves the font files from gstatic.
// • img-src https:/data: — uploaded images are same-origin, but wiki/news bodies
// (sanitizeHtml allows <img> over http/https) and BRAND_* logo/hero/favicon may
// point at external https images. http images are blocked by mixed-content on
// the https site anyway.
// • connect-src 'self' — the REST API and SSE streams are same-origin.
// • upgrade-insecure-requests is intentionally dropped: TLS is terminated at the
// proxy, there are no mixed-content subresources to upgrade, and leaving it on
// breaks a local `npm start` served over plain http.
// The interactive API docs at /api/docs get their own looser policy below.
app.use(
helmet({
contentSecurityPolicy: false,
contentSecurityPolicy: {
useDefaults: true,
directives: {
'default-src': ["'self'"],
'script-src': ["'self'"],
'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
'font-src': ["'self'", 'https://fonts.gstatic.com'],
'img-src': ["'self'", 'data:', 'https:'],
'connect-src': ["'self'"],
'frame-ancestors': ["'self'"],
'object-src': ["'none'"],
'base-uri': ["'self'"],
'upgrade-insecure-requests': null,
},
},
crossOriginResourcePolicy: { policy: 'cross-origin' },
}),
)
@@ -123,7 +150,18 @@ try {
// #swagger.ignore = true
res.json(swaggerSpec)
})
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
// swagger-ui-express injects an inline bootstrap script and inline styles, which
// the global 'self'-only script-src would block — relax CSP for this route only.
const swaggerCsp = helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
'script-src': ["'self'", "'unsafe-inline'"],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", 'data:', 'https:'],
'upgrade-insecure-requests': null,
},
})
app.use('/api/docs', swaggerCsp, swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
customSiteTitle: `${brand.name} API docs`,
swaggerOptions: { persistAuthorization: true },
}))

View File

@@ -11,6 +11,9 @@ const internalRouter = require('./router/v1/internal/internal.routes')
const internalApp = express()
// Internal-only listener, but don't advertise the stack anyway (defense in depth).
internalApp.disable('x-powered-by')
internalApp.use(express.json())
// Liveness probe for this listener (no secret required); mirrors the bot's

View File

@@ -18,10 +18,17 @@ function stableStringify(value) {
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`
}
// dedupe_key = sha1(kind + t + stable-json(payload)). Two identical events (same
// kind, same timestamp, same body) collapse to one row.
// dedupe_key = sha256(kind + t + stable-json(payload)), truncated to 40 hex chars.
// This is a content fingerprint for idempotent INSERT IGNORE, not a security value,
// but we use SHA-256 rather than SHA-1 anyway; the truncation keeps it inside the
// CHAR(40) column (160 bits is ample collision resistance for dedupe). Two identical
// events (same kind, same timestamp, same body) collapse to one row.
function dedupeKey(kind, t, payload) {
return crypto.createHash('sha1').update(`${kind}|${t}|${stableStringify(payload)}`).digest('hex')
return crypto
.createHash('sha256')
.update(`${kind}|${t}|${stableStringify(payload)}`)
.digest('hex')
.slice(0, 40)
}
// Append one event. Returns true if a new row was inserted (false = deduped).