rate_limiter.ts

In-memory sliding window rate limiter.

Tracks failed attempts per key (typically IP address) using a sliding time window. No external dependencies — state resets on server restart.

Reserve, then settle. A handler that checks the limiter, awaits work, and records afterwards lets every request of a concurrent burst pass the check before any of them records — a burst of any size gets through. RateLimiter.try_reserve closes that: it admits a request and counts it in flight in one synchronous step, and the attempt counts against the cap until its RateLimitReservation is settled — record keeps it as an attempt, release gives it back. Every handler whose outcome decides whether the attempt counts reserves, and releases in a finally so an early return or a throw never leaks an in-flight slot; check + record stays for callers that record in the same synchronous step they check.

Attempts count while in flight, whatever their outcome — so a burst of *correct* concurrent attempts from one key is capped too. The password surfaces therefore reserve with RateLimiter.reserve, which waits up to RESERVATION_WAIT_MAX_MS for a slot when the cap is reached only by attempts in flight, and refuses at once when it is reached by recorded ones.

view source

Declarations
#

20 declarations

announce_rate_limiters_disabled
#

rate_limiter.ts view source

(): void import {announce_rate_limiters_disabled} from '@fuzdev/fuz_app/rate_limiter.js';

Print RATE_LIMITERS_DISABLED_BANNER with console.error, once per module instance.

Deliberately on stderr as well as the surface warning, which goes through the server's logger: a deployment that reached this mode is unprotected on every password-bearing route, and that must show in its first lines of output even with the logger silenced. Once per module instance, so a module instance that assembles many in-process servers prints it once, while every spawned test binary prints it at startup — the twin of the Rust spine's RateLimiterMode::limiter.

returns

void

create_rate_limiter
#

default_action_account_rate_limit
#

rate_limiter.ts view source

RateLimiterOptions import {default_action_account_rate_limit} from '@fuzdev/fuz_app/rate_limiter.js';

Default options for per-account action-dispatcher rate limiting: 1200 attempts per 15 minutes. Shared by the HTTP RPC and WebSocket action dispatchers. Permissive — sustained ~80/min is well above any human admin workflow; an oracle probing 10k addresses still finishes in ~2 hours, slow enough to surface in audit. Tighten downstream.

default_action_ip_rate_limit
#

rate_limiter.ts view source

RateLimiterOptions import {default_action_ip_rate_limit} from '@fuzdev/fuz_app/rate_limiter.js';

Default options for per-IP action-dispatcher rate limiting: 600 attempts per 15 minutes. Shared by the HTTP RPC and WebSocket action dispatchers (one budget per action, not per transport). Permissive — catches runaway scripts and egregious oracle probes, but well above human or normal automation pace. Tighten downstream for stricter deployments.

default_login_account_rate_limit
#

rate_limiter.ts view source

RateLimiterOptions import {default_login_account_rate_limit} from '@fuzdev/fuz_app/rate_limiter.js';

Default options for per-account login rate limiting: 10 attempts per 30 minutes.

default_login_ip_rate_limit
#

rate_limiter.ts view source

RateLimiterOptions import {default_login_ip_rate_limit} from '@fuzdev/fuz_app/rate_limiter.js';

Default options for per-IP auth rate limiting: 5 attempts per 15 minutes. The default for each of the three per-surface IP limiters (login + password change, signup, bootstrap) and the shared cap the Rust spine's DEFAULT_LOGIN_IP_RATE_LIMIT pins.

Deliberately not widened when the buckets became monotone (a success no longer refunds them — see RateLimiter.reset). Widening would have bought NAT'd egress headroom by loosening the one bound that caps credential guessing from a single address; splitting one shared bucket into three per-surface ones buys the same headroom without touching that bound.

DEFAULT_RATE_LIMITER_MAX_KEYS
#

rate_limiter.ts view source

100000 import {DEFAULT_RATE_LIMITER_MAX_KEYS} from '@fuzdev/fuz_app/rate_limiter.js';

Default tracked-key cap: bounds worst-case memory under key-enumeration attacks (an attacker rotating source IPs cannot grow the backing map indefinitely between cleanup ticks). Tuned to comfortably fit real traffic for a single-instance deployment while capping memory at a few MB in the worst case.

IN_FLIGHT_RETRY_AFTER_SECONDS
#

rate_limiter.ts view source

1 import {IN_FLIGHT_RETRY_AFTER_SECONDS} from '@fuzdev/fuz_app/rate_limiter.js';

retry_after reported while a key is at its cap only because of attempts still in flight. Those settle within a request's lifetime, so the earliest moment worth retrying is the next second, not the oldest recorded attempt's expiry. Mirrors the Rust spine's IN_FLIGHT_RETRY_AFTER_SECONDS.

RATE_LIMITERS_DISABLED_BANNER
#

rate_limiter.ts view source

"!!! RATE LIMITERS DISABLED — test-only mode. A production server must never print this." import {RATE_LIMITERS_DISABLED_BANNER} from '@fuzdev/fuz_app/rate_limiter.js';

The stderr line a process prints the first time 'disabled_for_testing' leaves a limiter null — the same text as the Rust spine's.

RateLimiter
#

rate_limiter.ts view source

import {RateLimiter} from '@fuzdev/fuz_app/rate_limiter.js';

In-memory sliding window rate limiter.

Stores an array of timestamps per key, plus a count of attempts reserved (try_reserve) and not yet settled. On check/record, timestamps outside the window are pruned. retry_after reports seconds until the oldest active timestamp expires.

The backing store is an LruMap when options.max_keys is a positive number (default DEFAULT_RATE_LIMITER_MAX_KEYS) and a plain Map when max_keys is null. The LruMap path bounds memory under key-enumeration attack at the cost of a slight per-op overhead and the LRU trade-off described on RateLimiterOptions.max_keys.

Parameters that accept RateLimiter | null (e.g. login_ip_rate_limiter, login_account_rate_limiter) disable rate limiting when null is passed — no checks are performed and all requests are allowed through. create_app_server surfaces each disabled limiter as a warning diagnostic.

options

type RateLimiterOptions

readonly

constructor

type new (options: RateLimiterOptions): RateLimiter

options

the limiter's bounds

throws

  • RangeError - when `max_attempts`, `window_ms`, or `cleanup_interval_ms` is not a safe integer ≥ 0, `cleanup_interval_ms` exceeds `PERIODIC_INTERVAL_MS_MAX`, or `max_keys` is neither `null` nor a positive safe integer

[Symbol.for('nodejs.util.inspect.custom')]

Custom inspect output that exposes only options and size, never the tracked keys. The key set is sensitive (usernames / IP addresses) and unbounded, so it must not leak into logs via util.inspect / console.log. The #attempts field is already #private, but this keeps the boundary explicit against inspect(…, {showHidden: true}) and future field-visibility changes.

type (): { options: RateLimiterOptions; size: number; }

returns { options: RateLimiterOptions; size: number; }

check

Check whether key is allowed without recording an attempt, counting recorded attempts and reserved ones still in flight.

Prunes timestamps that fell outside the window as a side effect (and removes the key entirely when none remain and none are in flight), so the backing map stays bounded even under read-only traffic.

A check followed by an awaited operation and then a record lets a concurrent burst past the cap; reserve with try_reserve instead.

type (key: string, now?: number): RateLimitResult

key

rate limit key (e.g. IP address)

type string

now?

current timestamp in ms (defaults to Date.now())

type number
optional default Date.now()

mutates

  • internal map — prunes expired timestamps for `key`

record

Record a failed attempt for key and return the updated result.

type (key: string, now?: number): RateLimitResult

key

rate limit key (e.g. IP address)

type string

now?

current timestamp in ms (defaults to Date.now())

type number
optional default Date.now()

mutates

  • internal map — appends `now` to the timestamp list for `key` (after pruning expired entries)

try_reserve

Admit an attempt for key and count it in flight, in one synchronous step.

The attempt counts against the cap — for this request and every concurrent one — until the returned reservation is settled: recorded as an attempt, or released. So no burst of concurrent requests gets more than max_attempts past the limiter between them. Release in a finally: nothing settles a reservation for you, so one left unsettled holds its slot for the life of the process.

type (key: string, now?: number): RateLimitReserveResult

key

rate limit key (e.g. IP address)

type string

now?

current timestamp in ms (defaults to Date.now())

type number
optional default Date.now()

the reservation, or {ok: false, retry_after} when recorded plus in-flight attempts already reach the cap (nothing is reserved then)

mutates

  • internal map — increments `key`'s in-flight count, creating its entry when absent

reserve

try_reserve, waiting up to max_wait_ms for a slot when the key is at its cap only because of attempts still in flight.

Each settle (and record and reset) on the key wakes its waiters to re-decide — that key's only, so a settle costs nothing for waiters parked elsewhere: a freed slot is reserved; recorded attempts reaching the cap refuse at once with their real retry_after; reaching max_wait_ms (or signal aborting) refuses with IN_FLIGHT_RETRY_AFTER_SECONDS. At most max_attempts reservations wait on one key — one more is refused at once — so a flood can't park requests without bound. A waiter that leaves, by any path, leaves the key's waiter count as it found it. A waiter holds no place in a queue: each wake, every waiter re-decides, so one can lose every race for a freed slot until max_wait_ms refuses it.

type (key: string, options?: RateLimitReserveOptions): Promise<RateLimitReserveResult>

key

rate limit key (e.g. IP address)

type string

options?

the wait bound and an abort signal

optional default {}
returns Promise<RateLimitReserveResult>

the reservation, or {ok: false, retry_after} as described (nothing is reserved then)

mutates

  • internal map — increments `key`'s in-flight count on admission; counts the call in `key`'s waiters while it waits

reset

Clear all attempts for key.

Account-grain keys only. Called after a successful auth to forgive a user's own typos, which is safe because the key *is* the account being attacked — clearing it requires that account's credential and can only widen the budget against an account the caller already holds.

Never call this on an IP-aggregate key. That bucket is the distributed-spray backstop, and success on one account must not zero the budget shared by every other account reachable from the same IP; otherwise an attacker interleaves their own logins (or, under open signup, throwaway account creations needing no credential at all) with guesses against arbitrary victims and sprays indefinitely from one address. The only success that records on an IP bucket is an open signup (charged like a failure); no success clears one, so with no reset each is a monotone-within-window counter that only time clears.

Because they are monotone, the IP buckets are one instance per auth surface (login_ip_rate_limiter, signup_ip_rate_limiter, bootstrap_ip_rate_limiter) rather than one shared across all of them. A single instance meant a failure on any surface spent the budget that bounds guessing on every other one, and one caller's exhaustion denied four routes at once — a cost that used to be masked by the reset this doc forbids.

Attempts still in flight on key (reserved by concurrent requests) are kept: a reset forgives what was recorded, not what is still running.

type (key: string): void

key

type string
returns void

mutates

  • internal map — removes the entry for `key`, or clears its timestamps while attempts are in flight

cleanup

Remove entries whose timestamps are all outside the window and that have no attempt in flight.

type (now?: number): void

now?

current timestamp in ms (defaults to Date.now())

type number
optional default Date.now()
returns void

mutates

  • internal map — prunes expired timestamps and deletes empty keys

dispose

Stop the cleanup timer. Safe to call multiple times.

type (): void

returns void

mutates

  • timer — clears the cleanup `setInterval` and nulls the handle

size

Number of tracked keys.

type number

getter

waiter_keys

Keys holding a parked-waiter slot right now (see reserve): each slot is removed with its key's last waiter. For tests pinning that a waiter leaves nothing behind; the twin of the Rust spine's test-only waiter_keys.

type number

getter

internal

RateLimiterMode
#

rate_limiter.ts view source

RateLimiterMode

type "enforced" | "disabled_for_testing"

import type {RateLimiterMode} from '@fuzdev/fuz_app/rate_limiter.js';

Whether a server builds the rate limiters it is not handed — AppServerOptions.rate_limiters.

  • 'enforced' — every limiter left out of the options is a default instance. The only mode a production server uses, and the default.
  • 'disabled_for_testing' — every limiter left out is null, so nothing is throttled. For in-process test apps and test binaries: they drive many round-trips from one address, and the IP buckets are monotone within their window (a success never refunds them, see RateLimiter.reset), so a suite's failures pile up until every later call is refused.

A limiter passed explicitly — an instance or null — wins over the mode either way, so a rate-limit test enables just the limiter it pins. The disabled mode is loud: create_app_server adds a surface warning, which log_startup_summary logs at assembly, and the first limiter it leaves null prints RATE_LIMITERS_DISABLED_BANNER to stderr once per module instance.

Twin of the Rust spine's fuz_auth::RateLimiterMode (Enforced / DisabledForTesting).

RateLimiterOptions
#

rate_limiter.ts view source

RateLimiterOptions import type {RateLimiterOptions} from '@fuzdev/fuz_app/rate_limiter.js';

Configuration for a rate limiter instance.

max_attempts

Maximum allowed attempts within the window, a safe integer ≥ 0. 0 refuses every attempt — check, try_reserve, and reserve answer at once with the window's length as retry_after, tracking nothing.

type number

window_ms

Sliding window duration in milliseconds, a safe integer ≥ 0.

type number

cleanup_interval_ms

Interval for pruning stale entries, an integer from 0 to PERIODIC_INTERVAL_MS_MAX (0 disables the timer) — the largest delay a timer honours; past it setInterval fires every millisecond.

type number

max_keys?

Maximum tracked keys. When exceeded, the least-recently-used key is evicted — bounds memory under key-enumeration attacks. Default: DEFAULT_RATE_LIMITER_MAX_KEYS (100_000). Pass null to disable the cap (falls back to an unbounded Map — only recommended when the key set is known to be closed, e.g. a per-account limiter keyed to a bounded-size account table).

LRU trade-off: every check / record call marks the key as most-recently-used, so keys under active attack stay fresh and won't be evicted. A slow-burn attacker spread across many low-volume keys can, however, drop out of the table and reset their budget — set max_keys high enough to fit the expected legitimate key set and this stays theoretical.

A number must be a positive safe integer.

type number | null

RateLimitKey
#

rate_limiter.ts view source

value + type

"both" | "account" | "ip"

type "both" | "account" | "ip"

import {RateLimitKey} from '@fuzdev/fuz_app/rate_limiter.js';

Rate limit key type — declares what a route or RPC action's rate limiter is keyed on.

  • 'ip' — per-IP rate limiting (login, bootstrap, password change, signup)
  • 'account' — per-account rate limiting. On REST auth routes the key is the submitted identifier (login). On RPC actions (post-auth) the key is the resolved actor id (request_context.actor.id) — separate namespace.
  • 'both' — both keys.

RateLimitReservation
#

rate_limiter.ts view source

RateLimitReservation import type {RateLimitReservation} from '@fuzdev/fuz_app/rate_limiter.js';

An attempt admitted by RateLimiter.try_reserve or RateLimiter.reserve, counted against the key's cap until settled.

Settle it exactly once: record keeps it as an attempt (a failure, on the failure-counting surfaces), release gives it back. Both are idempotent and the first call wins, so a handler calls record where the outcome is known and release in a finally. When the key's entry was evicted or reset meanwhile, record still records (into the key's current entry) and release is a no-op. A reservation made against no limiter (try_reserve_optional / reserve_optional with null) is inert.

record

Settle as a recorded attempt.

type (now?: number | undefined): void

now?

current timestamp in ms (defaults to Date.now())

type number
optional
returns void

release

Settle without recording an attempt.

type (): void

returns void

RateLimitReserveOptions
#

rate_limiter.ts view source

RateLimitReserveOptions import type {RateLimitReserveOptions} from '@fuzdev/fuz_app/rate_limiter.js';

Options for RateLimiter.reserve.

max_wait_ms?

How long to wait for a slot. Default RESERVATION_WAIT_MAX_MS.

type number

signal?

Stops the wait (a refusal, retry_after: IN_FLIGHT_RETRY_AFTER_SECONDS) — pass the request's signal.

type AbortSignal

RateLimitReserveResult
#

rate_limiter.ts view source

RateLimitReserveResult

type { ok: true; reservation: RateLimitReservation; } | { ok: false; retry_after: number; }

import type {RateLimitReserveResult} from '@fuzdev/fuz_app/rate_limiter.js';

Result of RateLimiter.try_reserve and RateLimiter.reserve.

RateLimitResult
#

rate_limiter.ts view source

RateLimitResult import type {RateLimitResult} from '@fuzdev/fuz_app/rate_limiter.js';

Result of a rate limit check or record operation.

allowed

Whether the request is allowed.

type boolean

remaining

Remaining attempts before blocking, counting attempts still in flight.

type number

retry_after

Seconds until the oldest active attempt expires (0 if allowed).

type number

RESERVATION_WAIT_MAX_MS
#

rate_limiter.ts view source

5000 import {RESERVATION_WAIT_MAX_MS} from '@fuzdev/fuz_app/rate_limiter.js';

How long a password-surface reservation (RateLimiter.reserve) waits for a slot when the key is at its cap only because of attempts still in flight, before answering 429. Mirrors the Rust spine's RESERVATION_WAIT_MAX.

Counting attempts while they are in flight caps *successful* concurrent attempts from one key too — a class behind one NAT logging in together. Those attempts settle within a request's lifetime, so a short wait turns most of those refusals into a late success, while a key at its cap on *recorded* attempts is still refused at once.

reserve_optional
#

rate_limiter.ts view source

(limiter: RateLimiter | null, key: string | null, options?: RateLimitReserveOptions | undefined): Promise<RateLimitReserveResult> import {reserve_optional} from '@fuzdev/fuz_app/rate_limiter.js';

RateLimiter.reserve against a limiter that may be absent — an inert reservation when limiter or key is null. Twin of the Rust spine's reserve_optional.

limiter

the limiter, or null when disabled

type RateLimiter | null

key

rate limit key, or null to skip

type string | null

options?

the wait bound and an abort signal

optional

returns

Promise<RateLimitReserveResult>

try_reserve_optional
#

rate_limiter.ts view source

(limiter: RateLimiter | null, key: string | null, now?: number): RateLimitReserveResult import {try_reserve_optional} from '@fuzdev/fuz_app/rate_limiter.js';

RateLimiter.try_reserve against a limiter that may be absent.

An inert reservation when limiter is null (disabled) or key is null (no resolvable key — e.g. no client IP), so a handler reserves and settles the same way whether or not the surface is limited. Twin of the Rust spine's try_reserve_optional.

limiter

the limiter, or null when disabled

type RateLimiter | null

key

rate limit key, or null to skip

type string | null

now?

current timestamp in ms (defaults to Date.now())

type number
optional default Date.now()

returns

RateLimitReserveResult

Depends on
#

Imported by
#