Functional Weave
Code in Rust

auth.login-throttle

Allow a login attempt or lock the account out, from its recent failed attempts, with the seconds until it may retry.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 19 tests, run in TypeScript, Python and Rust.

What it does

Before checking a password, ask whether this account may try at all:

decision = loginThrottle(recentFailures, now, {maxAttempts: 5, windowSeconds: 900, lockoutSeconds: 900})
if not allowed: answer 429 with Retry-After: retryAfterSeconds (and do not check the password)
else: check it; on failure, record `now` as another failure

For example

  • login_throttle(, 1,000, max attempts 5, window seconds 900, lockout seconds 900) → allowed true, retry after seconds 0, remaining attempts 5, locked until — no failures: every attempt remains
  • login_throttle(100, 200, 300, 400, 500, max attempts 5, window seconds 900, lockout seconds 900) → allowed true, retry after seconds 0, remaining attempts 1, locked until — four failures in the window leave one attempt
  • login_throttle(100, 200, 300, 400, 500, 600, max attempts 5, window seconds 900, lockout seconds 900) → allowed false, retry after seconds 800, remaining attempts 0, locked until 1,400 the fifth failure within 15 minutes locks the account for 15 minutes from that failure

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

pub fn login_throttle(failures: &[i64], now: i64, policy: &ThrottlePolicy) -> ThrottleDecision
failuresint[]Unix seconds of this account's failed logins, any order; older than window plus lockout may be discarded
nowintthe current time in Unix seconds, read by the caller
policyThrottlePolicy
returnsThrottleDecisionallowed, or locked with retryAfterSeconds for a Retry-After header

The types it declares, generated into your project

/// How many failures lock an account, and for how long.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThrottlePolicy {
    /// failures within the window that trigger a lockout, 1 or more
    pub max_attempts: i64,
    /// how far back failures count towards the limit, 1 or more
    pub window_seconds: i64,
    /// how long a lockout lasts, 1 or more
    pub lockout_seconds: i64,
}

/// Whether to check the password at all, and what to tell the client.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThrottleDecision {
    pub allowed: bool,
    /// 0 when allowed; otherwise seconds until the lockout ends
    pub retry_after_seconds: i64,
    /// failures left before a lockout; 0 while locked
    pub remaining_attempts: i64,
    /// Unix seconds the lockout ends, when locked
    pub locked_until: Option<i64>,
}

Your code names it in one line, in the file that uses it

fune!(auth.login-throttle@^1);  // then call login_throttle(…)
impl/rust.rs · 87 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

/// Allowed or locked, by replaying the failures in time order: max_attempts
/// failures within window_seconds of the latest lock the account for
/// lockout_seconds from that failure, and the count starts again.
///
/// # Panics
/// Panics on a policy number below 1.
pub fn login_throttle(failures: &[i64], now: i64, policy: &ThrottlePolicy) -> ThrottleDecision {
    if policy.max_attempts < 1 {
        panic!("maxAttempts must be a whole number of at least 1");
    }
    if policy.window_seconds < 1 {
        panic!("windowSeconds must be a whole number of at least 1");
    }
    if policy.lockout_seconds < 1 {
        panic!("lockoutSeconds must be a whole number of at least 1");
    }
    let mut times: Vec<i64> = failures.iter().copied().filter(|&t| t <= now).collect();
    times.sort_unstable();
    let mut locked_until: Option<i64> = None;
    let mut streak: Vec<i64> = Vec::new();
    for t in times {
        if let Some(until) = locked_until {
            if t < until {
                continue;
            }
        }
        streak.retain(|&s| s > t - policy.window_seconds);
        streak.push(t);
        if streak.len() as i64 >= policy.max_attempts {
            locked_until = Some(t + policy.lockout_seconds);
            streak.clear();
        }
    }
    if let Some(until) = locked_until {
        if now < until {
            return ThrottleDecision {
                allowed: false,
                retry_after_seconds: until - now,
                remaining_attempts: 0,
                locked_until: Some(until),
            };
        }
    }
    let live = streak.iter().filter(|&&s| s > now - policy.window_seconds).count() as i64;
    ThrottleDecision {
        allowed: true,
        retry_after_seconds: 0,
        remaining_attempts: policy.max_attempts - live,
        locked_until: None,
    }
}

pub fn throttle_decision_to_value(decision: &ThrottleDecision) -> Value {
    Value::obj(vec![
        ("allowed", Value::Bool(decision.allowed)),
        ("retryAfterSeconds", Value::Int(decision.retry_after_seconds)),
        ("remainingAttempts", Value::Int(decision.remaining_attempts)),
        ("lockedUntil", decision.locked_until.map(Value::Int).unwrap_or(Value::Null)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let failures: Vec<i64> = args[0]
        .as_arr()
        .iter()
        .map(|v| match v {
            Value::Int(i) => *i,
            _ => panic!("failures must be whole Unix seconds"),
        })
        .collect();
    let now = match &args[1] {
        Value::Int(i) => *i,
        _ => panic!("now must be a whole number of Unix seconds"),
    };
    let field = |key: &str| match args[2].get(key) {
        Value::Int(i) => *i,
        _ => panic!("{} must be a whole number of at least 1", key),
    };
    let policy = ThrottlePolicy {
        max_attempts: field("maxAttempts"),
        window_seconds: field("windowSeconds"),
        lockout_seconds: field("lockoutSeconds"),
    };
    throttle_decision_to_value(&login_throttle(&failures, now, &policy))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add auth.login-throttle
Download for Rust auth.login-throttle-1.0.0-rust.fune · 13,901 bytes sha256 e5bd5f3032990cc8f47739b48e497f44d9e1e238dc8a6e3d0aa474654ef243f6

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./auth.login-throttle-1.0.0-rust.fune, or fetch it from a terminal with fune pull auth.login-throttle@1.0.0:rust.

The whole function, every language, is one file too: auth.login-throttle-1.0.0.fune, 18,062 bytes, sha256 cb6d13f80567a633f50be0eb2ba9f2432ad3e1c6d9138f5a2bbae76f7cc2d544. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before auth.login-throttle

after — your function gets the result and the arguments, and returns the final result.

// fune: after auth.login-throttle

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.login-throttle --steps.

// fune: step auth.login-throttle after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
no failures: every attempt remains , 1,000, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 5, locked until —
four failures in the window leave one attempt 100, 200, 300, 400, 500, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 1, locked until —
the fifth failure within 15 minutes locks the account for 15 minutes from that failure 100, 200, 300, 400, 500, 600, max attempts 5, window seconds 900, lockout seconds 900 → allowed false, retry after seconds 800, remaining attempts 0, locked until 1,400
one second before the lockout ends 100, 200, 300, 400, 500, 1,399, max attempts 5, window seconds 900, lockout seconds 900 → allowed false, retry after seconds 1, remaining attempts 0, locked until 1,400
the lockout ends exactly at lockedUntil, with the full allowance back 100, 200, 300, 400, 500, 1,400, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 5, locked until —
failures given out of order are replayed in time order 500, 300, 100, 400, 200, 600, max attempts 5, window seconds 900, lockout seconds 900 → allowed false, retry after seconds 800, remaining attempts 0, locked until 1,400
five failures spread over 20 minutes never have five in one window 0, 300, 600, 900, 1,200, 1,300, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 2, locked until —
failures during a lockout neither count nor extend it 100, 200, 300, 400, 500, 600, 700, 800, max attempts 5, window seconds 900, lockout seconds 900 → allowed false, retry after seconds 600, remaining attempts 0, locked until 1,400
after a lockout only newer failures count 100, 200, 300, 400, 500, 1,500, 1,600, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 4, locked until —
a second run of five failures locks again 100, 200, 300, 400, 500, 1,500, 1,600, 1,700, 1,800, 1,900, 2,000, max attempts 5, window seconds 900, lockout seconds 900 → allowed false, retry after seconds 800, remaining attempts 0, locked until 2,800
Show the other 9 tests
CaseArgumentsExpected
a failure stamped after now (clock skew) is ignored 5,000, 1,000, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 5, locked until —
old failures fall out of the window: at 1250 only the failure at 400 is within 15 minutes 100, 200, 300, 400, 1,250, max attempts 5, window seconds 900, lockout seconds 900 → allowed true, retry after seconds 0, remaining attempts 4, locked until —
one attempt allowed: locked by a single failure 100, 120, max attempts 1, window seconds 60, lockout seconds 30 → allowed false, retry after seconds 10, remaining attempts 0, locked until 130
one attempt allowed: free again after the 30-second lockout 100, 150, max attempts 1, window seconds 60, lockout seconds 30 → allowed true, retry after seconds 0, remaining attempts 1, locked until —
zero attempts is not a policy , 1,000, max attempts 0, window seconds 900, lockout seconds 900 → error: maxAttempts must be a whole number of at least 1
a zero-second window , 1,000, max attempts 5, window seconds 0, lockout seconds 900 → error: windowSeconds must be a whole number of at least 1
a zero-second lockout , 1,000, max attempts 5, window seconds 900, lockout seconds 0 → error: lockoutSeconds must be a whole number of at least 1
failure times with fractions of a second 100.5, 1,000, max attempts 5, window seconds 900, lockout seconds 900 → error: failures must be whole Unix seconds
now in fractional seconds , 1,000.5, max attempts 5, window seconds 900, lockout seconds 900 → error: now must be a whole number of Unix seconds

More from the author

The application stores the times of failed logins per account (per normalised email, so an attacker cannot dodge the count by changing case) and passes them in with the current time. The capability keeps no state and reads no clock.

**The rule.** Failures are replayed in time order. When `maxAttempts` failures fall within `windowSeconds` of each other (each within the window ending at the latest), the account is locked from that failure for `lockoutSeconds`, and the count starts again from zero. Failures recorded while locked do not count and do not extend the lockout (the application should not be recording them, since it does not check the password then). A lockout ends exactly at `lockedUntil`: at that second the account is allowed again, with its full allowance, because the failures that caused the lockout have been paid for. Failures stamped after `now` (clock skew between servers) are ignored.

`remainingAttempts` is how many more failures the account can have before it is locked, counting only failures still inside the window; a login form may show it ("2 attempts left"), though many sites prefer not to.

**Settings.** 5 attempts in 15 minutes and a 15-minute lockout (`{5, 900, 900}`) is a common, humane default: it stops online guessing (at most 480 guesses a day) while a forgetful person is inconvenienced for minutes, not locked out until support replies. NIST SP 800-63B-4 section 3.2.2 requires limiting consecutive failed attempts to no more than 100, so any setting here meets that; OWASP's Authentication Cheat Sheet discusses the trade-off with denial of service against known usernames.

A successful login does not clear earlier failures here; if the application wants that, it deletes the stored failures on success.

Sources: NIST SP 800-63B-4, section 3.2.2, Rate Limiting (Throttling) (https://pages.nist.gov/800-63-4/sp800-63b.html); OWASP Authentication Cheat Sheet, Account Lockout (https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html); RFC 9110 section 10.2.3, Retry-After.

Files

PathBytes
README.md2,411
impl/python.py2,059
impl/rust.rs3,088
impl/typescript.ts1,964
vectors.json4,801