Ratelimit
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registerCustomer } from "@/lib/zitadel";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import type { RegistrationInput } from "@/types";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -11,7 +12,34 @@ const registrationSchema = z.object({
|
||||
preferredLanguage: z.enum(["en", "de", "fr", "it"]).optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
/** 3 registrations per IP per hour */
|
||||
const RATE_LIMIT = 3;
|
||||
const RATE_WINDOW_MS = 3_600_000; // 1 hour
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
// --- Rate limiting ---
|
||||
const ip =
|
||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
||||
request.headers.get("x-real-ip") ??
|
||||
"unknown";
|
||||
|
||||
const rl = rateLimit(`register:${ip}`, RATE_LIMIT, RATE_WINDOW_MS);
|
||||
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many registration attempts. Please try again later." },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Retry-After": String(Math.ceil(rl.resetMs / 1000)),
|
||||
"X-RateLimit-Limit": String(RATE_LIMIT),
|
||||
"X-RateLimit-Remaining": "0",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// --- Validation ---
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = registrationSchema.safeParse(body);
|
||||
@@ -19,7 +47,7 @@ export async function POST(request: Request) {
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validation failed", details: parsed.error.flatten() },
|
||||
{ status: 400 }
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,9 +65,16 @@ export async function POST(request: Request) {
|
||||
{
|
||||
orgId: result.orgId,
|
||||
userId: result.userId,
|
||||
message: "Registration successful. You will receive an invitation email to set your password.",
|
||||
message:
|
||||
"Registration successful. You will receive an invitation email to set your password.",
|
||||
},
|
||||
{
|
||||
status: 201,
|
||||
headers: {
|
||||
"X-RateLimit-Limit": String(RATE_LIMIT),
|
||||
"X-RateLimit-Remaining": String(rl.remaining),
|
||||
},
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (e: any) {
|
||||
console.error("Registration failed:", e);
|
||||
@@ -48,14 +83,14 @@ export async function POST(request: Request) {
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: zitadelMessage || "Registration failed. Please try again." },
|
||||
{ status: e.statusCode || 500 }
|
||||
{ status: e.statusCode || 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ZITADEL errors come as:
|
||||
* "ZITADEL POST /path: 400 {"code":3, "message":"..."}"
|
||||
* "ZITADEL POST /path: 400 {"code":3, "message":"..."}"
|
||||
* Extract the human-readable "message" field.
|
||||
*/
|
||||
function extractZitadelMessage(errorMsg: string): string | null {
|
||||
|
||||
71
src/lib/rate-limit.ts
Normal file
71
src/lib/rate-limit.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* In-memory sliding-window rate limiter.
|
||||
*
|
||||
* Suitable for single-node deployments (pilot scale).
|
||||
* For multi-replica, replace with Redis-backed store.
|
||||
*/
|
||||
|
||||
interface RateLimitEntry {
|
||||
timestamps: number[];
|
||||
}
|
||||
|
||||
const store = new Map<string, RateLimitEntry>();
|
||||
|
||||
// Cleanup stale entries every 10 minutes
|
||||
if (typeof globalThis !== "undefined") {
|
||||
// Use globalThis to survive HMR in dev — only one interval
|
||||
const key = "__rateLimitCleanup";
|
||||
if (!(globalThis as any)[key]) {
|
||||
(globalThis as any)[key] = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [k, entry] of store) {
|
||||
entry.timestamps = entry.timestamps.filter((t) => now - t < 3_600_000);
|
||||
if (entry.timestamps.length === 0) store.delete(k);
|
||||
}
|
||||
}, 600_000);
|
||||
}
|
||||
}
|
||||
|
||||
export interface RateLimitResult {
|
||||
allowed: boolean;
|
||||
remaining: number;
|
||||
/** Milliseconds until the oldest request in the window expires */
|
||||
resetMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check and record a rate-limited action.
|
||||
*
|
||||
* @param key - Unique key, e.g. `register:${ip}`
|
||||
* @param limit - Max allowed actions in the window
|
||||
* @param windowMs - Window size in milliseconds
|
||||
*/
|
||||
export function rateLimit(
|
||||
key: string,
|
||||
limit: number,
|
||||
windowMs: number,
|
||||
): RateLimitResult {
|
||||
const now = Date.now();
|
||||
const entry = store.get(key) ?? { timestamps: [] };
|
||||
|
||||
// Prune expired timestamps
|
||||
entry.timestamps = entry.timestamps.filter((t) => now - t < windowMs);
|
||||
|
||||
if (entry.timestamps.length >= limit) {
|
||||
const oldest = entry.timestamps[0];
|
||||
return {
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
resetMs: oldest + windowMs - now,
|
||||
};
|
||||
}
|
||||
|
||||
entry.timestamps.push(now);
|
||||
store.set(key, entry);
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
remaining: limit - entry.timestamps.length,
|
||||
resetMs: entry.timestamps[0] + windowMs - now,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user