bruteforce.test.js
1.66 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { describe, it, expect } from 'vitest'
import {
attemptKey,
evaluateAttempts,
DEFAULT_MAX_ATTEMPTS,
DEFAULT_WINDOW_MS,
} from '../src/bruteforce.js'
describe('attemptKey', () => {
it('normalizes email and joins ip', () => {
expect(attemptKey(' A@B.com ', '1.2.3.4')).toBe('a@b.com|1.2.3.4')
})
it('omits ip when absent', () => {
expect(attemptKey('a@b.com')).toBe('a@b.com')
})
})
describe('evaluateAttempts', () => {
it('not locked below threshold', () => {
const r = evaluateAttempts({ recentCount: DEFAULT_MAX_ATTEMPTS - 1 })
expect(r.locked).toBe(false)
expect(r.retryAfterMs).toBe(0)
})
it('locked at threshold, retryAfter = full window without oldestAt', () => {
const r = evaluateAttempts({ recentCount: DEFAULT_MAX_ATTEMPTS })
expect(r.locked).toBe(true)
expect(r.retryAfterMs).toBe(DEFAULT_WINDOW_MS)
})
it('precise retryAfter when oldestAt given', () => {
const now = 1_000_000
const oldestAt = now - 60_000
const windowMs = 100_000
const r = evaluateAttempts({ recentCount: 5, maxAttempts: 5, windowMs, oldestAt, now })
expect(r.locked).toBe(true)
expect(r.retryAfterMs).toBe(40_000)
})
it('clamps retryAfter to 0 when oldest already aged out', () => {
const now = 1_000_000
const r = evaluateAttempts({
recentCount: 5,
maxAttempts: 5,
windowMs: 10_000,
oldestAt: now - 50_000,
now,
})
expect(r.retryAfterMs).toBe(0)
})
it('respects custom maxAttempts', () => {
expect(evaluateAttempts({ recentCount: 2, maxAttempts: 3 }).locked).toBe(false)
expect(evaluateAttempts({ recentCount: 3, maxAttempts: 3 }).locked).toBe(true)
})
})