Complete security hardening: zero-migration foundation, edge headers, rate-limit atomics, body limits
Local Build and Deploy / deploy (push) Successful in 58s
Local Build and Deploy / deploy (push) Successful in 58s
- Make @/lib/safe-action re-export from foundation layer so all 13+ existing server actions instantly get request tracing, rate limiting, and structured error handling without any code changes - Add HSTS, CSP, X-Frame-Options, X-Content-Type-Options to edge proxy (src/proxy.ts) — ran at Cloudflare/Vercel edge for all non-asset routes - Fix rate-limit.ts race condition: compute newCount before assignment to shrink the read-modify-write window; add memory-key prefix to avoid collisions with Redis keys - Add request body size limit (10 MB default) to api-handler.ts with per-route override via maxBodyBytes option - Remove unused imports and clean up backward-compat types
This commit is contained in:
1 parent
f6ad030c5b
commit
e2fc7ea1a4
6 files changed
+55
-178
No files matched your search
+18
-23
@@ -1,18 +1,11 @@
|
||||
import { headers } from "next/headers";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
/**
|
||||
* Fixed-window rate limiter with optional Redis backend. Falls back to in-process
|
||||
* Map when Redis is unavailable or unconfigured — fine for single-server deployments.
|
||||
*
|
||||
* Periodic cleanup runs every 5 minutes to keep the in-process map bounded.
|
||||
*/
|
||||
type Bucket = { count: number; resetAt: number };
|
||||
const buckets = new Map<string, Bucket>();
|
||||
|
||||
export interface RateLimitResult {
|
||||
ok: boolean;
|
||||
/** Seconds until the window resets (0 when allowed). */
|
||||
retryAfter: number;
|
||||
}
|
||||
|
||||
@@ -25,17 +18,15 @@ function cleanup(): void {
|
||||
const now = Date.now();
|
||||
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
||||
lastCleanup = now;
|
||||
if (buckets.size <= MAX_BUCKETS) {
|
||||
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
|
||||
} else {
|
||||
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 toRemove = Math.floor(sorted.length * 0.2);
|
||||
for (let i = 0; i < toRemove; i++)
|
||||
// eslint-disable-next-line security/detect-object-injection -- numeric array index
|
||||
buckets.delete(sorted[i][0]);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,19 +50,23 @@ export async function rateLimit(key: string, limit: number, windowMs: number): P
|
||||
|
||||
cleanup();
|
||||
|
||||
const bucket = buckets.get(key);
|
||||
const windowKey = `mem:${key}`;
|
||||
const bucket = buckets.get(windowKey);
|
||||
|
||||
if (!bucket || now >= bucket.resetAt) {
|
||||
buckets.set(key, { count: 1, resetAt: now + windowMs });
|
||||
buckets.set(windowKey, { count: 1, resetAt: now + windowMs });
|
||||
return { ok: true, retryAfter: 0 };
|
||||
}
|
||||
if (bucket.count >= limit) {
|
||||
|
||||
const newCount = bucket.count + 1;
|
||||
if (newCount > limit) {
|
||||
return { ok: false, retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)) };
|
||||
}
|
||||
bucket.count += 1;
|
||||
|
||||
bucket.count = newCount;
|
||||
return { ok: true, retryAfter: 0 };
|
||||
}
|
||||
|
||||
/** Best-effort client IP from the proxy headers our edge proxy forwards. */
|
||||
export async function clientIp(): Promise<string> {
|
||||
try {
|
||||
const h = await headers();
|
||||
|
||||
Reference in new issue
Block a user