Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

7.9 KB
Raw Blame
import { createHmac } from "node:crypto";
import sites from "../apps/gallery/sites.json" with { type: "json" };

const FAVORITES_ZSET = "designtaste:favorites";
const VOTERS_PREFIX = "designtaste:fav:voters:";
const RATE_WINDOW_MS = 10 * 60 * 1000;
const RATE_MAX_TOGGLES = 60;
const SITE_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/;
const KNOWN_SITE_IDS = new Set(sites.map((s) => s.id));

const memoryVoters = new Map();
const rateBuckets = new Map();

export function resetFavoritesState() {
  memoryVoters.clear();
  rateBuckets.clear();
}

export function isAllowedOrigin(originHeader) {
  if (!originHeader) return true;
  try {
    const u = new URL(originHeader);
    const host = u.hostname.toLowerCase();
    return (
      host === "designtaste.wtf" ||
      host === "www.designtaste.wtf" ||
      host.endsWith(".vercel.app") ||
      host === "localhost" ||
      host === "127.0.0.1"
    );
  } catch {
    return false;
  }
}

function getRedisConfig(env = process.env) {
  const url = (
    env.KV_REST_API_URL ||
    env.UPSTASH_REDIS_REST_URL ||
    ""
  ).replace(/\/+$/, "");
  const token =
    env.KV_REST_API_TOKEN || env.UPSTASH_REDIS_REST_TOKEN || "";
  if (!url || !token) return null;
  return { url, token };
}

async function redisPipeline(commands, config, fetchImpl = fetch) {
  const res = await fetchImpl(`${config.url}/pipeline`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${config.token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(commands),
  });
  if (!res.ok) {
    throw new Error(`Redis pipeline error (${res.status})`);
  }
  const data = await res.json();
  if (!Array.isArray(data)) {
    throw new Error("Invalid Redis pipeline response");
  }
  return data.map((entry) => {
    if (entry && entry.error) throw new Error(entry.error);
    return entry?.result;
  });
}

function hashVoter(clientKey, salt) {
  return createHmac("sha256", salt)
    .update(String(clientKey || "anonymous").slice(0, 120))
    .digest("hex")
    .slice(0, 24);
}

function checkToggleRate(clientKey, now = Date.now()) {
  const key = String(clientKey || "unknown").slice(0, 120);
  const recent = (rateBuckets.get(key) || []).filter(
    (t) => now - t < RATE_WINDOW_MS,
  );
  if (recent.length >= RATE_MAX_TOGGLES) {
    rateBuckets.set(key, recent);
    const retryAfter = Math.max(
      1,
      Math.ceil((RATE_WINDOW_MS - (now - recent[0])) / 1000),
    );
    return { allowed: false, retryAfter };
  }
  recent.push(now);
  rateBuckets.set(key, recent);
  if (rateBuckets.size > 500) {
    for (const [k, list] of rateBuckets) {
      if (!list.some((t) => now - t < RATE_WINDOW_MS)) rateBuckets.delete(k);
    }
  }
  return { allowed: true, retryAfter: 0 };
}

function memoryRanking() {
  return [...memoryVoters.entries()]
    .map(([id, set]) => [id, set.size])
    .filter(([, count]) => count > 0)
    .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
    .map(([id]) => id);
}

export async function getFavoritesRanking({
  env = process.env,
  fetchImpl = fetch,
} = {}) {
  const redis = getRedisConfig(env);
  if (!redis) {
    return {
      status: 200,
      body: { ok: true, ranking: memoryRanking(), persistent: false },
    };
  }
  try {
    // Only return ordered site IDs with at least 1 favorite — never expose raw counts.
    const [ranking] = await redisPipeline(
      [["ZREVRANGEBYSCORE", FAVORITES_ZSET, "+inf", "1", "LIMIT", "0", "500"]],
      redis,
      fetchImpl,
    );
    const clean = Array.isArray(ranking)
      ? ranking.filter((id) => typeof id === "string" && SITE_ID_RE.test(id))
      : [];
    return {
      status: 200,
      body: { ok: true, ranking: clean, persistent: true },
    };
  } catch {
    return {
      status: 200,
      body: { ok: true, ranking: memoryRanking(), persistent: false },
    };
  }
}

export async function recordFavoriteToggle(
  body,
  {
    clientKey = "anonymous",
    env = process.env,
    fetchImpl = fetch,
    skipRateLimit = false,
  } = {},
) {
  if (!body || typeof body !== "object") {
    return {
      status: 400,
      body: { ok: false, message: "Send a JSON body with site id and action." },
    };
  }

  const id = String(body.id || "").trim();
  const action = String(body.action || "").trim();
  if (!SITE_ID_RE.test(id) || !KNOWN_SITE_IDS.has(id)) {
    return {
      status: 400,
      body: { ok: false, message: "Invalid site identifier." },
    };
  }
  if (action !== "add" && action !== "remove") {
    return {
      status: 400,
      body: { ok: false, message: "Action must be add or remove." },
    };
  }

  if (!skipRateLimit) {
    const rate = checkToggleRate(clientKey);
    if (!rate.allowed) {
      return {
        status: 429,
        retryAfter: rate.retryAfter,
        body: { ok: false, message: "Too many favorite updates right now." },
      };
    }
  }

  const salt =
    env.FAVORITES_HASH_SALT ||
    env.KV_REST_API_TOKEN ||
    env.UPSTASH_REDIS_REST_TOKEN ||
    "designtaste-favorites-v1";
  const voterHash = hashVoter(clientKey, salt);
  const redis = getRedisConfig(env);

  if (!redis) {
    let set = memoryVoters.get(id);
    if (!set) {
      set = new Set();
      memoryVoters.set(id, set);
    }
    if (action === "add") set.add(voterHash);
    else set.delete(voterHash);
    if (set.size === 0) memoryVoters.delete(id);
    return { status: 200, body: { ok: true, persistent: false } };
  }

  try {
    const voterKey = VOTERS_PREFIX + id;
    const op = action === "add" ? "SADD" : "SREM";
    const [, rawCount] = await redisPipeline(
      [
        [op, voterKey, voterHash],
        ["SCARD", voterKey],
      ],
      redis,
      fetchImpl,
    );
    const count = Number(rawCount) || 0;
    const syncCmd =
      count > 0
        ? ["ZADD", FAVORITES_ZSET, String(count), id]
        : ["ZREM", FAVORITES_ZSET, id];
    await redisPipeline([syncCmd], redis, fetchImpl);
    return { status: 200, body: { ok: true, persistent: true } };
  } catch {
    return {
      status: 503,
      body: { ok: false, message: "Could not save favorite right now." },
    };
  }
}

async function readJsonBody(req) {
  if (req.body && typeof req.body === "object") return req.body;
  if (typeof req.body === "string") return JSON.parse(req.body);
  const chunks = [];
  let total = 0;
  for await (const chunk of req) {
    total += chunk.length;
    if (total > 4 * 1024) {
      throw Object.assign(new Error("Payload too large."), { status: 413 });
    }
    chunks.push(chunk);
  }
  const text = Buffer.concat(chunks).toString("utf8");
  return text ? JSON.parse(text) : {};
}

export default async function handler(req, res) {
  if (req.method === "GET") {
    res.setHeader(
      "Cache-Control",
      "public, s-maxage=15, stale-while-revalidate=60",
    );
    const result = await getFavoritesRanking();
    return res.status(result.status).json(result.body);
  }

  res.setHeader("Cache-Control", "no-store");
  if (req.method !== "POST") {
    res.setHeader("Allow", "GET, POST");
    return res.status(405).json({ ok: false, message: "Method not allowed." });
  }

  const origin = req.headers?.origin || req.headers?.referer || "";
  if (origin && !isAllowedOrigin(origin)) {
    return res.status(403).json({ ok: false, message: "Origin not allowed." });
  }

  const realIp = String(
    req.headers?.["x-real-ip"] ||
      req.headers?.["x-vercel-forwarded-for"] ||
      req.headers?.["x-forwarded-for"] ||
      "",
  )
    .split(",")[0]
    .trim();
  const clientKey = realIp || req.socket?.remoteAddress || "anonymous";

  try {
    const body = await readJsonBody(req);
    const result = await recordFavoriteToggle(body, { clientKey });
    if (result.retryAfter) {
      res.setHeader("Retry-After", String(result.retryAfter));
    }
    return res.status(result.status).json(result.body);
  } catch (err) {
    const status = err?.status || 400;
    return res.status(status).json({
      ok: false,
      message: err?.message || "Invalid favorite update.",
    });
  }
}