Gitea Actions Runner Test / test-job (push) Successful in 2s
CI / check (push) Successful in 28s
CI / tests-integration (push) Successful in 1m42s
CI / tests-unit (push) Failing after 1m45s
CI / tests-ui (push) Successful in 2m29s
CI / preflight (push) Skipped
CI / deploy (push) Skipped
Closes the four HIGH/MEDIUM items left open after the previous pass. Login lockout - The only login limits were keyed on the client IP, so a distributed attempt could grind on one account indefinitely. Added a per-account lockout with a budget of 8 failures per 15 minutes. - The bucket is keyed on the RESOLVED account id, not on the submitted string: users may sign in with either username or e-mail and neither the lookup nor the input normaliser folds case, so an input-keyed bucket would hand out a fresh budget per spelling of the same account. - precheckLogin and NextAuth's authorize share the bucket, so the pre-check cannot be used to buy extra attempts and a client that skips it entirely is still bounded. Both check the lockout BEFORE verifying the password: the success path clears the counter, which would otherwise walk a locked account straight back in on the right password. - A successful login clears the failures, which needs two new primitives in rate-limit.ts: peekRateLimit (read-only, does not consume a unit) and clearRateLimit. - Fixed a latent inconsistency while doing so: the in-process bucket capped its counter at the limit while Redis' INCR kept climbing, so the two backends disagreed about how far over the limit a key was. Both now track the true count. Mail lookup index - Added an index on users.mail (0035). Password reset, e-mail verification and the resend cooldown all resolve a single account from a submitted address and were full table scans of `users`. Deliberately non-unique: legacy rows can hold the same address more than once, so a unique index would fail to apply. Resend captcha - /verify's resend form triggers real outbound mail and was reachable with only a cooldown. It now runs the configured captcha before the account lookup and before any send. Client message payload - The root layout serialised the whole catalogue into every page. pages.admin and admin are ~177 KB of the ~235 KB and are unreachable from the public route group, so that layout now installs its own provider with the staff namespaces removed. Nested providers replace rather than merge, which is why this has to live in the segment layout. /admin, /mod, /client and /admin-next keep the full set; a guard test fails if a public page ever references a staff namespace.
174 lines
4.8 KiB
TypeScript
174 lines
4.8 KiB
TypeScript
import { headers } from "next/headers";
|
|
import { resolveClientIp, UNKNOWN_CLIENT_IP } from "@/lib/client-ip";
|
|
import { logger } from "@/lib/logger";
|
|
import { redis } from "@/lib/redis";
|
|
|
|
type Bucket = { count: number; resetAt: number };
|
|
const buckets = new Map<string, Bucket>();
|
|
|
|
export interface RateLimitResult {
|
|
ok: boolean;
|
|
retryAfter: number;
|
|
}
|
|
|
|
const CLEANUP_INTERVAL_MS = 300_000;
|
|
const MAX_BUCKETS = 10_000;
|
|
|
|
let lastCleanup = Date.now();
|
|
let redisFailWarned = false;
|
|
|
|
function cleanup(): void {
|
|
const now = Date.now();
|
|
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
|
lastCleanup = now;
|
|
|
|
for (const [k, b] of buckets) {
|
|
if (now >= b.resetAt) buckets.delete(k);
|
|
}
|
|
|
|
if (buckets.size > MAX_BUCKETS) {
|
|
const sorted = [...buckets.entries()].sort(
|
|
(a, b) => a[1].resetAt - b[1].resetAt,
|
|
);
|
|
const keysToRemove = sorted
|
|
.slice(0, Math.floor(sorted.length * 0.2))
|
|
.map((entry) => entry[0]);
|
|
for (const key of keysToRemove) buckets.delete(key);
|
|
}
|
|
}
|
|
|
|
export async function rateLimit(
|
|
key: string,
|
|
limit: number,
|
|
windowMs: number,
|
|
): Promise<RateLimitResult> {
|
|
const now = Date.now();
|
|
|
|
if (redis) {
|
|
try {
|
|
const windowKey = `ratelimit:${key}`;
|
|
// One atomic round trip: INCR + PEXPIRE in a single Lua call. Two
|
|
// separate commands left keys without a TTL whenever the process died
|
|
// in between, which permanently locked that client out.
|
|
const [current, ttl] = (await redis.eval(
|
|
`local c = redis.call('INCR', KEYS[1])
|
|
if c == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
|
local t = redis.call('PTTL', KEYS[1])
|
|
if t < 0 then t = tonumber(ARGV[1]) end
|
|
return {c, t}`,
|
|
1,
|
|
windowKey,
|
|
String(windowMs),
|
|
)) as [number, number];
|
|
if (current > limit) {
|
|
return { ok: false, retryAfter: Math.max(1, Math.ceil(ttl / 1000)) };
|
|
}
|
|
return { ok: true, retryAfter: 0 };
|
|
} catch {
|
|
// Redis unavailable — fall through to in-memory
|
|
if (process.env.NODE_ENV === "production" && !redisFailWarned) {
|
|
redisFailWarned = true;
|
|
logger.error(
|
|
"[rate-limit] Redis error — falling back to in-process buckets. Limits are not shared across instances until Redis recovers.",
|
|
);
|
|
}
|
|
}
|
|
} else if (redisFailWarned) {
|
|
redisFailWarned = false;
|
|
logger.info("[rate-limit] Redis available again — shared limits restored.");
|
|
}
|
|
|
|
cleanup();
|
|
|
|
const windowKey = `mem:${key}`;
|
|
const bucket = buckets.get(windowKey);
|
|
|
|
if (!bucket || now >= bucket.resetAt) {
|
|
buckets.set(windowKey, { count: 1, resetAt: now + windowMs });
|
|
return { ok: limit >= 1, retryAfter: 0 };
|
|
}
|
|
|
|
// The counter keeps climbing past the limit, matching Redis' INCR. Capping
|
|
// it here would make the two backends disagree about how far over the limit
|
|
// a key is, which breaks read-only consumers such as the login lockout.
|
|
const newCount = bucket.count + 1;
|
|
bucket.count = newCount;
|
|
if (newCount > limit) {
|
|
return {
|
|
ok: false,
|
|
retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)),
|
|
};
|
|
}
|
|
|
|
return { ok: true, retryAfter: 0 };
|
|
}
|
|
|
|
/**
|
|
* Read-only peek at a bucket — how it would judge the next call WITHOUT
|
|
* consuming a unit.
|
|
*
|
|
* The login lockout needs this: it has to know whether an account is already
|
|
* locked *before* the password is verified. Verifying first would clear the
|
|
* counter on the success path, handing a locked account a session the moment
|
|
* the right password turns up.
|
|
*/
|
|
export async function peekRateLimit(
|
|
key: string,
|
|
limit: number,
|
|
windowMs: number,
|
|
): Promise<RateLimitResult> {
|
|
if (redis) {
|
|
try {
|
|
const [countRaw, ttl] = (await redis.eval(
|
|
`local c = redis.call('GET', KEYS[1])
|
|
if not c then c = 0 end
|
|
local t = redis.call('PTTL', KEYS[1])
|
|
if t < 0 then t = tonumber(ARGV[1]) end
|
|
return {c, t}`,
|
|
1,
|
|
`ratelimit:${key}`,
|
|
String(windowMs),
|
|
)) as [string | null, number];
|
|
const count = Number(countRaw ?? 0);
|
|
return {
|
|
ok: count <= limit,
|
|
retryAfter: Math.max(1, Math.ceil(ttl / 1000)),
|
|
};
|
|
} catch {
|
|
// Redis unavailable — fall through to the in-process bucket.
|
|
}
|
|
}
|
|
|
|
const bucket = buckets.get(`mem:${key}`);
|
|
if (!bucket || Date.now() >= bucket.resetAt) {
|
|
return { ok: true, retryAfter: 0 };
|
|
}
|
|
return {
|
|
ok: bucket.count <= limit,
|
|
retryAfter: Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Drop a bucket entirely, both in Redis and in-process. Required wherever a
|
|
* successful action must reset a counter — a failed-attempt budget is only
|
|
* usable if a success clears it.
|
|
*/
|
|
export async function clearRateLimit(key: string): Promise<void> {
|
|
buckets.delete(`mem:${key}`);
|
|
if (!redis) return;
|
|
try {
|
|
await redis.del(`ratelimit:${key}`);
|
|
} catch {
|
|
// Best effort: a stale key only re-arms the lockout for its own TTL.
|
|
}
|
|
}
|
|
|
|
export async function clientIp(): Promise<string> {
|
|
try {
|
|
return resolveClientIp(await headers());
|
|
} catch {
|
|
return UNKNOWN_CLIENT_IP;
|
|
}
|
|
}
|