Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

2.7 KB
Raw Blame
import type { BetterAuthOptions } from "better-auth";
import { getCoordination } from "@reactive-resume/db/coordination";
import { getRedis, redisKey } from "@reactive-resume/db/redis";

// Match Better Auth's rolling inactivity window: only accepted requests extend it.
const consumeScript = `
local count = tonumber(redis.call('GET', KEYS[1]) or '0')
if count >= tonumber(ARGV[2]) then
  return {0, math.max(1, math.ceil(redis.call('PTTL', KEYS[1]) / 1000))}
end
redis.call('INCR', KEYS[1])
redis.call('PEXPIRE', KEYS[1], ARGV[1])
return {1, 0}
`;

const redis = getRedis();

// Per-instance fallback while Redis is unreachable: login stays available and still rate limited.
const localCounts = new Map<string, { count: number; expiresAt: number }>();
let nextSweepAt = 0;

function consumeLocally(key: string, rule: { window: number; max: number }) {
	const now = Date.now();
	const entry = localCounts.get(key);
	const active = entry && entry.expiresAt > now ? entry : undefined;
	if (active && active.count >= rule.max) {
		return { allowed: false, retryAfter: Math.max(1, Math.ceil((active.expiresAt - now) / 1000)) };
	}
	if (!entry && localCounts.size >= 10_000) {
		if (now >= nextSweepAt) {
			for (const [candidate, counter] of localCounts) if (counter.expiresAt <= now) localCounts.delete(candidate);
			nextSweepAt = now + 1_000;
		}
		// Saturation must never erase an active login limit.
		if (localCounts.size >= 10_000) return { allowed: false, retryAfter: 1 };
	}
	localCounts.set(key, { count: (active?.count ?? 0) + 1, expiresAt: now + rule.window * 1_000 });
	return { allowed: true, retryAfter: null };
}

export const authRateLimitStorage: NonNullable<BetterAuthOptions["rateLimit"]>["customStorage"] =
	redis || process.env.CLOUDFLARE === "1"
		? {
				async consume(key, rule) {
					const service = getCoordination();
					if (service) {
						const result = await service.consume(redisKey("auth", key), {
							window: rule.window * 1_000,
							max: rule.max,
							rolling: true,
						});
						return {
							allowed: result.allowed,
							retryAfter: result.allowed ? null : Math.max(1, Math.ceil((result.reset - Date.now()) / 1_000)),
						};
					}
					if (!redis) throw new Error("Cloudflare auth coordination is not configured");
					try {
						const result = await redis.eval(consumeScript, 1, redisKey("auth", key), rule.window * 1_000, rule.max);
						if (!Array.isArray(result) || result.length !== 2) throw new Error("Invalid rate limit result");
						return { allowed: result[0] === 1, retryAfter: result[0] === 1 ? null : Number(result[1]) };
					} catch (error) {
						console.error("[auth] Redis rate limit unavailable; using per-instance limits", error);
						return consumeLocally(key, rule);
					}
				},
			}
		: undefined;