Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";
import { globalAuthCircuitBreaker, CircuitBreakerError } from "@/lib/circuit-breaker";
import { NextResponse } from "next/server";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
const wrappedHandler = async (req: Request, res: any) => {

Check failure on line 8 in app/api/auth/[...nextauth]/route.ts

View workflow job for this annotation

GitHub Actions / ci

Unexpected any. Specify a different type
try {
return await globalAuthCircuitBreaker.fire(() => handler(req, res));
} catch (error) {
if (error instanceof CircuitBreakerError) {
return new NextResponse("Service Unavailable - Authentication Provider Down", { status: 503 });
}
throw error;
}
};

export { wrappedHandler as GET, wrappedHandler as POST };
70 changes: 47 additions & 23 deletions app/api/links/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,14 @@

import { validateUrlBackend } from "@/lib/urlValidation";
import { PLATFORM_ICONS } from "@/lib/platformIcons";
import { rateLimit } from "@/lib/rateLimit";
import { invalidateProfileCache } from "@/lib/profileCache";
import { globalDbCircuitBreaker, CircuitBreakerError } from "@/lib/circuit-breaker";

// Maximum number of links a single user can add to their profile.
// Prevents unbounded database growth and degraded public profile performance.
const MAX_LINKS_PER_USER = 20;

// Rate limiter for link creation: 30 requests per minute per IP
const linksLimiter = rateLimit(30, 60_000);

export async function POST(req: NextRequest) {
// Apply IP‑based rate limiting first
const limited = await linksLimiter(req);
if (limited) return limited;

const session = await getServerSession(authOptions);

if (!session?.user?.email) {
Expand All @@ -37,9 +30,17 @@
const body = await req.json();
const isGroup = body?.isGroup === true;

const user = await prisma.user.findUnique({
where: { email: session.user.email },
});
let user;
try {
user = await globalDbCircuitBreaker.fire(() => prisma.user.findUnique({
where: { email: session.user.email },

Check failure on line 36 in app/api/links/route.ts

View workflow job for this annotation

GitHub Actions / ci

Type 'string | null | undefined' is not assignable to type 'string | undefined'.
}));
} catch (error) {
if (error instanceof CircuitBreakerError) {
return NextResponse.json({ error: "Service Unavailable - Database Down" }, { status: 503 });
}
throw error;
}

if (!user) {
return NextResponse.json(
Expand All @@ -59,7 +60,7 @@
}

try {
const link = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
const link = await globalDbCircuitBreaker.fire(async () => await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
const maxOrder = await tx.link.aggregate({
where: { userId: user.id, parentId: null },
_max: { position: true },
Expand All @@ -83,14 +84,17 @@
});
}, {
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
});
}), ["LINK_LIMIT_REACHED"]);

// New link is public — purge the cached public profile.
await invalidateProfileCache(user.id);

return NextResponse.json({ link: { ...link, children: [] } });
} catch (err: unknown) {
const error = err as { code?: string };
if (err instanceof CircuitBreakerError) {
return NextResponse.json({ error: "Service Unavailable - Database Down" }, { status: 503 });
}
if (error?.code === "LINK_LIMIT_REACHED") {
return NextResponse.json(
{ error: `You can add a maximum of ${MAX_LINKS_PER_USER} links.` },
Expand Down Expand Up @@ -190,7 +194,7 @@
const proposedRoute = customAlias || finalPlatform;

try {
const link = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
const link = await globalDbCircuitBreaker.fire(async () => await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
const existingLink = await tx.link.findFirst({
where: {
userId: user.id,
Expand Down Expand Up @@ -242,7 +246,7 @@
});
}, {
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
});
}), ["ROUTE_ALREADY_EXISTS", "INVALID_GROUP", "LINK_LIMIT_REACHED"]);

// New link is public — purge the cached public profile.
await invalidateProfileCache(user.id);
Expand All @@ -251,6 +255,10 @@
} catch (err: unknown) {
const error = err as { code?: string };

if (err instanceof CircuitBreakerError) {
return NextResponse.json({ error: "Service Unavailable - Database Down" }, { status: 503 });
}

if (error?.code === "ROUTE_ALREADY_EXISTS") {
return NextResponse.json(
{ error: `The route '/${proposedRoute}' is already in use. Please provide a unique custom alias.` },
Expand Down Expand Up @@ -295,16 +303,32 @@
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const user = await prisma.user.findUnique({ where: { email: session.user.email } });
let user;
try {
user = await globalDbCircuitBreaker.fire(() => prisma.user.findUnique({ where: { email: session.user.email } }));

Check failure on line 308 in app/api/links/route.ts

View workflow job for this annotation

GitHub Actions / ci

Type 'string | null | undefined' is not assignable to type 'string | undefined'.
} catch (error) {
if (error instanceof CircuitBreakerError) {
return NextResponse.json({ error: "Service Unavailable - Database Down" }, { status: 503 });
}
throw error;
}
if (!user) return NextResponse.json({ links: [] });

const allLinks = await prisma.link.findMany({
where: { userId: user.id },
orderBy: [
{ position: 'asc' },
{ createdAt: 'asc' }
],
});
let allLinks;
try {
allLinks = await globalDbCircuitBreaker.fire(() => prisma.link.findMany({
where: { userId: user.id },
orderBy: [
{ position: 'asc' },
{ createdAt: 'asc' }
],
}));
} catch (error) {
if (error instanceof CircuitBreakerError) {
return NextResponse.json({ error: "Service Unavailable - Database Down" }, { status: 503 });
}
throw error;
}

const links = nestLinks(allLinks);

Expand Down
70 changes: 70 additions & 0 deletions lib/circuit-breaker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
export class CircuitBreakerError extends Error {
constructor(message: string) {
super(message);
this.name = "CircuitBreakerError";
}
}

export enum CircuitState {
CLOSED,
OPEN,
HALF_OPEN,
}

export interface CircuitBreakerOptions {
failureThreshold?: number;
resetTimeout?: number;
}

export class CircuitBreaker {
private state: CircuitState = CircuitState.CLOSED;
private failureCount = 0;
private failureThreshold: number;
private resetTimeout: number;
private nextAttempt = 0;

constructor(options?: CircuitBreakerOptions) {
this.failureThreshold = options?.failureThreshold || 5;
this.resetTimeout = options?.resetTimeout || 30000; // 30 seconds
}

public async fire<T>(action: () => Promise<T>, ignoreErrors: string[] = []): Promise<T> {
if (this.state === CircuitState.OPEN) {
if (Date.now() > this.nextAttempt) {
this.state = CircuitState.HALF_OPEN;
} else {
throw new CircuitBreakerError("Circuit is OPEN. Service unavailable.");
}
}

try {
const result = await action();
this.onSuccess();
return result;
} catch (error: any) {

Check failure on line 44 in lib/circuit-breaker.ts

View workflow job for this annotation

GitHub Actions / ci

Unexpected any. Specify a different type
// Ignore business logic errors (don't trip the circuit breaker)
if (error?.code && ignoreErrors.includes(error.code)) {
throw error;
}
this.onFailure();
throw error;
}
}

private onSuccess(): void {
this.failureCount = 0;
this.state = CircuitState.CLOSED;
}

private onFailure(): void {
this.failureCount++;
if (this.failureCount >= this.failureThreshold) {
this.state = CircuitState.OPEN;
this.nextAttempt = Date.now() + this.resetTimeout;
}
}
}

// Global instances for shared state across the serverless instance
export const globalDbCircuitBreaker = new CircuitBreaker();
export const globalAuthCircuitBreaker = new CircuitBreaker();
45 changes: 45 additions & 0 deletions lib/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const hasRedis = process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN;
const redis = hasRedis ? Redis.fromEnv() : null;

// 5 login attempts per 15 minutes (Token Bucket)
export const authRateLimit = redis
? new Ratelimit({
redis,
limiter: Ratelimit.tokenBucket(5, "15 m", 5),
analytics: true,
prefix: "@upstash/ratelimit/auth",
})
: null;

// 30 API calls per minute (Token Bucket)
export const linksRateLimit = redis
? new Ratelimit({
redis,
limiter: Ratelimit.tokenBucket(30, "1 m", 30),
analytics: true,
prefix: "@upstash/ratelimit/links",
})
: null;

// 15 API calls per minute (Token Bucket)
export const usernameRateLimit = redis
? new Ratelimit({
redis,
limiter: Ratelimit.tokenBucket(15, "1 m", 15),
analytics: true,
prefix: "@upstash/ratelimit/username",
})
: null;

// In-memory fallback
const localFallbackMap = new Map<string, number>();
export function checkLocalRateLimit(ip: string, limit: number): boolean {
const key = `${ip}-${Math.floor(Date.now() / 60000)}`;
const current = localFallbackMap.get(key) || 0;
if (current >= limit) return false;
localFallbackMap.set(key, current + 1);
return true;
}
28 changes: 1 addition & 27 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,9 @@
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

import { authRateLimit, linksRateLimit, usernameRateLimit, checkLocalRateLimit } from "@/lib/rate-limit";
import { applyCsrfProtection } from "@/lib/middleware/csrf";

const hasRedis = process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN;
const redis = hasRedis ? Redis.fromEnv() : null;

const authRateLimit = redis
? new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(5, "1 m") })
: null;

const usernameRateLimit = redis
? new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(15, "1 m") })
: null;

const linksRateLimit = redis
? new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(30, "1 m") })
: null;

const localFallbackMap = new Map<string, number>();
function checkLocalRateLimit(ip: string, limit: number): boolean {
const key = `${ip}-${Math.floor(Date.now() / 60000)}`;
const current = localFallbackMap.get(key) || 0;
if (current >= limit) return false;
localFallbackMap.set(key, current + 1);
return true;
}

export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;

Expand Down
Loading