All files / Bandstand/src/lib login-throttle.ts

100% Statements 24/24
100% Branches 8/8
100% Functions 5/5
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37          1x 1x 1x   1x   83x 83x 83x 83x 83x   1x 17x 17x 14x   17x   1x 26x 26x 26x   1x 2x 2x   1x 5x 5x  
/**
 * Slows down password guessing. In memory: there is one app instance, and a
 * restart clearing the counters is acceptable. Generated passwords are long
 * enough that this is a backstop, not the main defence.
 */
const WINDOW_MS = 15 * 60_000
const MAX_PER_EMAIL = 8
const MAX_PER_IP = 30
 
const failures = new Map<string, number[]>()
 
function recent(key: string, now: number) {
  const list = (failures.get(key) ?? []).filter((t) => now - t < WINDOW_MS)
  failures.set(key, list)
  return list
}
 
export function isThrottled(email: string, ip: string, now = Date.now()) {
  return (
    recent(`e:${email}`, now).length >= MAX_PER_EMAIL ||
    recent(`i:${ip}`, now).length >= MAX_PER_IP
  )
}
 
export function recordFailure(email: string, ip: string, now = Date.now()) {
  recent(`e:${email}`, now).push(now)
  recent(`i:${ip}`, now).push(now)
}
 
export function clearFailures(email: string) {
  failures.delete(`e:${email}`)
}
 
export function resetThrottleForTests() {
  failures.clear()
}