Files
Webserver/app/api/analytics/route.ts

101 lines
3.1 KiB
TypeScript
Raw Normal View History

2026-02-08 14:05:15 -05:00
import { NextResponse } from 'next/server';
import { logVisit } from '@/lib/db';
2026-05-25 09:49:40 -04:00
import {
getClientAddress,
getUserAgent,
isSameOriginRequest,
normalizeVisitPath,
} from '@/lib/request';
2026-02-08 14:05:15 -05:00
2026-05-25 09:49:40 -04:00
export const runtime = 'nodejs';
const MAX_BODY_BYTES = 4096;
function getAdminRelayUrl() {
const adminUrl = process.env.ADMIN_DASH_URL;
if (!adminUrl) return null;
try {
const url = new URL(adminUrl);
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
return url.toString();
} catch {
return null;
}
}
function relayVisit(path: string, visitorId: string | null) {
const adminUrl = getAdminRelayUrl();
if (!adminUrl) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (process.env.ADMIN_DASH_KEY) {
headers.Authorization = `Bearer ${process.env.ADMIN_DASH_KEY}`;
}
fetch(adminUrl, {
method: 'POST',
body: JSON.stringify({ path, visitorId, timestamp: Date.now() }),
headers,
signal: AbortSignal.timeout(1500),
}).catch((error) => {
if (process.env.NODE_ENV !== 'production') {
console.error('Analytics relay failed', error);
}
});
}
2026-02-08 23:18:21 -05:00
2026-02-08 14:05:15 -05:00
export async function POST(req: Request) {
try {
2026-05-25 09:49:40 -04:00
if (!isSameOriginRequest(req)) {
return NextResponse.json({ success: false, error: 'Forbidden' }, { status: 403 });
}
const contentType = req.headers.get('content-type') || '';
if (!contentType.toLowerCase().includes('application/json')) {
return NextResponse.json({ success: false, error: 'Unsupported media type' }, { status: 415 });
}
const contentLength = Number(req.headers.get('content-length') || 0);
if (contentLength > MAX_BODY_BYTES) {
return NextResponse.json({ success: false, error: 'Payload too large' }, { status: 413 });
2026-02-08 23:18:21 -05:00
}
2026-05-25 09:49:40 -04:00
const rawBody = await req.text();
if (Buffer.byteLength(rawBody, 'utf8') > MAX_BODY_BYTES) {
return NextResponse.json({ success: false, error: 'Payload too large' }, { status: 413 });
}
const body = JSON.parse(rawBody);
if (!body || typeof body !== 'object' || Array.isArray(body)) {
return NextResponse.json({ success: false, error: 'Invalid input' }, { status: 400 });
}
const visitPath = normalizeVisitPath(body.path);
2026-02-08 14:05:15 -05:00
2026-05-25 09:49:40 -04:00
if (!visitPath) {
2026-02-08 23:18:21 -05:00
return NextResponse.json({ success: false, error: 'Invalid input' }, { status: 400 });
}
const headers = req.headers;
2026-05-25 09:49:40 -04:00
const clientAddress = getClientAddress(headers);
const userAgent = getUserAgent(headers);
let visitorId: string | null = null;
2026-02-08 14:05:15 -05:00
try {
2026-05-25 09:49:40 -04:00
visitorId = logVisit(clientAddress, userAgent, visitPath);
} catch (e) {
console.error('Failed to log visit to SQLite', e);
}
2026-05-25 09:49:40 -04:00
relayVisit(visitPath, visitorId);
2026-02-08 14:05:15 -05:00
return NextResponse.json({ success: true });
2026-02-08 23:18:21 -05:00
} catch {
return NextResponse.json({ success: false, error: 'Bad request' }, { status: 400 });
2026-02-08 14:05:15 -05:00
}
}