Files
Kelx/services/global-rate-limit-owner.js
2026-11-30 16:32:37 +00:00

151 lines
6.8 KiB
JavaScript

"use strict";
// adpanel:rate-limit-policy-owner — the ONE home of the Redis-backed global
// /api rate-limit POLICY (the limiter mounted via app.use("/api/") in
// index.js). Nothing else may construct a parallel global limiter or render
// its wire strings; entry points keep only their mount + hook wiring.
//
// adpanel:rate-limit-shared-revision - the generation-scoped prefix derives
// from the policy store's persisted revision, never this worker's diagnostic
// generation counter. Workers with different restart histories therefore
// increment the same IP bucket for the same committed policy.
// express-rate-limit bakes windowMs at construction, so a changed window OR
// shared revision needs a fresh limiter/store instance. Revision comparison
// also catches a missed window round trip. Limit-only and flag-only edits
// remain live without resetting counters. Atomic committed publications and
// reconciled manual edits call applyPolicy through the injected live getter.
//
// Postures preserved exactly as they were when the options lived in index.js:
// - the injected redisSendCommand is index.js's hardened
// safeRedisSendCommand closure (fail-open placeholder reply with
// positiveHits-valid totalHits 1, NOSCRIPT rethrow for
// retryableIncrement's self-heal) — this module never re-implements a
// client wrapper;
// - passOnStoreError: true keeps the boot-down SCRIPT-LOAD rejection
// fail-open (abuse brake, not an auth control);
// - the skip order is rate_limiting gate → trusted-subnet bypass →
// exempt-path consult through the ONE shared isRateLimitExempt helper
// (single source for both limiter stores), reading the ORIGINAL request
// path because app.use("/api/") strips the mount prefix before the skip
// runs;
// - the 429 shape is the JSON handler with the same message string.
const { policyWindowMs: effectiveWindowMs, policyRevision } = require("./security-policy");
function createGlobalRateLimitOwner(deps) {
const {
rateLimit,
RateLimitRedisStore,
getSecurity,
redisSendCommand,
isRequestFromTrustedSubnet,
isRateLimitExempt,
basePrefix = "rl",
} = deps;
if (typeof rateLimit !== "function") throw new TypeError("createGlobalRateLimitOwner: rateLimit dependency is required");
if (typeof RateLimitRedisStore !== "function") throw new TypeError("createGlobalRateLimitOwner: RateLimitRedisStore dependency is required");
if (typeof getSecurity !== "function") throw new TypeError("createGlobalRateLimitOwner: getSecurity dependency is required (index.js reassigns the security binding on fs.watch — a captured object reference would go stale)");
if (typeof isRequestFromTrustedSubnet !== "function") throw new TypeError("createGlobalRateLimitOwner: isRequestFromTrustedSubnet dependency is required");
if (typeof isRateLimitExempt !== "function") throw new TypeError("createGlobalRateLimitOwner: isRateLimitExempt dependency is required");
const hasRedis = typeof redisSendCommand === "function";
let generation = 0;
let currentWindowMs = null;
let currentRevision = null;
const getMaxRequests = () => {
const limit = parseInt(getSecurity().limit, 10);
return Number.isFinite(limit) && limit > 0 ? limit : 100;
};
const buildLimiter = () => {
const windowMs = effectiveWindowMs(getSecurity());
const revision = policyRevision(getSecurity()) || `legacy-w${windowMs}`;
generation += 1;
// adpanel:rate-limit-shared-revision - each local limiter owns its store
// instance while all workers share this revision's counter namespace.
const store = new RateLimitRedisStore({
prefix: `${basePrefix}:${revision}:`,
sendCommand: redisSendCommand,
});
const limiter = rateLimit({
windowMs,
max: getMaxRequests,
standardHeaders: true,
legacyHeaders: false,
store,
// adpanel:store-fallback-valid-hits — fail-open on the one error class
// the injected wrapper cannot absorb (Redis down since boot leaves the
// store's un-awaited SCRIPT LOAD rejected and increment() rejecting;
// without this option the rejection rethrows out of the middleware and
// 500s every /api/* request).
passOnStoreError: true,
message: "Too many requests from this IP, please try again later.",
skip: (req) => {
const security = getSecurity();
if (!security || security.rate_limiting !== true) return true;
if (isRequestFromTrustedSubnet(req)) return true;
// app.use("/api/") strips the mount prefix before this skip runs, so
// req.path here would be "/me", not "/api/me" — the exempt consult
// below must read the original request path or it silently never
// matches (the same desync note the in-memory limiter carries).
const path = String(req.originalUrl || req.url || "").split("?")[0];
if (isRateLimitExempt(path, req.method)) return true;
return false;
},
handler: (req, res, next, options) => {
res.status(options.statusCode).json({ error: options.message });
},
});
currentWindowMs = windowMs;
currentRevision = revision;
return limiter;
};
const owner = {
// The CURRENT generation's limiter, swapped by applyPolicy(). The wrapper
// indirection is what makes the swap safe for the mounted middleware:
// Express captured `owner.middleware` once at mount time, and every
// request reads owner.current at dispatch — an in-flight request that
// already entered the previous instance finishes under the previous
// policy, every new request enters the rebuilt one.
middleware: (req, res, next) => {
const limiter = owner.current;
if (!limiter) return next();
return limiter(req, res, next);
},
current: null,
// Repeated publication is idempotent; revision adoption also rebuilds a
// worker that missed intermediate changes but retained the same window.
applyPolicy() {
if (!hasRedis) return { rebuilt: false, reason: "no-redis-at-boot" };
const windowMs = effectiveWindowMs(getSecurity());
const revision = policyRevision(getSecurity()) || `legacy-w${windowMs}`;
if (owner.current && windowMs === currentWindowMs && revision === currentRevision) {
return { rebuilt: false, generation, windowMs };
}
owner.current = buildLimiter();
return { rebuilt: true, generation, windowMs: currentWindowMs };
},
describePolicy() {
return {
mounted: hasRedis,
enforcing: hasRedis && owner.current !== null,
generation: hasRedis ? generation : 0,
windowMs: hasRedis ? currentWindowMs : null,
};
},
};
if (hasRedis) {
owner.current = buildLimiter(); // generation 1 at boot, exactly one mount
}
return owner;
}
module.exports = { createGlobalRateLimitOwner };