security: P1/P2 hardening — rate limiting, CORS, Redis auth, network isolation
- Add Redis-based sliding window rate limiting on login, register, forgot-password, reset-password - Fix user enumeration: register returns generic 200 for both new and existing emails - Add Redis authentication (requirepass) and password in .env - Docker network isolation: postgres/redis on internal-only network - Whitelist Stripe redirect origins (prevent open redirect) - Add 10MB request size limit on trace ingestion - Limit API keys to 10 per user - Add CORS headers via middleware (whitelist agentlens.vectry.tech + localhost) - Reduce JWT max age from 30 days to 7 days
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
"@dagrejs/dagre": "^2.0.4",
|
||||
"@xyflow/react": "^12.10.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"ioredis": "^5.9.2",
|
||||
"lucide-react": "^0.469.0",
|
||||
"next": "^15.1.0",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
|
||||
@@ -44,6 +44,13 @@ export default function RegisterPage() {
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.status === 429) {
|
||||
const data: { error?: string } = await res.json();
|
||||
setError(data.error ?? "Too many attempts. Please try again later.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const data: { error?: string } = await res.json();
|
||||
setError(data.error ?? "Registration failed");
|
||||
@@ -58,8 +65,7 @@ export default function RegisterPage() {
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
setError("Account created but sign-in failed. Please log in manually.");
|
||||
setLoading(false);
|
||||
router.push("/login");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { randomBytes, createHash } from "crypto";
|
||||
import { z } from "zod";
|
||||
import nodemailer from "nodemailer";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { checkRateLimit, AUTH_RATE_LIMITS } from "@/lib/rate-limit";
|
||||
|
||||
const forgotPasswordSchema = z.object({
|
||||
email: z.email("Invalid email address"),
|
||||
@@ -24,6 +25,15 @@ function hashToken(token: string): string {
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
|
||||
const rl = await checkRateLimit(`forgot:${ip}`, AUTH_RATE_LIMITS.forgotPassword);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many requests. Please try again later." },
|
||||
{ status: 429, headers: { "Retry-After": String(Math.ceil((rl.resetAt - Date.now()) / 1000)) } }
|
||||
);
|
||||
}
|
||||
|
||||
const body: unknown = await request.json();
|
||||
const parsed = forgotPasswordSchema.safeParse(body);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import crypto from "crypto";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendEmail } from "@/lib/email";
|
||||
import { checkRateLimit, AUTH_RATE_LIMITS } from "@/lib/rate-limit";
|
||||
|
||||
const registerSchema = z.object({
|
||||
email: z.email("Invalid email address"),
|
||||
@@ -13,6 +14,15 @@ const registerSchema = z.object({
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
|
||||
const rl = await checkRateLimit(`register:${ip}`, AUTH_RATE_LIMITS.register);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many registration attempts. Please try again later." },
|
||||
{ status: 429, headers: { "Retry-After": String(Math.ceil((rl.resetAt - Date.now()) / 1000)) } }
|
||||
);
|
||||
}
|
||||
|
||||
const body: unknown = await request.json();
|
||||
const parsed = registerSchema.safeParse(body);
|
||||
|
||||
@@ -32,8 +42,8 @@ export async function POST(request: Request) {
|
||||
|
||||
if (existing) {
|
||||
return NextResponse.json(
|
||||
{ error: "An account with this email already exists" },
|
||||
{ status: 409 }
|
||||
{ message: "If this email is available, a confirmation email will be sent." },
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,7 +69,6 @@ export async function POST(request: Request) {
|
||||
},
|
||||
});
|
||||
|
||||
// Send verification email (non-blocking — don't fail registration on email errors)
|
||||
try {
|
||||
const rawToken = crypto.randomBytes(32).toString("hex");
|
||||
const tokenHash = crypto
|
||||
@@ -71,7 +80,7 @@ export async function POST(request: Request) {
|
||||
data: {
|
||||
userId: user.id,
|
||||
token: tokenHash,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -98,7 +107,10 @@ export async function POST(request: Request) {
|
||||
console.error("[register] Failed to send verification email:", emailError);
|
||||
}
|
||||
|
||||
return NextResponse.json(user, { status: 201 });
|
||||
return NextResponse.json(
|
||||
{ message: "If this email is available, a confirmation email will be sent." },
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { createHash } from "crypto";
|
||||
import { hash } from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { checkRateLimit, AUTH_RATE_LIMITS } from "@/lib/rate-limit";
|
||||
|
||||
const resetPasswordSchema = z.object({
|
||||
token: z.string().min(1, "Token is required"),
|
||||
@@ -15,6 +16,15 @@ function hashToken(token: string): string {
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
|
||||
const rl = await checkRateLimit(`reset:${ip}`, AUTH_RATE_LIMITS.resetPassword);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many attempts. Please try again later." },
|
||||
{ status: 429, headers: { "Retry-After": String(Math.ceil((rl.resetAt - Date.now()) / 1000)) } }
|
||||
);
|
||||
}
|
||||
|
||||
const body: unknown = await request.json();
|
||||
const parsed = resetPasswordSchema.safeParse(body);
|
||||
|
||||
|
||||
@@ -37,6 +37,17 @@ export async function POST(request: Request) {
|
||||
if (!session?.user?.id)
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const MAX_KEYS_PER_USER = 10;
|
||||
const keyCount = await prisma.apiKey.count({
|
||||
where: { userId: session.user.id, revoked: false },
|
||||
});
|
||||
if (keyCount >= MAX_KEYS_PER_USER) {
|
||||
return NextResponse.json(
|
||||
{ error: `Maximum of ${MAX_KEYS_PER_USER} API keys allowed. Revoke an existing key first.` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const name =
|
||||
typeof body.name === "string" && body.name.trim()
|
||||
|
||||
@@ -72,8 +72,14 @@ export async function POST(request: Request) {
|
||||
}
|
||||
}
|
||||
|
||||
const origin =
|
||||
request.headers.get("origin") ?? "https://agentlens.vectry.tech";
|
||||
const ALLOWED_ORIGINS = [
|
||||
"https://agentlens.vectry.tech",
|
||||
"http://localhost:3000",
|
||||
];
|
||||
const requestOrigin = request.headers.get("origin");
|
||||
const origin = ALLOWED_ORIGINS.includes(requestOrigin ?? "")
|
||||
? requestOrigin!
|
||||
: "https://agentlens.vectry.tech";
|
||||
|
||||
const checkoutSession = await getStripe().checkout.sessions.create({
|
||||
customer: stripeCustomerId,
|
||||
|
||||
@@ -22,8 +22,14 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
const origin =
|
||||
request.headers.get("origin") ?? "https://agentlens.vectry.tech";
|
||||
const ALLOWED_ORIGINS = [
|
||||
"https://agentlens.vectry.tech",
|
||||
"http://localhost:3000",
|
||||
];
|
||||
const requestOrigin = request.headers.get("origin");
|
||||
const origin = ALLOWED_ORIGINS.includes(requestOrigin ?? "")
|
||||
? requestOrigin!
|
||||
: "https://agentlens.vectry.tech";
|
||||
|
||||
const portalSession = await getStripe().billingPortal.sessions.create({
|
||||
customer: subscription.stripeCustomerId,
|
||||
|
||||
@@ -92,6 +92,12 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: "Missing or invalid Authorization header" }, { status: 401 });
|
||||
}
|
||||
|
||||
const contentLength = parseInt(request.headers.get("content-length") ?? "0", 10);
|
||||
const MAX_BODY_SIZE = 10 * 1024 * 1024;
|
||||
if (contentLength > MAX_BODY_SIZE) {
|
||||
return NextResponse.json({ error: "Request body too large (max 10MB)" }, { status: 413 });
|
||||
}
|
||||
|
||||
const rawApiKey = authHeader.slice(7);
|
||||
if (!rawApiKey) {
|
||||
return NextResponse.json({ error: "Missing API key in Authorization header" }, { status: 401 });
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { NextAuthConfig } from "next-auth";
|
||||
|
||||
export default {
|
||||
providers: [],
|
||||
session: { strategy: "jwt" },
|
||||
session: { strategy: "jwt", maxAge: 7 * 24 * 60 * 60 },
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ import Credentials from "next-auth/providers/credentials";
|
||||
import { compare } from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { checkRateLimit, AUTH_RATE_LIMITS } from "@/lib/rate-limit";
|
||||
import authConfig from "./auth.config";
|
||||
|
||||
declare module "next-auth" {
|
||||
@@ -37,11 +38,17 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
async authorize(credentials, request) {
|
||||
const parsed = loginSchema.safeParse(credentials);
|
||||
if (!parsed.success) return null;
|
||||
|
||||
const { email, password } = parsed.data;
|
||||
const ip = (request instanceof Request
|
||||
? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
|
||||
: undefined) ?? "unknown";
|
||||
|
||||
const rl = await checkRateLimit(`login:${ip}`, AUTH_RATE_LIMITS.login);
|
||||
if (!rl.allowed) return null;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: email.toLowerCase() },
|
||||
|
||||
52
apps/web/src/lib/rate-limit.ts
Normal file
52
apps/web/src/lib/rate-limit.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { redis } from "./redis";
|
||||
|
||||
interface RateLimitConfig {
|
||||
windowMs: number;
|
||||
maxAttempts: number;
|
||||
}
|
||||
|
||||
interface RateLimitResult {
|
||||
allowed: boolean;
|
||||
remaining: number;
|
||||
resetAt: number;
|
||||
}
|
||||
|
||||
export async function checkRateLimit(
|
||||
key: string,
|
||||
config: RateLimitConfig
|
||||
): Promise<RateLimitResult> {
|
||||
const now = Date.now();
|
||||
const windowStart = now - config.windowMs;
|
||||
const redisKey = `rl:${key}`;
|
||||
|
||||
try {
|
||||
await redis.zremrangebyscore(redisKey, 0, windowStart);
|
||||
const count = await redis.zcard(redisKey);
|
||||
|
||||
if (count >= config.maxAttempts) {
|
||||
const oldestEntry = await redis.zrange(redisKey, 0, 0, "WITHSCORES");
|
||||
const resetAt = oldestEntry.length >= 2
|
||||
? parseInt(oldestEntry[1], 10) + config.windowMs
|
||||
: now + config.windowMs;
|
||||
return { allowed: false, remaining: 0, resetAt };
|
||||
}
|
||||
|
||||
await redis.zadd(redisKey, now, `${now}:${Math.random()}`);
|
||||
await redis.pexpire(redisKey, config.windowMs);
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
remaining: config.maxAttempts - count - 1,
|
||||
resetAt: now + config.windowMs,
|
||||
};
|
||||
} catch {
|
||||
return { allowed: true, remaining: config.maxAttempts, resetAt: now + config.windowMs };
|
||||
}
|
||||
}
|
||||
|
||||
export const AUTH_RATE_LIMITS = {
|
||||
login: { windowMs: 15 * 60 * 1000, maxAttempts: 10 },
|
||||
register: { windowMs: 60 * 60 * 1000, maxAttempts: 5 },
|
||||
forgotPassword: { windowMs: 60 * 60 * 1000, maxAttempts: 5 },
|
||||
resetPassword: { windowMs: 15 * 60 * 1000, maxAttempts: 5 },
|
||||
} as const;
|
||||
14
apps/web/src/lib/redis.ts
Normal file
14
apps/web/src/lib/redis.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import Redis from "ioredis";
|
||||
|
||||
const globalForRedis = globalThis as unknown as { redis?: Redis };
|
||||
|
||||
export const redis =
|
||||
globalForRedis.redis ??
|
||||
new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", {
|
||||
maxRetriesPerRequest: 3,
|
||||
lazyConnect: true,
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalForRedis.redis = redis;
|
||||
}
|
||||
@@ -10,6 +10,10 @@ const publicPaths = [
|
||||
"/api/auth",
|
||||
"/api/traces",
|
||||
"/api/health",
|
||||
"/api/stripe/webhook",
|
||||
"/forgot-password",
|
||||
"/reset-password",
|
||||
"/verify-email",
|
||||
];
|
||||
|
||||
function isPublicPath(pathname: string): boolean {
|
||||
@@ -18,31 +22,64 @@ function isPublicPath(pathname: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
const ALLOWED_ORIGINS = new Set([
|
||||
"https://agentlens.vectry.tech",
|
||||
"http://localhost:3000",
|
||||
]);
|
||||
|
||||
function corsHeaders(origin: string | null): Record<string, string> {
|
||||
const allowedOrigin = origin && ALLOWED_ORIGINS.has(origin)
|
||||
? origin
|
||||
: "https://agentlens.vectry.tech";
|
||||
return {
|
||||
"Access-Control-Allow-Origin": allowedOrigin,
|
||||
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
"Access-Control-Max-Age": "86400",
|
||||
};
|
||||
}
|
||||
|
||||
export default auth((req) => {
|
||||
const { pathname } = req.nextUrl;
|
||||
const isLoggedIn = !!req.auth;
|
||||
const origin = req.headers.get("origin");
|
||||
|
||||
if (isPublicPath(pathname)) {
|
||||
if (isLoggedIn && (pathname === "/login" || pathname === "/register")) {
|
||||
return NextResponse.redirect(new URL("/dashboard", req.nextUrl.origin));
|
||||
if (req.method === "OPTIONS") {
|
||||
return new NextResponse(null, { status: 204, headers: corsHeaders(origin) });
|
||||
}
|
||||
|
||||
const response = (() => {
|
||||
if (isPublicPath(pathname)) {
|
||||
if (isLoggedIn && (pathname === "/login" || pathname === "/register")) {
|
||||
return NextResponse.redirect(new URL("/dashboard", req.nextUrl.origin));
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (pathname === "/login" || pathname === "/register") {
|
||||
if (isLoggedIn) {
|
||||
return NextResponse.redirect(new URL("/dashboard", req.nextUrl.origin));
|
||||
if (pathname === "/login" || pathname === "/register") {
|
||||
if (isLoggedIn) {
|
||||
return NextResponse.redirect(new URL("/dashboard", req.nextUrl.origin));
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/dashboard") && !isLoggedIn) {
|
||||
const loginUrl = new URL("/login", req.nextUrl.origin);
|
||||
loginUrl.searchParams.set("callbackUrl", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
})();
|
||||
|
||||
if (pathname.startsWith("/api/")) {
|
||||
const headers = corsHeaders(origin);
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
response.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/dashboard") && !isLoggedIn) {
|
||||
const loginUrl = new URL("/login", req.nextUrl.origin);
|
||||
loginUrl.searchParams.set("callbackUrl", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
return response;
|
||||
});
|
||||
|
||||
export const config = {
|
||||
|
||||
Reference in New Issue
Block a user