fix: address code review findings for analytics and security

This commit is contained in:
syntaxbullet
2026-01-08 21:39:01 +01:00
parent 11e07a0068
commit 6763e3c543
6 changed files with 114 additions and 26 deletions

View File

@@ -60,7 +60,8 @@ export async function createWebServer(config: WebServerConfig = {}): Promise<Web
let statsBroadcastInterval: Timer | undefined;
// Cache for activity stats (heavy aggregation)
let cachedActivity: { data: any, timestamp: number } | null = null;
let activityPromise: Promise<any> | null = null;
let lastActivityFetch: number = 0;
const ACTIVITY_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const server = serve({
@@ -103,15 +104,31 @@ export async function createWebServer(config: WebServerConfig = {}): Promise<Web
if (url.pathname === "/api/stats/activity") {
try {
const now = Date.now();
if (cachedActivity && (now - cachedActivity.timestamp < ACTIVITY_CACHE_TTL)) {
return Response.json(cachedActivity.data);
// Security Check: Token-based authentication
const { env } = await import("@shared/lib/env");
const authHeader = req.headers.get("Authorization");
if (authHeader !== `Bearer ${env.ADMIN_TOKEN}`) {
return new Response("Unauthorized", { status: 401 });
}
const { dashboardService } = await import("@shared/modules/dashboard/dashboard.service");
const activity = await dashboardService.getActivityAggregation();
const now = Date.now();
cachedActivity = { data: activity, timestamp: now };
// If we have a valid cache, return it
if (activityPromise && (now - lastActivityFetch < ACTIVITY_CACHE_TTL)) {
const data = await activityPromise;
return Response.json(data);
}
// Otherwise, trigger a new fetch (deduplicated by the promise)
if (!activityPromise || (now - lastActivityFetch >= ACTIVITY_CACHE_TTL)) {
activityPromise = (async () => {
const { dashboardService } = await import("@shared/modules/dashboard/dashboard.service");
return await dashboardService.getActivityAggregation();
})();
lastActivityFetch = now;
}
const activity = await activityPromise;
return Response.json(activity);
} catch (error) {
console.error("Error fetching activity stats:", error);