Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

5.3 KB
Raw Blame
export const config = { runtime: 'edge' };

import { getCachedJson, setCachedJson } from './_upstash-cache.js';
import { recordCacheTelemetry } from './_cache-telemetry.js';
import { getCorsHeaders, isDisallowedOrigin } from './_cors.js';
import { createIpRateLimiter } from './_ip-rate-limit.js';
import { UA_BOT } from './_ua.js';

const limiter = createIpRateLimiter({ limit: 30, windowMs: 60_000 });
const CACHE_KEY = 'exploit-ledger:v1';
const CACHE_TTL = 3600; // 1h: the hacks DB is curated, not real-time

/** In-memory stale fallback (survives warm-start when Redis + upstream both fail) */
let staleResponse = null;

const NINETY_DAYS_S = 90 * 24 * 3600;
const YEAR_S = 365 * 24 * 3600;

/**
 * Structured exploit history from DeFiLlama /hacks (free, no API key):
 * curated database of protocol hacks with USD losses, attack technique,
 * and chain. Complements the RSS-based Exploit Alerts panel with hard
 * numbers instead of headlines.
 */
function shapeResponse(data, limit) {
  const hacks = (Array.isArray(data) ? data : [])
    .filter((h) => h && typeof h.date === 'number')
    .sort((a, b) => b.date - a.date);

  const nowS = Math.floor(Date.now() / 1000);
  const sumLost = (list) => list.reduce((sum, h) => sum + (typeof h.amount === 'number' ? h.amount : 0), 0);
  const last90d = hacks.filter((h) => nowS - h.date <= NINETY_DAYS_S);
  const lastYear = hacks.filter((h) => nowS - h.date <= YEAR_S);
  const biggest = hacks.reduce((max, h) => ((h.amount || 0) > (max?.amount || 0) ? h : max), null);

  return {
    timestamp: new Date().toISOString(),
    summary: {
      totalHacks: hacks.length,
      count90d: last90d.length,
      lost90d: sumLost(last90d),
      lost1y: sumLost(lastYear),
      lostAllTime: sumLost(hacks),
      biggest: biggest ? { name: biggest.name, amount: biggest.amount, date: biggest.date } : null,
    },
    hacks: hacks.slice(0, limit).map((h) => ({
      date: h.date,
      name: h.name || 'Unknown',
      amount: typeof h.amount === 'number' ? h.amount : null,
      classification: h.classification || null,
      technique: h.technique || null,
      chains: Array.isArray(h.chain) ? h.chain.slice(0, 4) : (h.chain ? [h.chain] : []),
      targetType: h.targetType || null,
      bridgeHack: Boolean(h.bridgeHack),
      returnedFunds: typeof h.returnedFunds === 'number' ? h.returnedFunds : null,
    })),
  };
}

export default async function handler(req) {
  const cors = getCorsHeaders(req);
  if (req.method === 'OPTIONS') {
    if (isDisallowedOrigin(req)) return new Response(null, { status: 403, headers: cors });
    return new Response(null, { status: 204, headers: cors });
  }
  if (isDisallowedOrigin(req)) {
    return new Response(JSON.stringify({ error: 'Forbidden' }), { status: 403, headers: { ...cors, 'Content-Type': 'application/json' } });
  }
  if (req.method !== 'GET') {
    return new Response(JSON.stringify({ error: 'Method not allowed' }), {
      status: 405, headers: { ...cors, 'Content-Type': 'application/json', Allow: 'GET, OPTIONS' },
    });
  }
  const clientIp = (req.headers.get('x-forwarded-for') || 'unknown').split(',')[0].trim();
  if (!limiter.check(clientIp)) {
    return new Response(JSON.stringify({ error: 'Too many requests' }), {
      status: 429, headers: { ...cors, 'Content-Type': 'application/json', 'Retry-After': '60' },
    });
  }

  const url = new URL(req.url);
  const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '30', 10) || 30, 1), 100);
  const redisKey = `${CACHE_KEY}:${limit}`;

  const cached = await getCachedJson(redisKey);
  if (cached) {
    recordCacheTelemetry('/api/exploit-ledger', 'HIT');
    return new Response(JSON.stringify(cached), {
      headers: { 'Content-Type': 'application/json', ...cors, 'X-Cache': 'HIT', 'Cache-Control': `public, max-age=${CACHE_TTL}, s-maxage=${CACHE_TTL}, stale-while-revalidate=300` },
    });
  }

  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 12000);
    const res = await fetch('https://api.llama.fi/hacks', {
      signal: controller.signal,
      headers: { Accept: 'application/json', 'User-Agent': UA_BOT },
    });
    clearTimeout(timeout);

    if (!res.ok) {
      return new Response(JSON.stringify({ error: `Upstream ${res.status}` }), {
        status: 502, headers: { 'Content-Type': 'application/json', ...cors },
      });
    }

    const shaped = shapeResponse(await res.json(), limit);
    staleResponse = shaped;
    void setCachedJson(redisKey, shaped, CACHE_TTL);
    recordCacheTelemetry('/api/exploit-ledger', 'MISS');

    return new Response(JSON.stringify(shaped), {
      headers: { 'Content-Type': 'application/json', ...cors, 'X-Cache': 'MISS', 'Cache-Control': `public, max-age=${CACHE_TTL}, s-maxage=${CACHE_TTL}, stale-while-revalidate=300` },
    });
  } catch {
    if (staleResponse) {
      recordCacheTelemetry('/api/exploit-ledger', 'STALE');
      return new Response(JSON.stringify(staleResponse), {
        headers: { 'Content-Type': 'application/json', ...cors, 'X-Cache': 'STALE', 'Cache-Control': 'public, max-age=300' },
      });
    }
    recordCacheTelemetry('/api/exploit-ledger', 'ERROR');
    return new Response(JSON.stringify({ error: 'Failed to fetch exploit data' }), {
      status: 500, headers: { 'Content-Type': 'application/json', ...cors },
    });
  }
}