freezmo/lib/rate-limit.ts
Martin Dvorak 618ad5fb9c Add an English/Czech interface language switch
English stays the default; Czech is a full translation. Only the app chrome
is translated - notes and generated decks keep their own language, which is a
core feature, not a setting.

i18n
- lib/i18n-dict.ts: flat en/cs dictionaries (441 keys each), translate() and
  translatePlural() with real Czech plural rules (1 sada / 2-4 sady / 5+ sad).
  English is the default and the fallback for a missing key.
- lib/i18n.ts: browser store (freezmo.locale.v1), useI18n() hook, and the
  x-freezmo-locale header. The hook's t/plural are bound to the locale React
  is rendering with, so the first client render matches the server HTML and
  then re-renders in the stored language; module-level t is only for event
  handlers and non-React helpers.
- <html lang> follows the choice (inline script + setLocale).

UI
- Settings -> Language segmented control (English / Cestina), plus an EN/CS
  button on the key gate for first run.
- Every screen translated: sidebar, header, tab bar, library, deck cards,
  folder bar, create flow, all seven activities, study chrome, results,
  settings + health panel, API-key gate and help, install sheet, offline and
  the deck-not-found page.
- Plural-aware counts everywhere (decks, folders, activities, runs, photos,
  documents, pages, words, wrong attempts).

Server
- API routes and guards (generate, grade, health, http-guard, rate-limit,
  ollama error mapping) answer in the request's language, so error cards and
  the health panel never fall back to English mid-sentence.

Fixes
- A hydration mismatch when a non-default locale was stored silently dropped
  the .dark class after hydration; render-time t() is now bound to the
  hook's locale (UploadScreen.describeExtraction, ResultsScreen.answerFor,
  DeckCard's folder fallback).
- Bumped the service worker cache to freezmo-v4 for this deploy.

Tests: i18n 27/27 (gate toggle, persistence, html lang, Czech plurals,
settings switch) and a rebuilt regression suite 72/72 (English default,
library, create, all 7 activity types, results, settings, install sheet,
offline, PWA, security, Czech smoke).
2026-10-08 13:56:32 +00:00

105 lines
3.1 KiB
TypeScript

/**
* In-memory sliding-window rate limiter.
*
* Deliberately dependency-free and good enough for a self-hosted, single
* instance app: each key (route + client IP) gets N requests per window.
* Counters live in memory and reset on restart, and a busy instance cannot
* share state with others — fine for Freezmo, documented in the README.
*/
import { DEFAULT_LOCALE, translate, type Locale } from "./i18n-dict";
type Hits = { timestamps: number[] };
/**
* Kept on globalThis so dev-mode hot reloads (and any module re-evaluation)
* don't silently reset everybody's counters.
*/
const globalStore = globalThis as unknown as { __freezmoRateLimit?: Map<string, Hits> };
const buckets: Map<string, Hits> = (globalStore.__freezmoRateLimit ??= new Map());
const MAX_BUCKETS = 5_000;
export type RateLimitResult = {
allowed: boolean;
limit: number;
remaining: number;
/** Seconds until the oldest hit falls out of the window (0 when allowed). */
retryAfter: number;
resetAt: number;
};
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
const now = Date.now();
const windowStart = now - windowMs;
let bucket = buckets.get(key);
if (!bucket) {
if (buckets.size >= MAX_BUCKETS) prune(now, windowMs);
bucket = { timestamps: [] };
buckets.set(key, bucket);
}
bucket.timestamps = bucket.timestamps.filter((timestamp) => timestamp > windowStart);
if (bucket.timestamps.length >= limit) {
const oldest = bucket.timestamps[0];
const retryAfter = Math.max(1, Math.ceil((oldest + windowMs - now) / 1000));
return {
allowed: false,
limit,
remaining: 0,
retryAfter,
resetAt: oldest + windowMs,
};
}
bucket.timestamps.push(now);
return {
allowed: true,
limit,
remaining: Math.max(0, limit - bucket.timestamps.length),
retryAfter: 0,
resetAt: now + windowMs,
};
}
/** Drop stale buckets so long-running servers don't grow without bound. */
function prune(now: number, windowMs: number): void {
const cutoff = now - windowMs;
for (const [key, bucket] of buckets) {
if (bucket.timestamps.length === 0 || bucket.timestamps[bucket.timestamps.length - 1] < cutoff) {
buckets.delete(key);
}
if (buckets.size < MAX_BUCKETS / 2) break;
}
}
/** Best-effort client identity: proxy headers first, then a shared bucket. */
export function clientKey(request: Request): string {
const forwarded = request.headers.get("x-forwarded-for");
if (forwarded) {
const first = forwarded.split(",")[0]?.trim();
if (first) return first;
}
return (
request.headers.get("x-real-ip") ??
request.headers.get("cf-connecting-ip") ??
"local"
);
}
export function rateLimitResponse(result: RateLimitResult, locale: Locale = DEFAULT_LOCALE): Response {
return Response.json(
{
error: translate(locale, "server.rateLimited", { limit: result.limit, retry: result.retryAfter }),
kind: "rate_limited",
retryAfter: result.retryAfter,
},
{
status: 429,
headers: {
"Retry-After": String(result.retryAfter),
"Cache-Control": "no-store",
},
},
);
}