Skip to content

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

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

const DEFAULT_REPO = "ethanplusai/designtaste";
const SITE_ORIGIN = "https://designtaste.wtf";
export const PENDING_SUBMISSIONS_HASH = "designtaste:submissions:pending";

export const CATEGORIES = [
  "AI tools",
  "Design tools",
  "Developer tools",
  "SaaS",
  "Product",
  "Portfolio",
  "Experimental",
  "404 pages",
];

function safePublicWebsite(value) {
  let u;
  try {
    u = new URL(value);
  } catch {
    throw new Error("Use a full HTTPS website URL.");
  }
  if (
    u.protocol !== "https:" ||
    u.username ||
    u.password ||
    u.port ||
    u.hostname === "localhost" ||
    u.hostname.endsWith(".local") ||
    u.hostname.endsWith(".internal") ||
    !u.hostname.includes(".") ||
    /^\d+\.\d+\.\d+\.\d+$/.test(u.hostname) ||
    u.hostname.includes(":")
  ) {
    throw new Error(
      "Use a public HTTPS URL without credentials, ports, or IP addresses.",
    );
  }
  return u;
}

function canonicalKeyFromUrl(u) {
  return u.hostname.replace(/^www\./, "").toLowerCase() +
    u.pathname.replace(/\/$/, "") +
    u.search;
}

const CATALOG_BY_CANONICAL_URL = new Map();
for (const site of sites) {
  try {
    CATALOG_BY_CANONICAL_URL.set(
      canonicalKeyFromUrl(safePublicWebsite(site.url)),
      site,
    );
  } catch {
    // Ignore malformed catalog entries if any.
  }
}

export function extractStructuredIssueUrl(body) {
  if (typeof body !== "string") return null;
  const match = body.match(/^- \*\*URL\*\*:\s*(\S+)\s*$/m);
  if (!match) return null;
  try {
    return canonicalKeyFromUrl(safePublicWebsite(match[1].trim()));
  } catch {
    return null;
  }
}

const IP_WINDOW_MS = 15 * 60 * 1000;
const IP_MAX_REQUESTS = 5;
const GLOBAL_WINDOW_MS = 60 * 60 * 1000;
const GLOBAL_MAX_REQUESTS = 20;
const MAX_OPEN_QUEUE_ISSUES = 50;

const ipBuckets = new Map();
let globalTimestamps = [];

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 checkPersistentRateLimit(clientKey, { env = process.env, fetchImpl = fetch } = {}) {
  const redis = getRedisConfig(env);
  if (!redis) return checkRateLimit(clientKey);
  try {
    const ipWindow = Math.floor(Date.now() / IP_WINDOW_MS);
    const globalWindow = Math.floor(Date.now() / GLOBAL_WINDOW_MS);
    const safeKey = String(clientKey || "unknown").replace(/[^a-zA-Z0-9.:_-]/g, "").slice(0, 64) || "unknown";
    const ipKey = `designtaste:submit:ip:${safeKey}:${ipWindow}`;
    const globalKey = `designtaste:submit:global:${globalWindow}`;
    const res = await fetchImpl(`${redis.url}/pipeline`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${redis.token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify([
        ["INCR", ipKey],
        ["EXPIRE", ipKey, String(Math.ceil(IP_WINDOW_MS / 1000) + 60)],
        ["INCR", globalKey],
        ["EXPIRE", globalKey, String(Math.ceil(GLOBAL_WINDOW_MS / 1000) + 60)],
      ]),
    });
    if (!res.ok) return checkRateLimit(clientKey);
    const results = await res.json();
    const ipCount = Number(results?.[0]?.result) || 0;
    const globalCount = Number(results?.[2]?.result) || 0;
    if (globalCount > GLOBAL_MAX_REQUESTS) {
      return { allowed: false, retryAfter: 300 };
    }
    if (ipCount > IP_MAX_REQUESTS) {
      return { allowed: false, retryAfter: Math.ceil(IP_WINDOW_MS / 1000) };
    }
    return { allowed: true, retryAfter: 0 };
  } catch {
    return checkRateLimit(clientKey);
  }
}

export function resetRateLimits() {
  ipBuckets.clear();
  globalTimestamps = [];
}

export function checkRateLimit(clientKey, now = Date.now()) {
  globalTimestamps = globalTimestamps.filter((t) => now - t < GLOBAL_WINDOW_MS);
  if (globalTimestamps.length >= GLOBAL_MAX_REQUESTS) {
    return { allowed: false, retryAfter: 300 };
  }

  const key = String(clientKey || "unknown").slice(0, 120);
  const recent = (ipBuckets.get(key) || []).filter((t) => now - t < IP_WINDOW_MS);
  if (recent.length >= IP_MAX_REQUESTS) {
    const oldest = recent[0];
    const retryAfter = Math.max(1, Math.ceil((IP_WINDOW_MS - (now - oldest)) / 1000));
    ipBuckets.set(key, recent);
    return { allowed: false, retryAfter };
  }

  recent.push(now);
  ipBuckets.set(key, recent);
  globalTimestamps.push(now);

  // Prevent unbounded memory growth in long-lived warm instances.
  if (ipBuckets.size > 500) {
    for (const [k, list] of ipBuckets) {
      if (!list.some((t) => now - t < IP_WINDOW_MS)) ipBuckets.delete(k);
    }
  }
  return { allowed: true, retryAfter: 0 };
}

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;
  }
}

export function normalizeSubmission(body) {
  if (!body || typeof body !== "object") {
    throw Object.assign(new Error("Send a JSON body with a website URL."), {
      status: 400,
    });
  }
  if (typeof body.company_website === "string" && body.company_website.trim()) {
    return { spam: true };
  }
  const rawUrl = String(body.url || "").trim();
  if (!rawUrl) {
    throw Object.assign(new Error("Enter a website URL."), { status: 400 });
  }
  const withScheme = /^https?:\/\//i.test(rawUrl) ? rawUrl : `https://${rawUrl}`;
  let parsed;
  try {
    parsed = safePublicWebsite(withScheme);
  } catch (err) {
    throw Object.assign(new Error(err.message), { status: 400 });
  }
  const url = parsed.toString();
  const host = parsed.hostname.replace(/^www\./, "");
  const normalizedUrl = canonicalKeyFromUrl(parsed);
  const name =
    String(body.name || "").replace(/[\r\n]+/g, " ").trim().slice(0, 100) ||
    host;
  const rawCategory = String(body.category || "").trim();
  const category = CATEGORIES.includes(rawCategory)
    ? rawCategory
    : "Uncategorized";
  const note = String(body.note || "").replace(/[\r\n]+/g, " ").trim().slice(0, 500);

  return {
    spam: false,
    url,
    normalizedUrl,
    host,
    name,
    category,
    note,
  };
}

export function buildIssuePayload(sub) {
  const title = `Submission: ${sub.name} (${sub.host})`;
  const lines = [
    "### Website submission",
    "",
    `- **URL**: ${sub.url}`,
    `- **Name**: ${sub.name}`,
    `- **Suggested category**: ${sub.category}`,
    sub.note ? `- **Why it stood out**: ${sub.note}` : null,
    "",
    "---",
    "Submitted via `designtaste.wtf`.",
    "Curator quick-add: run `npm run site:from-issue -- <issue-number>` locally to capture a full-page screenshot and append to `apps/gallery/sites.json`.",
  ].filter((line) => line !== null);

  return {
    title,
    body: lines.join("\n"),
    labels: ["submission"],
  };
}

export function buildFallbackIssueUrl(sub, repo = DEFAULT_REPO) {
  const payload = buildIssuePayload(sub);
  const params = new URLSearchParams({
    title: payload.title,
    body: payload.body,
    labels: "submission",
  });
  return `https://github.com/${repo}/issues/new?${params.toString()}`;
}

async function queueSubmissionInRedis(sub, redis, { fetchImpl = fetch } = {}) {
  const headers = {
    Authorization: `Bearer ${redis.token}`,
    "Content-Type": "application/json",
  };
  const checkRes = await fetchImpl(`${redis.url}/pipeline`, {
    method: "POST",
    headers,
    body: JSON.stringify([
      ["HGET", PENDING_SUBMISSIONS_HASH, sub.normalizedUrl],
      ["HLEN", PENDING_SUBMISSIONS_HASH],
    ]),
  });
  if (!checkRes?.ok) return null;
  const checkData = await checkRes.json().catch(() => null);
  if (!Array.isArray(checkData)) return null;

  const existingRaw = checkData[0]?.result;
  const pendingCount = Number(checkData[1]?.result) || 0;

  if (typeof existingRaw === "string" && existingRaw) {
    let existing = {};
    try {
      existing = JSON.parse(existingRaw);
    } catch {
      existing = {};
    }
    const updated = {
      id: existing.id || `sub_${randomBytes(6).toString("base64url")}`,
      url: existing.url || sub.url,
      normalizedUrl: sub.normalizedUrl,
      host: existing.host || sub.host,
      name: existing.name || sub.name,
      category:
        existing.category && existing.category !== "Uncategorized"
          ? existing.category
          : sub.category,
      note: existing.note || sub.note,
      votes: (Number(existing.votes) || 1) + 1,
      submittedAt: existing.submittedAt || new Date().toISOString(),
      lastVotedAt: new Date().toISOString(),
    };
    await fetchImpl(`${redis.url}/pipeline`, {
      method: "POST",
      headers,
      body: JSON.stringify([
        ["HSET", PENDING_SUBMISSIONS_HASH, sub.normalizedUrl, JSON.stringify(updated)],
      ]),
    });
    return {
      status: 200,
      body: {
        ok: true,
        duplicate: true,
        submissionId: updated.id,
        votes: updated.votes,
        message: "Already in the curation queue — thanks for the vote!",
      },
    };
  }

  if (pendingCount >= MAX_OPEN_QUEUE_ISSUES) {
    return {
      status: 429,
      retryAfter: 600,
      body: {
        ok: false,
        code: "queue_full",
        message:
          "The curation queue is full right now while we review pending sites. Please try again later.",
      },
    };
  }

  const submissionId = `sub_${randomBytes(6).toString("base64url")}`;
  const record = {
    id: submissionId,
    url: sub.url,
    normalizedUrl: sub.normalizedUrl,
    host: sub.host,
    name: sub.name,
    category: sub.category,
    note: sub.note,
    votes: 1,
    submittedAt: new Date().toISOString(),
  };

  const writeRes = await fetchImpl(`${redis.url}/pipeline`, {
    method: "POST",
    headers,
    body: JSON.stringify([
      ["HSET", PENDING_SUBMISSIONS_HASH, sub.normalizedUrl, JSON.stringify(record)],
    ]),
  });
  if (!writeRes?.ok) return null;
  const writeData = await writeRes.json().catch(() => null);
  if (!Array.isArray(writeData) || writeData[0]?.error) return null;

  return {
    status: 201,
    body: {
      ok: true,
      queued: true,
      submissionId,
      message: "Submitted — added to the curation queue.",
    },
  };
}

export async function handleSubmission(
  body,
  {
    env = process.env,
    token = env.GITHUB_SUBMISSIONS_TOKEN || "",
    repo = env.GITHUB_SUBMISSIONS_REPO || DEFAULT_REPO,
    fetchImpl = fetch,
    clientKey = "anonymous",
    skipRateLimit = false,
  } = {},
) {
  if (!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(repo)) {
    throw Object.assign(new Error("Invalid submissions repository."), {
      status: 500,
    });
  }

  const sub = normalizeSubmission(body);
  if (sub.spam) {
    return {
      status: 202,
      body: { ok: true, message: "Thanks — your submission has been received." },
    };
  }

  if (!skipRateLimit) {
    const rate = await checkPersistentRateLimit(clientKey, { env, fetchImpl });
    if (!rate.allowed) {
      return {
        status: 429,
        retryAfter: rate.retryAfter,
        body: {
          ok: false,
          code: "rate_limited",
          message: "Too many submissions right now. Please wait a few minutes and try again.",
        },
      };
    }
  }

  const published = CATALOG_BY_CANONICAL_URL.get(sub.normalizedUrl);
  if (published) {
    return {
      status: 200,
      body: {
        ok: true,
        alreadyListed: true,
        siteId: published.id,
        siteUrl: `${SITE_ORIGIN}/sites/${published.id}/`,
        message: `${published.name} is already featured in DesignTaste!`,
      },
    };
  }

  const fallbackUrl = buildFallbackIssueUrl(sub, repo);

  if (!token) {
    const redis = getRedisConfig(env);
    if (redis) {
      try {
        const queued = await queueSubmissionInRedis(sub, redis, { fetchImpl });
        if (queued) return queued;
      } catch {
        // Fall through to upstream error with one-click fallback.
      }
      return {
        status: 502,
        body: {
          ok: false,
          code: "upstream_error",
          message:
            "Could not queue the submission right now. Try the one-click fallback below.",
          fallbackUrl,
        },
      };
    }

    return {
      status: 503,
      body: {
        ok: false,
        code: "queue_unconfigured",
        message:
          "Direct submission queue is not configured on this environment yet. You can open a pre-filled submission in one click.",
        fallbackUrl,
      },
    };
  }

  const endpoint = `https://api.github.com/repos/${repo}/issues`;
  const headers = {
    Authorization: `Bearer ${token}`,
    Accept: "application/vnd.github+json",
    "Content-Type": "application/json",
    "X-GitHub-Api-Version": "2022-11-28",
    "User-Agent": "designtaste-submit/1.0",
  };

  // Deduplicate against open submission issues and cap total open queue size to prevent flooding.
  const openRes = await fetchImpl(
    `${endpoint}?state=open&labels=submission&per_page=${MAX_OPEN_QUEUE_ISSUES}`,
    { method: "GET", headers },
  );
  if (openRes?.ok) {
    const openIssues = await openRes.json().catch(() => []);
    if (Array.isArray(openIssues)) {
      const existing = openIssues.find(
        (item) => extractStructuredIssueUrl(item?.body) === sub.normalizedUrl,
      );
      if (existing) {
        return {
          status: 200,
          body: {
            ok: true,
            duplicate: true,
            message: "Already in the curation queue — thanks for the vote!",
            issueNumber: existing.number,
            issueUrl: existing.html_url,
          },
        };
      }
      if (openIssues.length >= MAX_OPEN_QUEUE_ISSUES) {
        return {
          status: 429,
          retryAfter: 600,
          body: {
            ok: false,
            code: "queue_full",
            message:
              "The curation queue is full right now while we review pending sites. Please try again later.",
          },
        };
      }
    }
  }

  const payload = buildIssuePayload(sub);
  let response = await fetchImpl(endpoint, {
    method: "POST",
    headers,
    body: JSON.stringify(payload),
  });

  if (response.status === 422) {
    const { title, body: issueBody } = payload;
    response = await fetchImpl(endpoint, {
      method: "POST",
      headers,
      body: JSON.stringify({ title, body: issueBody }),
    });
  }

  if (!response.ok) {
    return {
      status: 502,
      body: {
        ok: false,
        code: "upstream_error",
        message:
          "Could not queue the submission right now. Try the one-click fallback below.",
        fallbackUrl,
      },
    };
  }

  const issue = await response.json();
  return {
    status: 201,
    body: {
      ok: true,
      message: "Submitted — added to the curation queue.",
      issueNumber: issue.number,
      issueUrl: issue.html_url,
    },
  };
}

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 > 16 * 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("Cache-Control", "no-store");
  if (req.method !== "POST") {
    res.setHeader("Allow", "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 handleSubmission(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 submission.",
    });
  }
}