Skip to content

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

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

export const ORIGIN = "https://designtaste.wtf";
const LIST_KEY_PREFIX = "designtaste:list:";
const LIST_ID_RE = /^dt_[a-z0-9]{6,16}$/;
const MAX_SITES_PER_LIST = 50;
const RATE_WINDOW_MS = 15 * 60 * 1000;
const RATE_MAX_CREATES = 15;
const GLOBAL_WINDOW_MS = 60 * 60 * 1000;
const GLOBAL_MAX_CREATES = 250;
const LIST_TTL_SECONDS = 365 * 24 * 60 * 60;
const ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";

export const sitesById = new Map(sites.map((s) => [s.id, s]));
export const catalogSites = sites;

const memoryLists = new Map();
const memoryRate = new Map();

export function resetListsState() {
  memoryLists.clear();
  memoryRate.clear();
}

export function outboundUrl(url) {
  try {
    const u = new URL(url);
    if (u.protocol === "https:" || u.protocol === "http:") {
      if (!u.searchParams.has("ref")) {
        u.searchParams.set("ref", "designtaste.wtf");
      }
      return u.toString();
    }
  } catch {
    // fall through
  }
  return url;
}

export function formatPublicSite(site) {
  return {
    id: site.id,
    name: site.name,
    url: site.url,
    visitUrl: outboundUrl(site.url),
    category: site.category,
    tags: site.tags,
    description: site.description,
    observation: site.observation || site.description,
    capturedAt: site.capturedAt,
    credit: site.credit || site.name,
    detailUrl: `${ORIGIN}/sites/${site.id}/`,
    thumbUrl: `${ORIGIN}/images/${site.id}-thumb.jpg`,
    previewUrl: `${ORIGIN}/images/${site.id}-720.jpg`,
    imageUrl: `${ORIGIN}/${site.image}`,
  };
}

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 error (${res.status})`);
  const data = await res.json();
  if (!Array.isArray(data)) throw new Error("Invalid Redis response");
  return data.map((entry) => {
    if (entry && entry.error) throw new Error(entry.error);
    return entry?.result;
  });
}

function generateListId() {
  const bytes = randomBytes(8);
  let out = "dt_";
  for (let i = 0; i < bytes.length; i++) {
    out += ALPHABET[bytes[i] % ALPHABET.length];
  }
  return out;
}

function sanitizeTitle(raw) {
  return String(raw || "")
    .replace(/[\r\n\t]+/g, " ")
    .replace(/[<>]/g, "")
    .replace(/\s{2,}/g, " ")
    .trim()
    .slice(0, 80);
}

async function checkCreateRate(
  clientKey,
  { env = process.env, fetchImpl = fetch } = {},
) {
  const redis = getRedisConfig(env);
  const safeKey =
    String(clientKey || "unknown")
      .replace(/[^a-zA-Z0-9.:_-]/g, "")
      .slice(0, 64) || "unknown";
  if (redis) {
    try {
      const win = Math.floor(Date.now() / RATE_WINDOW_MS);
      const gWin = Math.floor(Date.now() / GLOBAL_WINDOW_MS);
      const key = `designtaste:lists:rate:${safeKey}:${win}`;
      const gKey = `designtaste:lists:global:${gWin}`;
      const [count, , globalCount] = await redisPipeline(
        [
          ["INCR", key],
          ["EXPIRE", key, String(Math.ceil(RATE_WINDOW_MS / 1000) + 60)],
          ["INCR", gKey],
          ["EXPIRE", gKey, String(Math.ceil(GLOBAL_WINDOW_MS / 1000) + 60)],
        ],
        redis,
        fetchImpl,
      );
      if (Number(globalCount) > GLOBAL_MAX_CREATES) {
        return { allowed: false, retryAfter: 300 };
      }
      if (Number(count) > RATE_MAX_CREATES) {
        return { allowed: false, retryAfter: 300 };
      }
      return { allowed: true, retryAfter: 0 };
    } catch {
      // Fall through to memory limiter.
    }
  }
  const now = Date.now();
  const recent = (memoryRate.get(safeKey) || []).filter(
    (t) => now - t < RATE_WINDOW_MS,
  );
  if (recent.length >= RATE_MAX_CREATES) {
    memoryRate.set(safeKey, recent);
    return { allowed: false, retryAfter: 300 };
  }
  recent.push(now);
  memoryRate.set(safeKey, recent);
  return { allowed: true, retryAfter: 0 };
}

export async function createSavedList(
  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 ids." },
    };
  }
  if (!Array.isArray(body.ids)) {
    return {
      status: 400,
      body: { ok: false, message: "Provide an array of site ids." },
    };
  }

  const uniqueIds = [];
  const seen = new Set();
  for (const raw of body.ids) {
    const id = String(raw || "").trim();
    if (!id || seen.has(id)) continue;
    if (!sitesById.has(id)) {
      return {
        status: 400,
        body: { ok: false, message: `Unknown site id: ${id}` },
      };
    }
    seen.add(id);
    uniqueIds.push(id);
    if (uniqueIds.length > MAX_SITES_PER_LIST) {
      return {
        status: 400,
        body: {
          ok: false,
          message: `A shared list can hold at most ${MAX_SITES_PER_LIST} websites.`,
        },
      };
    }
  }

  if (uniqueIds.length === 0) {
    return {
      status: 400,
      body: { ok: false, message: "Save at least one website before sharing." },
    };
  }

  if (!skipRateLimit) {
    const rate = await checkCreateRate(clientKey, { env, fetchImpl });
    if (!rate.allowed) {
      return {
        status: 429,
        retryAfter: rate.retryAfter,
        body: {
          ok: false,
          message: "Too many lists created right now. Please try again shortly.",
        },
      };
    }
  }

  const id = generateListId();
  const title = sanitizeTitle(body.title);
  const record = {
    id,
    title,
    ids: uniqueIds,
    createdAt: new Date().toISOString(),
  };

  const redis = getRedisConfig(env);
  let persistent = false;
  if (redis) {
    try {
      await redisPipeline(
        [
          [
            "SET",
            LIST_KEY_PREFIX + id,
            JSON.stringify(record),
            "EX",
            String(LIST_TTL_SECONDS),
          ],
        ],
        redis,
        fetchImpl,
      );
      persistent = true;
    } catch {
      return {
        status: 503,
        body: { ok: false, message: "Could not save list right now." },
      };
    }
  } else {
    memoryLists.set(id, record);
  }

  const url = `${ORIGIN}/?list=${id}`;
  return {
    status: 201,
    body: {
      ok: true,
      id,
      title,
      ids: uniqueIds,
      count: uniqueIds.length,
      url,
      mcpUrl: `${ORIGIN}/api/mcp/`,
      mcpPrompt: `Use my DesignTaste saved list "${id}" via the DesignTaste MCP (${ORIGIN}/api/mcp/) as visual direction.`,
      persistent,
    },
  };
}

export async function getSavedList(
  rawId,
  { env = process.env, fetchImpl = fetch } = {},
) {
  const id = String(rawId || "").trim().toLowerCase();
  if (!LIST_ID_RE.test(id)) {
    return {
      status: 400,
      body: { ok: false, message: "Invalid list ID format (expected dt_...)." },
    };
  }

  const redis = getRedisConfig(env);
  let record = null;
  if (redis) {
    try {
      const [raw] = await redisPipeline(
        [["GET", LIST_KEY_PREFIX + id]],
        redis,
        fetchImpl,
      );
      if (typeof raw === "string" && raw) {
        record = JSON.parse(raw);
      }
    } catch {
      return {
        status: 503,
        body: { ok: false, message: "Could not load list right now." },
      };
    }
  } else {
    record = memoryLists.get(id) || null;
  }

  if (!record || !Array.isArray(record.ids)) {
    return {
      status: 404,
      body: { ok: false, message: "Saved list not found." },
    };
  }

  const resolvedSites = record.ids
    .map((siteId) => sitesById.get(siteId))
    .filter(Boolean)
    .map(formatPublicSite);

  return {
    status: 200,
    body: {
      ok: true,
      list: {
        id: record.id,
        title: record.title || "",
        ids: resolvedSites.map((s) => s.id),
        count: resolvedSites.length,
        createdAt: record.createdAt || null,
        url: `${ORIGIN}/?list=${record.id}`,
        sites: resolvedSites,
      },
    },
  };
}

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 > 8 * 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) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept");

  if (req.method === "OPTIONS") {
    return res.status(204).end();
  }

  if (req.method === "GET") {
    const reqUrl = new URL(req.url || "/", ORIGIN);
    const id = req.query?.id || reqUrl.searchParams.get("id") || "";
    const result = await getSavedList(id);
    if (result.status === 200) {
      res.setHeader(
        "Cache-Control",
        "public, s-maxage=60, stale-while-revalidate=300",
      );
    } else {
      res.setHeader("Cache-Control", "no-store");
    }
    return res.status(result.status).json(result.body);
  }

  res.setHeader("Cache-Control", "no-store");
  if (req.method !== "POST") {
    res.setHeader("Allow", "GET, POST, OPTIONS");
    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 createSavedList(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 list request.",
    });
  }
}