mirror of
https://github.com/mileswolfallen2/miles-web.git
synced 2026-12-03 15:43:25 +00:00
- Implement tests for HTTP API endpoints, ensuring correct responses and security headers. - Create configuration tests to validate loading of defaults and environment overrides. - Add tests for FEDL service to verify data handling and snapshot functionality. - Introduce GitHub service tests to check API data normalization and caching behavior. - Develop monitor service tests for network checks and uptime calculations. - Implement persistence tests to ensure database migrations are idempotent and data persists across restarts. - Add vault service tests for session management and brute-force protection mechanisms. - Include helper functions for test context creation and JSON response handling.
48 lines
1.3 KiB
JavaScript
48 lines
1.3 KiB
JavaScript
/**
|
|
* Small in-memory sliding-window rate limiter.
|
|
* Single-process by design; the vault login also has a DB-backed limit
|
|
* so brute-force protection survives restarts.
|
|
*/
|
|
export function createRateLimiter({ now = () => Date.now(), maxEntries = 20000 } = {}) {
|
|
const buckets = new Map();
|
|
|
|
function hit(key, { limit, windowMs }) {
|
|
const t = now();
|
|
const cutoff = t - windowMs;
|
|
let hits = buckets.get(key) || [];
|
|
hits = hits.filter((ts) => ts > cutoff);
|
|
|
|
if (hits.length >= limit) {
|
|
buckets.set(key, hits);
|
|
const retryAfterMs = Math.max(0, hits[0] + windowMs - t);
|
|
return { allowed: false, remaining: 0, retryAfterMs };
|
|
}
|
|
|
|
hits.push(t);
|
|
buckets.set(key, hits);
|
|
|
|
if (buckets.size > maxEntries) {
|
|
for (const [k, list] of buckets) {
|
|
if (!list.length || list[list.length - 1] <= cutoff) buckets.delete(k);
|
|
}
|
|
}
|
|
|
|
return { allowed: true, remaining: Math.max(0, limit - hits.length), retryAfterMs: 0 };
|
|
}
|
|
|
|
function reset(key) {
|
|
buckets.delete(key);
|
|
}
|
|
|
|
function cleanup() {
|
|
const cutoff = now() - 60 * 60 * 1000;
|
|
for (const [key, list] of buckets) {
|
|
const kept = list.filter((ts) => ts > cutoff);
|
|
if (kept.length) buckets.set(key, kept);
|
|
else buckets.delete(key);
|
|
}
|
|
}
|
|
|
|
return { hit, reset, cleanup, buckets };
|
|
}
|