fix: previews Meta vía proxy y creatividades Google PMax/RSA

Las imágenes Meta dejan de romperse en el navegador; Google trae assets en vivo.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-09-23 18:25:48 +02:00
parent 86225a701e
commit d05df8c371
5 changed files with 697 additions and 57 deletions

View File

@@ -0,0 +1,81 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
export const dynamic = 'force-dynamic';
/** CDN prefixes safe to proxy for Ad Tracker previews. */
const ALLOWED = [
'https://scontent.',
'https://external.',
'https://facebook.com/',
'https://www.facebook.com/',
'https://fbcdn.net/',
'https://scontent.xx.fbcdn.net/',
'https://tpc.googlesyndication.com/',
'https://lh3.googleusercontent.com/',
'https://i.ytimg.com/',
'https://img.youtube.com/',
];
function allowed(url: string): boolean {
if (!url.startsWith('https://')) return false;
if (ALLOWED.some((p) => url.startsWith(p))) return true;
// Meta CDN hosts vary by region: scontent.fmad19-2.fna.fbcdn.net
try {
const host = new URL(url).hostname;
return (
host.endsWith('.fbcdn.net') ||
host.endsWith('.facebook.com') ||
host.endsWith('.googleusercontent.com') ||
host.endsWith('.googlesyndication.com') ||
host === 'i.ytimg.com' ||
host === 'img.youtube.com'
);
} catch {
return false;
}
}
/**
* GET /api/ad-tracker/media?url=…
* Proxies Meta/Google creative images so the browser always gets a same-origin preview.
*/
export async function GET(req: NextRequest) {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
}
const url = req.nextUrl.searchParams.get('url') || '';
if (!allowed(url)) {
return NextResponse.json({ error: 'url_not_allowed' }, { status: 400 });
}
try {
const res = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (compatible; 4VenturesAdTracker/1.0; +https://app.4ventures.es)',
Accept: 'image/*,*/*;q=0.8',
},
cache: 'force-cache',
next: { revalidate: 86400 },
});
if (!res.ok) {
return NextResponse.json({ error: 'upstream' }, { status: 502 });
}
const contentType = res.headers.get('content-type') || 'image/jpeg';
const body = await res.arrayBuffer();
return new NextResponse(body, {
headers: {
'Content-Type': contentType,
'Cache-Control': 'private, max-age=3600',
},
});
} catch {
return NextResponse.json({ error: 'fetch_failed' }, { status: 502 });
}
}