Files
e-tib.com/app/[locale]/errors/api/relay/route.ts

84 lines
2.8 KiB
TypeScript

import { NextResponse } from 'next/server';
import https from 'https';
const ALLOWED_HOSTS = ['glitchtip.infra.mintel.me', 'errors.infra.mintel.me'];
export async function POST(req: Request) {
try {
const rawText = await req.text();
const items = rawText.split('\n');
if (items.length === 0 || !items[0]) {
return NextResponse.json({ error: 'Empty payload' }, { status: 400 });
}
const header = JSON.parse(items[0]);
// Use the server's configured DSN (if available) to override the client's potentially fake DSN
// This allows the client to work without exposing NEXT_PUBLIC_SENTRY_DSN
const dsn = process.env.SENTRY_DSN || header.dsn;
if (!dsn) {
return NextResponse.json({ error: 'No DSN found' }, { status: 400 });
}
const url = new URL(dsn);
const projectId = url.pathname.replace('/', '');
const host = url.hostname;
if (!ALLOWED_HOSTS.includes(host)) {
return NextResponse.json({ error: 'Invalid Sentry Host' }, { status: 400 });
}
// Rewrite the DSN in the envelope header so Glitchtip doesn't reject the fake client DSN
if (process.env.SENTRY_DSN) {
header.dsn = process.env.SENTRY_DSN;
items[0] = JSON.stringify(header);
}
const sentryIngestUrl = `https://${host}/api/${projectId}/envelope/`;
const payloadToForward = items.join('\n');
return new Promise<NextResponse>((resolve) => {
const req = https.request(
sentryIngestUrl,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-sentry-envelope',
},
// Bypass self-signed cert error since glitchtip.infra.mintel.me uses an internal CA
// that the Next.js docker container doesn't trust by default.
rejectUnauthorized: false,
},
(res) => {
res.on('data', () => {
// Consume data to free up memory
});
res.on('end', () => {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
resolve(NextResponse.json({ success: true }));
} else {
resolve(
NextResponse.json(
{ error: `Relay rejected (${res.statusCode})` },
{ status: res.statusCode || 500 }
)
);
}
});
}
);
req.on('error', (err) => {
console.error('[Sentry Tunnel] https.request failed', err);
resolve(NextResponse.json({ error: 'Relay failed' }, { status: 500 }));
});
req.write(payloadToForward);
req.end();
});
} catch (e) {
console.error("[Sentry Tunnel] Failed to parse or relay body", e);
return NextResponse.json({ error: 'Relay failed' }, { status: 500 });
}
}