'use strict'; // Rate-limit buckets (#10). Everyone reaches Pulse through the same reverse proxy, so // keying on the client IP put every user in one shared bucket, which the live UI alone // could empty. Instead: // - a trusted SSO identity gets its own bucket (user:); // - Gandalf, proven by a VALID key, gets one (a forged header must not let anyone // drain Gandalf's bucket, so an invalid key falls back to the IP); // - everything else is keyed by IP, as before. const { ipKeyGenerator } = require('express-rate-limit'); const { ssoIdentity } = require('./pageauth'); const { safeEqual } = require('./wsauth'); function rateLimitKey(req, env = process.env) { const who = ssoIdentity(req); if (who && who.username) return `user:${who.username}`; const gandalfKey = req.headers && req.headers['x-gandalf-api-key']; if (gandalfKey && env.GANDALF_API_KEY && safeEqual(gandalfKey, env.GANDALF_API_KEY)) return 'gandalf'; return `ip:${ipKeyGenerator(req.ip || (req.socket && req.socket.remoteAddress) || '')}`; } module.exports = { rateLimitKey };