Files
nx9-chronoseal-rs/server/src/ratelimit.rs
T
thakares b75d586b86 fix: correct 7 bugs found in security audit
Critical:
- crypto.rs (server): use BTreeMap for canonical JSON so key order
  matches JS client's JSON.stringify sort — sig verification was always
  failing silently
- heartbeat.js: capture sentSalt before rotating to next_salt so both
  sides compute next_chain_hash with the same salt — chain was broken
  after the first heartbeat

High:
- trust.rs: avg_speed = total_dist / total_time_ms (px/ms), not
  distance/event_count — legitimate users were always rejected
- ratelimit.rs: add evict_stale() to drain expired entries and prevent
  unbounded HashMap memory growth
- cleanup.rs: call rl.evict_stale() from the periodic cleanup loop

Medium:
- vm.rs: op 0x08 (NOT) is unary — split from binary-op arm so depth
  is not decremented incorrectly
- wasm/crypto.rs: replace unwrap() panics in sign_message /
  get_public_key with unwrap_or_default(); add JS-side guard

Low:
- shared/Cargo.toml, wasm/Cargo.toml: remove leftover add-this comments
- Dockerfile: rust:1.88-bookworm -> rust:1.87-bookworm (1.88 non-existent)
2026-05-08 14:27:41 +05:30

37 lines
1.1 KiB
Rust

use std::collections::HashMap;
use std::time::Instant;
pub struct RateLimiter {
buckets: HashMap<String, (u32, Instant)>,
limit: u32,
window_secs: u64,
}
impl RateLimiter {
pub fn new(limit: u32, window_secs: u64) -> Self {
Self { buckets: HashMap::new(), limit, window_secs }
}
pub fn check(&mut self, key: &str) -> bool {
let now = Instant::now();
let entry = self.buckets.entry(key.to_string()).or_insert((0, now));
if now.duration_since(entry.1).as_secs() >= self.window_secs {
*entry = (1, now);
true
} else if entry.0 >= self.limit {
false
} else {
entry.0 += 1;
true
}
}
/// Remove entries whose rate-limit window has fully elapsed.
/// Call this periodically (e.g. from the cleanup loop) to bound memory usage.
pub fn evict_stale(&mut self) {
let window = self.window_secs;
let now = Instant::now();
self.buckets
.retain(|_, (_, ts)| now.duration_since(*ts).as_secs() < window);
}
}