Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(api): add rate limiting and filtering for anon view notifications

Richie McIlroy530e728f5129
diff --git a/apps/web/app/api/analytics/track/route.ts b/apps/web/app/api/analytics/track/route.ts
index b1c1a27fc..5b6192b92 100644
--- a/apps/web/app/api/analytics/track/route.ts
+++ b/apps/web/app/api/analytics/track/route.ts
@@ -8,6 +8,40 @@ import { getAnonymousName } from "@/lib/anonymous-names";
import { createAnonymousViewNotification } from "@/lib/Notification";
import { runPromise } from "@/lib/server";
+const anonNotifRateLimit = new Map<
+ string,
+ { count: number; resetAt: number }
+>();
+const ANON_NOTIF_WINDOW_MS = 5 * 60 * 1000;
+const ANON_NOTIF_MAX_PER_VIDEO = 50;
+const ANON_NOTIF_MAX_ENTRIES = 10_000;
+let anonNotifCleanupCounter = 0;
+
+function checkAnonNotifRateLimit(videoId: string): boolean {
+ anonNotifCleanupCounter++;
+ if (anonNotifCleanupCounter % 100 === 0) {
+ const now = Date.now();
+ for (const [k, v] of anonNotifRateLimit) {
+ if (v.resetAt < now) anonNotifRateLimit.delete(k);
+ }
+ if (anonNotifRateLimit.size > ANON_NOTIF_MAX_ENTRIES)
+ anonNotifRateLimit.clear();
+ }
+
+ const now = Date.now();
+ const entry = anonNotifRateLimit.get(videoId);
+ if (!entry || entry.resetAt < now) {
+ anonNotifRateLimit.set(videoId, {
+ count: 1,
+ resetAt: now + ANON_NOTIF_WINDOW_MS,
+ });
+ return true;
+ }
+ if (entry.count >= ANON_NOTIF_MAX_PER_VIDEO) return false;
+ entry.count++;
+ return true;
+}
+
interface TrackPayload {
videoId: string;
orgId?: string | null;
@@ -103,7 +137,11 @@ export async function POST(request: NextRequest) {
},
]);
- if (!userId) {
+ if (
+ !userId &&
+ sessionId !== "anon" &&
+ checkAnonNotifRateLimit(body.videoId)
+ ) {
const anonName = getAnonymousName(sessionId);
const locationParts = [city, country].filter(Boolean);
const location =
@@ -116,7 +154,15 @@ export async function POST(request: NextRequest) {
anonName,
location,
}),
- ).pipe(Effect.catchAll(() => Effect.void));
+ ).pipe(
+ Effect.catchAll((error) => {
+ console.error(
+ "Failed to create anonymous view notification:",
+ error,
+ );
+ return Effect.void;
+ }),
+ );
}
}).pipe(provideOptionalAuth),
);