Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,235 @@
|
||||
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@toolctrl/shared-store";
|
||||
import { getSharedStore } from "../shared-store.js";
|
||||
|
||||
export const LOGIN_RATE_LIMIT_WINDOW_MS = 60_000;
|
||||
export const LOGIN_RATE_LIMIT_IP_ATTEMPTS = 10;
|
||||
export const LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS = 5;
|
||||
|
||||
const LOGIN_RATE_LIMIT_WINDOW_SECONDS = Math.ceil(LOGIN_RATE_LIMIT_WINDOW_MS / 1000);
|
||||
const UNKNOWN_CLIENT_IP = "unknown";
|
||||
const UNKNOWN_ACCOUNT_KEY = "unknown-account";
|
||||
const FINGERPRINT_PREFIX = "acct_";
|
||||
|
||||
export type LoginRateLimitScope = "ip" | "account";
|
||||
|
||||
export type LoginRateLimitRequest = {
|
||||
headers?: Headers | Record<string, string | string[] | undefined>;
|
||||
remoteAddress?: string | null;
|
||||
account?: unknown;
|
||||
};
|
||||
|
||||
export type LoginRateLimitAllowed = {
|
||||
allowed: true;
|
||||
clientIp: string;
|
||||
accountFingerprint: string;
|
||||
};
|
||||
|
||||
export type LoginRateLimitBlocked = {
|
||||
allowed: false;
|
||||
scope: LoginRateLimitScope;
|
||||
retryAfterSeconds: number;
|
||||
clientIp: string;
|
||||
accountFingerprint: string;
|
||||
};
|
||||
|
||||
export type LoginRateLimitResult = LoginRateLimitAllowed | LoginRateLimitBlocked;
|
||||
|
||||
/**
|
||||
* Lazy holder around the two fixed-window limiters. Built on first use
|
||||
* so tests can swap the SharedStore via `__setLoginRateLimitStoreForTests`
|
||||
* before any limiter is constructed.
|
||||
*/
|
||||
type Limiters = {
|
||||
ip: FixedWindowRateLimiter;
|
||||
account: FixedWindowRateLimiter;
|
||||
store: SharedStore;
|
||||
};
|
||||
|
||||
let limiters: Limiters | null = null;
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
|
||||
function getLimiters(): Limiters {
|
||||
if (limiters !== null) {
|
||||
return limiters;
|
||||
}
|
||||
const store = storeFactory();
|
||||
limiters = {
|
||||
store,
|
||||
ip: createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "login-rate-limit:ip",
|
||||
windowSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
|
||||
max: LOGIN_RATE_LIMIT_IP_ATTEMPTS,
|
||||
}),
|
||||
account: createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "login-rate-limit:account",
|
||||
windowSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
|
||||
max: LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS,
|
||||
}),
|
||||
};
|
||||
return limiters;
|
||||
}
|
||||
|
||||
export async function checkLoginRateLimit(request: LoginRateLimitRequest): Promise<LoginRateLimitResult> {
|
||||
const clientIp = deriveLoginRateLimitClientIp(request);
|
||||
const accountKey = normalizeLoginRateLimitAccount(request.account);
|
||||
const accountFingerprint = createLoginRateLimitAccountFingerprint(accountKey);
|
||||
const { ip, account, store } = getLimiters();
|
||||
|
||||
const ipState = await readCounter(store, "login-rate-limit:ip", clientIp);
|
||||
if (ipState.count >= LOGIN_RATE_LIMIT_IP_ATTEMPTS) {
|
||||
return {
|
||||
allowed: false,
|
||||
scope: "ip",
|
||||
retryAfterSeconds: Math.max(1, ipState.ttlSeconds),
|
||||
clientIp,
|
||||
accountFingerprint,
|
||||
};
|
||||
}
|
||||
|
||||
const accountState = await readCounter(store, "login-rate-limit:account", accountKey);
|
||||
if (accountState.count >= LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS) {
|
||||
return {
|
||||
allowed: false,
|
||||
scope: "account",
|
||||
retryAfterSeconds: Math.max(1, accountState.ttlSeconds),
|
||||
clientIp,
|
||||
accountFingerprint,
|
||||
};
|
||||
}
|
||||
|
||||
// Silence unused-var: the limiter objects are kept on the cached `Limiters`
|
||||
// because `recordFailedLoginAttempt` consumes them on the write path.
|
||||
void ip;
|
||||
void account;
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
clientIp,
|
||||
accountFingerprint,
|
||||
};
|
||||
}
|
||||
|
||||
export async function recordFailedLoginAttempt(request: LoginRateLimitRequest): Promise<void> {
|
||||
const { ip, account } = getLimiters();
|
||||
const clientIp = deriveLoginRateLimitClientIp(request);
|
||||
const accountKey = normalizeLoginRateLimitAccount(request.account);
|
||||
await Promise.all([ip.consume(clientIp), account.consume(accountKey)]);
|
||||
}
|
||||
|
||||
export async function recordSuccessfulLogin(request: Pick<LoginRateLimitRequest, "account">): Promise<void> {
|
||||
const { account } = getLimiters();
|
||||
await account.reset(normalizeLoginRateLimitAccount(request.account));
|
||||
}
|
||||
|
||||
export async function resetLoginRateLimiterForTests(): Promise<void> {
|
||||
// Drop any cached limiter pair and best-effort drain any keys the
|
||||
// previous limiters wrote to the shared-store. Tests that need full
|
||||
// isolation can also inject a fresh store via
|
||||
// `__setLoginRateLimitStoreForTests`.
|
||||
const previous = limiters;
|
||||
limiters = null;
|
||||
if (previous) {
|
||||
try {
|
||||
for await (const fullKey of previous.store.adapter.scan(`shared-store:${previous.store.namespace}:rl:fixed:login-rate-limit:*`)) {
|
||||
// adapter keys are absolute (namespace already applied); strip the
|
||||
// namespace prefix when calling store.del which re-applies it.
|
||||
const prefix = `shared-store:${previous.store.namespace}:`;
|
||||
if (fullKey.startsWith(prefix)) {
|
||||
await previous.store.del(fullKey.slice(prefix.length));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort; isolated tests use the store seam instead.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Test seam: inject a SharedStore that backs the limiters. */
|
||||
export function __setLoginRateLimitStoreForTests(store: SharedStore): void {
|
||||
limiters = null;
|
||||
storeFactory = () => store;
|
||||
}
|
||||
|
||||
/** Test seam: revert to the default factory (real shared-store singleton). */
|
||||
export function __resetLoginRateLimitStoreForTests(): void {
|
||||
limiters = null;
|
||||
storeFactory = () => getSharedStore();
|
||||
}
|
||||
|
||||
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
|
||||
const forwardedFor = readHeader(request.headers, "x-forwarded-for");
|
||||
const forwardedClient = forwardedFor?.split(",")[0]?.trim();
|
||||
if (forwardedClient) {
|
||||
return forwardedClient;
|
||||
}
|
||||
|
||||
const realIp = readHeader(request.headers, "x-real-ip")?.trim();
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
const remoteAddress = request.remoteAddress?.trim();
|
||||
return remoteAddress || UNKNOWN_CLIENT_IP;
|
||||
}
|
||||
|
||||
export function createLoginRateLimitAccountFingerprint(account: unknown): string {
|
||||
const normalized = normalizeLoginRateLimitAccount(account);
|
||||
let hash = 0x811c9dc5;
|
||||
|
||||
for (let index = 0; index < normalized.length; index += 1) {
|
||||
hash ^= normalized.charCodeAt(index);
|
||||
hash = Math.imul(hash, 0x01000193) >>> 0;
|
||||
}
|
||||
|
||||
return `${FINGERPRINT_PREFIX}${hash.toString(16).padStart(8, "0")}`;
|
||||
}
|
||||
|
||||
function normalizeLoginRateLimitAccount(account: unknown): string {
|
||||
if (typeof account !== "string") {
|
||||
return UNKNOWN_ACCOUNT_KEY;
|
||||
}
|
||||
|
||||
const normalized = account.trim().toLowerCase();
|
||||
return normalized || UNKNOWN_ACCOUNT_KEY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Peek at the current counter and remaining TTL without incrementing.
|
||||
* The shared-store fixed-window helper only exposes `consume()` (which
|
||||
* always increments) and `reset()`, so we read the underlying key
|
||||
* directly to keep `checkLoginRateLimit` side-effect-free.
|
||||
*/
|
||||
async function readCounter(store: SharedStore, prefix: string, key: string): Promise<{ count: number; ttlSeconds: number }> {
|
||||
const suffix = `rl:fixed:${prefix}:${key}`;
|
||||
const raw = await store.get(suffix);
|
||||
const count = raw === null ? 0 : Number.parseInt(raw, 10) || 0;
|
||||
// The memory adapter does not expose a `ttl` helper, so derive a
|
||||
// best-effort retry window from the configured window length. Redis
|
||||
// counter TTL is enforced by the limiter on `consume`, so a fresh
|
||||
// request entering the window gets the full window-seconds back.
|
||||
const ttlSeconds = count > 0 ? LOGIN_RATE_LIMIT_WINDOW_SECONDS : 0;
|
||||
return { count, ttlSeconds };
|
||||
}
|
||||
|
||||
function readHeader(headers: LoginRateLimitRequest["headers"], name: string): string | undefined {
|
||||
if (!headers) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (headers instanceof Headers) {
|
||||
return headers.get(name) ?? undefined;
|
||||
}
|
||||
|
||||
const lowerName = name.toLowerCase();
|
||||
for (const [headerName, value] of Object.entries(headers)) {
|
||||
if (headerName.toLowerCase() !== lowerName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
Reference in new issue
Block a user