Skip to content
Merged
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
9 changes: 9 additions & 0 deletions app/app/api/analytics/events/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { prisma } from "@/lib/prisma";
import { apiSuccess, apiError } from "@/lib/api-response";
import { readJsonBody } from "@/lib/parse-json-body";
import { auth } from "@/lib/auth";
import { checkRateLimit } from "@/lib/rate-limit";

const VALID_EVENTS = [
"page_view",
Expand All @@ -15,6 +16,14 @@ const VALID_EVENTS = [

export async function POST(request: NextRequest) {
try {
// Rate limit: 60 events per minute per IP
const ip =
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
"unknown";
if (!checkRateLimit(`analytics:${ip}`, 60, 60_000)) {
return apiError("Too many requests", 429);
}

const parsed = await readJsonBody<Record<string, unknown>>(request);
if (!parsed.ok) return parsed.response;

Expand Down
26 changes: 21 additions & 5 deletions app/components/post-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export function PostCard({ post }: PostCardProps) {
const [showEntryForm, setShowEntryForm] = useState(false);
const [showContributionForm, setShowContributionForm] = useState(false);
const [isBurned, setIsBurned] = useState(false);
const [burnCount, setBurnCount] = useState(post.burnCount);

const handleAuthRequiredAction = (action: () => void) => {
if (!user) {
Expand All @@ -53,10 +54,25 @@ export function PostCard({ post }: PostCardProps) {

const handleBurn = (e: React.MouseEvent) => {
e.stopPropagation();
handleAuthRequiredAction(() => {
if (!isBurned) {
burnPost(post.id);
setIsBurned(true);
handleAuthRequiredAction(async () => {
if (isBurned) return;
// Optimistic update
setIsBurned(true);
setBurnCount((c) => c + 1);
burnPost(post.id);
try {
const res = await fetch(`/api/posts/${post.id}/burn`, { method: 'POST' });
if (res.ok) {
const data = await res.json();
if (data?.data?.count !== undefined) setBurnCount(data.data.count);
} else {
// Rollback on failure
setIsBurned(false);
setBurnCount((c) => c - 1);
}
} catch {
setIsBurned(false);
setBurnCount((c) => c - 1);
}
});
};
Expand Down Expand Up @@ -384,7 +400,7 @@ export function PostCard({ post }: PostCardProps) {
className={`w-4 h-4 ${isBurned ? 'fill-current' : ''}`}
/>
<span className="text-sm font-medium">
{post.burnCount + (isBurned ? 1 : 0)}
{burnCount}
</span>
</Button>

Expand Down
29 changes: 29 additions & 0 deletions app/lib/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interface RateLimitEntry {
count: number;
resetAt: number;
}

const store = new Map<string, RateLimitEntry>();

/**
* Simple in-memory token-bucket rate limiter.
* Returns true when the request is allowed, false when the limit is exceeded.
*/
export function checkRateLimit(
key: string,
limit: number,
windowMs: number,
): boolean {
const now = Date.now();
const entry = store.get(key);

if (!entry || now >= entry.resetAt) {
store.set(key, { count: 1, resetAt: now + windowMs });
return true;
}

if (entry.count >= limit) return false;

entry.count += 1;
return true;
}
Loading