Files
accounted/lib/api/token-rate-limit.ts
T
admin e7f0070e84
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s
fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
2026-11-10 09:37:22 +01:00

41 lines
1.4 KiB
TypeScript

/**
* In-memory per-token rate limiter for the public token-authenticated routes
* (calendar feed, payslip PDF). The token IS the authentication on those
* routes, so the limit is keyed by token, not by user.
*
* Process-local by design: a multi-instance deploy limits per instance, which
* is acceptable for these low-value endpoints. Each route creates its own
* limiter so the maps stay isolated.
*/
export function createTokenRateLimiter(options: { max: number; windowMs: number; cleanupEveryMs?: number }) {
const { max, windowMs, cleanupEveryMs = 5 * 60_000 } = options
const entries = new Map<string, { count: number; resetAt: number }>()
let lastCleanup = Date.now()
// Periodic sweep of expired entries so the map cannot grow without bound.
function cleanup() {
const now = Date.now()
if (now - lastCleanup < cleanupEveryMs) return
lastCleanup = now
for (const [key, value] of entries) {
if (now > value.resetAt) entries.delete(key)
}
}
return {
/** Count one request for `token`; false when the window's budget is spent. */
allow(token: string): boolean {
cleanup()
const nowMs = Date.now()
const entry = entries.get(token)
if (entry && nowMs < entry.resetAt) {
if (entry.count >= max) return false
entry.count++
} else {
entries.set(token, { count: 1, resetAt: nowMs + windowMs })
}
return true
},
}
}