Skip to content

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

28.2 KB
Raw Blame
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { JSDOM } from "jsdom";
import { gallery, detail, info, escapeHTML } from "../apps/gallery/render.mjs";
import { validateSites, safeWebsite } from "../scripts/gallery-catalog.mjs";
import {
  handleSubmission,
  normalizeSubmission,
  isAllowedOrigin,
  resetRateLimits,
} from "../api/submit.js";
import {
  getFavoritesRanking,
  recordFavoriteToggle,
  resetFavoritesState,
} from "../api/favorites.js";
import {
  createSavedList,
  getSavedList,
  resetListsState,
} from "../api/lists.js";
import { handleMcpMessage } from "../api/mcp.js";
import { assertPublicTargetUrl } from "../scripts/capture-lib.mjs";

const root = fileURLToPath(new URL("../apps/gallery/", import.meta.url));
const sites = JSON.parse(readFileSync(root + "sites.json", "utf8"));
const script = readFileSync(root + "gallery.js", "utf8");

function dom(html, url = "https://designtaste.wtf/") {
  return new JSDOM(html, {
    url,
    runScripts: "outside-only",
    pretendToBeVisual: true,
  });
}

function interactive(url) {
  const d = dom(gallery(sites), url);
  d.window.matchMedia = () => ({ matches: false, addEventListener() {} });
  d.window.eval(script);
  return d;
}

test("all submitted references have safe URLs, real local screenshots, accurate dimensions and hashes", async () => {
  assert.ok(sites.length >= 100);
  await validateSites(sites, root);
});

test("public URL validation rejects credentials, local addresses, ports and executable schemes", () => {
  for (const value of [
    "javascript:alert(1)",
    "http://example.com",
    "https://a:[email protected]",
    "https://127.0.0.1",
    "https://localhost/",
    "https://host.local/",
    "https://[::1]/",
    "https://example.com:999/",
  ])
    assert.throws(() => safeWebsite(value));
  assert.equal(safeWebsite("https://example.com/").hostname, "example.com");
});

test("catalog rejects duplicates, traversal and tampered screenshot hashes", async () => {
  for (const mutation of [
    (s) => s.push(s[0]),
    (s) => (s[0].image = "../secret.jpg"),
    (s) => (s[0].captureSha256 = "bad"),
    (s) => (s[0].imageDimensions.width = 1),
  ]) {
    const input = structuredClone(sites);
    mutation(input);
    await assert.rejects(validateSites(input, root));
  }
});

test("gallery works without scripts, has heart save buttons, and opens sources separately from details", () => {
  const d = dom(gallery(sites)),
    doc = d.window.document;
  assert.equal(doc.querySelectorAll(".site-card").length, sites.length);
  for (const c of doc.querySelectorAll(".site-card")) {
    const a = c.querySelector(".preview");
    assert.equal(a.target, "_blank");
    assert.match(a.rel, /noopener/);
    assert.match(
      c.querySelector(".details").pathname,
      /^\/sites\/[a-z0-9-]+\/$/,
    );
    const saveBtn = c.querySelector(".save-btn");
    assert.ok(saveBtn, "each card has a circular save button");
    assert.equal(saveBtn.dataset.saveId, c.dataset.id);
    assert.equal(saveBtn.closest("a"), null, "save button is not nested inside link");
  }
  assert.equal(doc.querySelectorAll("iframe").length, 0);
  assert.doesNotMatch(doc.body.textContent, /Sign in|Create a brief/);
  d.window.close();
});

test("category pages are filtered before JavaScript and expose crawlable detail links", () => {
  const d = dom(gallery(sites, { category: "AI tools" }));
  assert.equal(
    d.window.document.querySelectorAll(".site-card:not([hidden])").length,
    sites.filter((s) => s.category === "AI tools").length,
  );
  assert.equal(
    d.window.document.querySelector('link[rel="canonical"]').href,
    "https://designtaste.wtf/categories/ai-tools/",
  );
  d.window.close();
});

test("search, categories, saved filter, empty state, URL restore, and sorting operate on the actual collection", () => {
  const d = interactive("https://designtaste.wtf/?q=cursor"),
    w = d.window,
    doc = w.document;
  const input = doc.querySelector("#search");
  assert.equal(doc.querySelectorAll(".site-card:not([hidden])").length, 1);
  assert.equal(doc.querySelector("#result-count").textContent, "1");
  input.value = "zzzz-does-not-exist";
  input.dispatchEvent(new w.Event("input"));
  assert.equal(doc.querySelector("#empty").hidden, false);
  input.value = "";
  input.dispatchEvent(new w.Event("input"));
  doc.querySelector('[data-filter="AI tools"]').click();
  const aiCount = sites.filter((s) => s.category === "AI tools").length;
  assert.equal(doc.querySelector("#result-count").textContent, String(aiCount));
  assert.equal(
    doc.querySelectorAll(".site-card:not([hidden])").length,
    Math.min(36, aiCount),
  );
  if (aiCount > 36) {
    doc.querySelector("#load-more").click();
    assert.equal(
      doc.querySelectorAll(".site-card:not([hidden])").length,
      Math.min(72, aiCount),
    );
  }
  assert.equal(w.location.pathname, "/categories/ai-tools/");
  const sort = doc.querySelector("#sort");
  sort.value = "az";
  sort.dispatchEvent(new w.Event("change"));
  const names = [...doc.querySelectorAll(".site-name")].map(
    (x) => x.textContent,
  );
  assert.deepEqual(
    names,
    [...names].sort((a, b) => a.localeCompare(b)),
  );
  d.window.close();
});

test("circular heart save persists in localStorage and powers the Saved filter view", () => {
  const d = interactive(),
    w = d.window,
    doc = w.document;
  const firstCard = doc.querySelector(".site-card");
  const saveBtn = firstCard.querySelector(".save-btn");
  const id = firstCard.dataset.id;

  assert.equal(saveBtn.getAttribute("aria-pressed"), "false");
  saveBtn.click();
  assert.equal(saveBtn.getAttribute("aria-pressed"), "true");
  assert.deepEqual(JSON.parse(w.localStorage.getItem("designtaste:saved")), [id]);

  // Switch to Saved view
  doc.querySelector("[data-saved-filter]").click();
  assert.equal(doc.querySelectorAll(".site-card:not([hidden])").length, 1);
  assert.equal(doc.querySelector("#result-count").textContent, "1");
  assert.equal(w.location.search, "?saved=1");

  // Unsave inside Saved view updates empty state immediately
  saveBtn.click();
  assert.equal(doc.querySelectorAll(".site-card:not([hidden])").length, 0);
  assert.equal(doc.querySelector("#empty").hidden, false);
  assert.deepEqual(JSON.parse(w.localStorage.getItem("designtaste:saved")), []);
  d.window.close();
});

test("preview motion is focus-accessible, reversible, and stoppable", () => {
  const d = interactive(),
    doc = d.window.document,
    a = doc.querySelector(".preview"),
    img = a.querySelector("img");
  Object.defineProperty(img, "naturalWidth", { value: 1200 });
  img.getBoundingClientRect = () => ({ height: 1600 });
  Object.defineProperty(a, "clientHeight", { value: 400 });
  a.dispatchEvent(new d.window.Event("focus"));
  assert.equal(a.classList.contains("scrolling"), true);
  assert.equal(a.style.getPropertyValue("--travel"), "-1200px");
  a.dispatchEvent(new d.window.Event("blur"));
  assert.equal(a.classList.contains("scrolling"), false);
  doc.querySelector("#motion-toggle").click();
  a.dispatchEvent(new d.window.Event("focus"));
  assert.equal(a.classList.contains("scrolling"), false);
  assert.equal(
    doc.querySelector("#motion-toggle").getAttribute("aria-pressed"),
    "true",
  );
  d.window.close();
});

test("reduced motion prevents auto-scrolling and honors the system preference", () => {
  const d = dom(gallery(sites));
  d.window.matchMedia = () => ({ matches: true, addEventListener() {} });
  d.window.eval(script);
  const doc = d.window.document,
    a = doc.querySelector(".preview");
  a.dispatchEvent(new d.window.Event("focus"));
  assert.equal(a.classList.contains("scrolling"), false);
  assert.ok(doc.documentElement.classList.contains("motion-paused"));
  assert.equal(doc.querySelector("#motion-toggle").disabled, true);
  d.window.close();
});

test("detail pages provide unique SEO, creator attribution, save button, and related references", () => {
  for (const site of sites) {
    const d = dom(detail(site, sites)),
      doc = d.window.document;
    assert.equal(doc.querySelector("h1").textContent, site.name);
    assert.equal(
      doc.querySelector('link[rel="canonical"]').href,
      `https://designtaste.wtf/sites/${site.id}/`,
    );
    assert.match(
      doc.querySelector('meta[property="og:image"]').content,
      new RegExp(site.id + "-og.jpg"),
    );
    assert.ok(doc.querySelector(`.detail-save-btn[data-save-id="${site.id}"]`));
    assert.doesNotThrow(() =>
      JSON.parse(
        doc.querySelector('script[type="application/ld+json"]').textContent,
      ),
    );
    assert.ok(doc.body.textContent.includes(site.credit));
    d.window.close();
  }
});

test("catalog text cannot inject markup or terminate structured data", () => {
  const evil = {
    ...sites[0],
    name: "</script><script>alert(1)</script>",
    description: '<img onerror="alert(1)">',
  };
  const d = dom(detail(evil, sites));
  assert.equal(d.window.document.querySelectorAll("script").length, 4);
  assert.ok(
    d.window.document.querySelector('script[src="/share-studio.js"]'),
  );
  assert.ok(
    d.window.document.querySelector('script[src="/_vercel/insights/script.js"]'),
  );
  assert.equal(d.window.document.querySelector("h1").textContent, evil.name);
  assert.ok(escapeHTML('"<').includes("&quot;"));
  d.window.close();
});

test("submit page provides a simple URL submission form and about page explains rights", () => {
  const submit = dom(info("submit")),
    about = dom(info("about"));
  assert.ok(submit.window.document.querySelector("form[data-submit-form]"));
  assert.ok(submit.window.document.querySelector('input[name="url"]'));
  assert.match(about.window.document.body.textContent, /respective owners/);
  submit.window.close();
  about.window.close();
});

test("submission API validates URLs, ignores honeypot spam, deduplicates, rate-limits, and creates structured GitHub issues", async () => {
  resetRateLimits();
  assert.throws(() => normalizeSubmission({ url: "http://localhost:3000" }));
  assert.equal(
    normalizeSubmission({ url: "example.com", category: "SaaS" }).url,
    "https://example.com/",
  );
  assert.equal(isAllowedOrigin("https://designtaste.wtf"), true);
  assert.equal(isAllowedOrigin("https://evil.example"), false);

  const spam = await handleSubmission({
    url: "https://example.com",
    company_website: "bot-filled",
  });
  assert.equal(spam.status, 202);
  assert.equal(spam.body.ok, true);

  // Already-published catalog sites return a friendly gallery link immediately
  const alreadyListed = await handleSubmission(
    { url: "https://linear.app", note: "Crisp dark craft" },
    { token: "", env: {}, clientKey: "198.51.100.1" },
  );
  assert.equal(alreadyListed.status, 200);
  assert.equal(alreadyListed.body.ok, true);
  assert.equal(alreadyListed.body.alreadyListed, true);
  assert.equal(alreadyListed.body.siteUrl, "https://designtaste.wtf/sites/linear/");

  const unconfigured = await handleSubmission(
    { url: "https://new-studio.example", note: "Crisp dark craft" },
    { token: "", env: {}, clientKey: "198.51.100.10" },
  );
  assert.equal(unconfigured.status, 503);
  assert.match(unconfigured.body.fallbackUrl, /github\.com\/.*\/issues\/new/);

  // Queues directly into Upstash Redis when GITHUB_SUBMISSIONS_TOKEN is unset
  const redisStore = new Map();
  const redisEnv = {
    KV_REST_API_URL: "https://redis.example",
    KV_REST_API_TOKEN: "redis-secret",
  };
  const redisFetch = async (_url, init) => {
    const cmds = JSON.parse(init.body);
    const out = cmds.map(([op, _key, field, val]) => {
      if (op === "INCR") return { result: 1 };
      if (op === "EXPIRE") return { result: 1 };
      if (op === "HGET") return { result: redisStore.get(field) ?? null };
      if (op === "HLEN") return { result: redisStore.size };
      if (op === "HSET") {
        redisStore.set(field, val);
        return { result: 1 };
      }
      return { result: null };
    });
    return { ok: true, status: 200, json: async () => out };
  };
  const queued = await handleSubmission(
    { url: "https://fresh-craft.example", name: "Fresh Craft", category: "Portfolio", note: "Bold type" },
    { token: "", env: redisEnv, fetchImpl: redisFetch, clientKey: "198.51.100.11" },
  );
  assert.equal(queued.status, 201);
  assert.equal(queued.body.ok, true);
  assert.equal(queued.body.queued, true);
  assert.match(queued.body.submissionId, /^sub_/);

  // Deduplicates in Redis and bumps vote count
  const queuedDup = await handleSubmission(
    { url: "https://www.fresh-craft.example/" },
    { token: "", env: redisEnv, fetchImpl: redisFetch, clientKey: "198.51.100.12" },
  );
  assert.equal(queuedDup.status, 200);
  assert.equal(queuedDup.body.duplicate, true);
  assert.equal(queuedDup.body.votes, 2);

  let sent = null;
  const created = await handleSubmission(
    { url: "https://new-portfolio.example", name: "Studio Nova", category: "Portfolio", note: "Tactile motion" },
    {
      token: "test-token",
      env: {},
      clientKey: "198.51.100.2",
      fetchImpl: async (url, init) => {
        if (init.method === "GET") {
          return { ok: true, status: 200, json: async () => [] };
        }
        sent = { url, body: JSON.parse(init.body) };
        return {
          ok: true,
          status: 201,
          json: async () => ({
            number: 42,
            html_url: "https://github.com/ethanplusai/designtaste/issues/42",
          }),
        };
      },
    },
  );
  assert.equal(created.status, 201);
  assert.equal(created.body.issueNumber, 42);
  assert.match(sent.body.title, /Studio Nova/);
  assert.match(sent.body.body, /https:\/\/new-portfolio\.example\//);

  // Deduplicates against open issues
  const dup = await handleSubmission(
    { url: "https://new-portfolio.example" },
    {
      token: "test-token",
      env: {},
      clientKey: "198.51.100.3",
      fetchImpl: async () => ({
        ok: true,
        status: 200,
        json: async () => [
          {
            number: 42,
            html_url: "https://github.com/ethanplusai/designtaste/issues/42",
            body: "- **URL**: https://new-portfolio.example/",
          },
        ],
      }),
    },
  );
  assert.equal(dup.status, 200);
  assert.equal(dup.body.duplicate, true);

  // Free-text mentions of another URL inside a note do not suppress legitimate submissions
  const notDup = await handleSubmission(
    { url: "https://brand-new-craft.example" },
    {
      token: "test-token",
      env: {},
      clientKey: "198.51.100.4",
      fetchImpl: async (_url, init) => {
        if (init.method === "GET") {
          return {
            ok: true,
            status: 200,
            json: async () => [
              {
                number: 43,
                html_url: "https://github.com/ethanplusai/designtaste/issues/43",
                body: "- **URL**: https://other.example/\n- **Why it stood out**: similar to https://brand-new-craft.example/",
              },
            ],
          };
        }
        return {
          ok: true,
          status: 201,
          json: async () => ({
            number: 44,
            html_url: "https://github.com/ethanplusai/designtaste/issues/44",
          }),
        };
      },
    },
  );
  assert.equal(notDup.status, 201);
  assert.equal(notDup.body.issueNumber, 44);

  // Rate limits rapid bursts from the same client
  for (let i = 0; i < 5; i++) {
    await handleSubmission(
      { url: `https://site${i}.example.com` },
      { token: "", env: {}, clientKey: "198.51.100.99" },
    );
  }
  const throttled = await handleSubmission(
    { url: "https://site6.example.com" },
    { token: "", env: {}, clientKey: "198.51.100.99" },
  );
  assert.equal(throttled.status, 429);
  assert.equal(throttled.body.code, "rate_limited");
});

test("capture helper blocks localhost, direct IPs, and private network targets", async () => {
  await assert.rejects(() => assertPublicTargetUrl("http://127.0.0.1:8080/"));
  await assert.rejects(() => assertPublicTargetUrl("http://169.254.169.254/latest/meta-data/"));
  await assert.rejects(() => assertPublicTargetUrl("https://localhost/admin"));
  await assert.rejects(() => assertPublicTargetUrl("file:///etc/passwd"));
});

test("favorites API deduplicates per visitor, ranks most-favorited first, and never leaks counts", async () => {
  resetFavoritesState();
  // Invalid inputs rejected
  assert.equal((await recordFavoriteToggle({ id: "../evil", action: "add" })).status, 400);
  assert.equal((await recordFavoriteToggle({ id: "linear", action: "boost" })).status, 400);

  // One visitor clicking add repeatedly only counts once (idempotent)
  for (let i = 0; i < 4; i++) {
    await recordFavoriteToggle(
      { id: "linear", action: "add" },
      { clientKey: "203.0.113.10", env: {} },
    );
  }
  // Two distinct visitors favorite "anywr" -> should rank ahead of "linear"
  await recordFavoriteToggle(
    { id: "anywr", action: "add" },
    { clientKey: "203.0.113.11", env: {} },
  );
  await recordFavoriteToggle(
    { id: "anywr", action: "add" },
    { clientKey: "203.0.113.12", env: {} },
  );

  const res = await getFavoritesRanking({ env: {} });
  assert.equal(res.status, 200);
  assert.deepEqual(res.body.ranking, ["anywr", "linear"]);
  assert.equal("counts" in res.body, false, "raw favorite counts are never exposed");

  // Removing a favorite updates ranking cleanly
  await recordFavoriteToggle(
    { id: "anywr", action: "remove" },
    { clientKey: "203.0.113.11", env: {} },
  );
  await recordFavoriteToggle(
    { id: "anywr", action: "remove" },
    { clientKey: "203.0.113.12", env: {} },
  );
  const after = await getFavoritesRanking({ env: {} });
  assert.deepEqual(after.body.ranking, ["linear"]);

  // Redis REST pipeline integration works when KV env vars are set
  const calls = [];
  const redisEnv = {
    KV_REST_API_URL: "https://kv.example.upstash.io",
    KV_REST_API_TOKEN: "test-secret",
  };
  await recordFavoriteToggle(
    { id: "cursor", action: "add" },
    {
      clientKey: "203.0.113.20",
      env: redisEnv,
      fetchImpl: async (url, init) => {
        const cmds = JSON.parse(init.body);
        calls.push({ url, cmds });
        if (cmds[0][0] === "SADD") {
          return { ok: true, json: async () => [{ result: 1 }, { result: 3 }] };
        }
        return { ok: true, json: async () => [{ result: 1 }] };
      },
    },
  );
  assert.equal(calls.length, 2);
  assert.equal(calls[0].cmds[0][0], "SADD");
  assert.deepEqual(calls[1].cmds[0], ["ZADD", "designtaste:favorites", "3", "cursor"]);
});

test("gallery defaults to favorite-weighted popular order without showing favorite counts", async () => {
  const lastId = sites[sites.length - 1].id;
  const secondLastId = sites[sites.length - 2].id;
  const posted = [];
  const d = dom(gallery(sites), "https://designtaste.wtf/");
  d.window.matchMedia = () => ({ matches: false, addEventListener() {} });
  d.window.fetch = async (url, init) => {
    if (init?.method === "POST") {
      posted.push({ url, body: JSON.parse(init.body) });
      return { ok: true, json: async () => ({ ok: true }) };
    }
    return {
      ok: true,
      json: async () => ({ ok: true, ranking: [lastId, secondLastId] }),
    };
  };
  d.window.eval(script);
  // Allow fetch microtask chain to resolve
  await new Promise((r) => setTimeout(r, 15));

  const doc = d.window.document;
  assert.equal(doc.querySelector("#sort").value, "popular");
  const orderedIds = [...doc.querySelectorAll(".site-card")].map((c) => c.dataset.id);
  assert.equal(orderedIds[0], lastId);
  assert.equal(orderedIds[1], secondLastId);
  // Favorite counts are never displayed on cards
  for (const btn of doc.querySelectorAll(".save-btn")) {
    assert.equal(btn.textContent.trim(), "");
  }

  // Clicking save syncs to /api/favorites/
  doc.querySelector(`.site-card[data-id="${lastId}"] .save-btn`).click();
  assert.equal(posted.length, 1);
  assert.equal(posted[0].url, "/api/favorites/");
  assert.deepEqual(posted[0].body, { id: lastId, action: "add" });
  d.window.close();
});

test("shared lists API validates catalog IDs, sanitizes titles, and loads saved moodboards", async () => {
  resetListsState();
  assert.equal((await createSavedList({ ids: ["nonexistent-site"] }, { env: {} })).status, 400);
  assert.equal((await createSavedList({ ids: [] }, { env: {} })).status, 400);

  const created = await createSavedList(
    { ids: ["linear", "anywr", "linear"], title: "Dark <script> SaaS" },
    { clientKey: "198.51.100.7", env: {} },
  );
  assert.equal(created.status, 201);
  assert.match(created.body.id, /^dt_[a-z0-9]{8}$/);
  assert.deepEqual(created.body.ids, ["linear", "anywr"]);
  assert.equal(created.body.title, "Dark script SaaS");

  const loaded = await getSavedList(created.body.id, { env: {} });
  assert.equal(loaded.status, 200);
  assert.equal(loaded.body.list.sites.length, 2);
  assert.equal(loaded.body.list.sites[0].id, "linear");
  assert.equal((await getSavedList("dt_doesnotexist", { env: {} })).status, 404);
  assert.equal((await getSavedList("../bad", { env: {} })).status, 400);
});

test("open MCP server handles initialize, icons, MCP Apps UI, tools, saved lists, and resources", async () => {
  resetListsState();
  const init = await handleMcpMessage({
    jsonrpc: "2.0",
    id: 1,
    method: "initialize",
    params: { protocolVersion: "2025-11-25" },
  });
  assert.equal(init.result.serverInfo.name, "designtaste");
  assert.equal(init.result.serverInfo.title, "DesignTaste");
  assert.equal(init.result.protocolVersion, "2025-11-25");
  assert.ok(
    init.result.serverInfo.icons.some((i) => i.src === "https://designtaste.wtf/icon-192.png"),
  );
  assert.ok(
    init.result.capabilities.extensions["io.modelcontextprotocol/ui"].mimeTypes.includes(
      "text/html;profile=mcp-app",
    ),
  );

  const tools = await handleMcpMessage({
    jsonrpc: "2.0",
    id: 2,
    method: "tools/list",
  });
  const toolNames = tools.result.tools.map((t) => t.name);
  for (const name of [
    "browse_gallery",
    "search_sites",
    "get_site",
    "find_similar_sites",
    "discover_random",
    "list_categories",
    "get_saved_list",
    "create_saved_list",
    "submit_site",
  ]) {
    assert.ok(toolNames.includes(name), `missing tool ${name}`);
  }
  const browseTool = tools.result.tools.find((t) => t.name === "browse_gallery");
  assert.equal(browseTool._meta.ui.resourceUri, "ui://designtaste/app.html");
  assert.equal(browseTool._meta["openai/outputTemplate"], "ui://designtaste/app.html");

  const uiRes = await handleMcpMessage({
    jsonrpc: "2.0",
    id: 20,
    method: "resources/read",
    params: { uri: "ui://designtaste/app.html" },
  });
  const uiDoc = uiRes.result.contents[0];
  assert.equal(uiDoc.mimeType, "text/html;profile=mcp-app");
  assert.ok(uiDoc.text.includes("ui/initialize"));
  assert.deepEqual(uiDoc._meta.ui.csp.resourceDomains, ["https://designtaste.wtf"]);

  const browse = await handleMcpMessage(
    {
      jsonrpc: "2.0",
      id: 21,
      method: "tools/call",
      params: { name: "browse_gallery", arguments: { category: "AI tools", limit: 6 } },
    },
    { env: {} },
  );
  assert.equal(browse.result.structuredContent.kind, "gallery");
  assert.equal(browse.result.structuredContent.sites.length, 6);

  const similar = await handleMcpMessage(
    {
      jsonrpc: "2.0",
      id: 22,
      method: "tools/call",
      params: { name: "find_similar_sites", arguments: { id: "linear", limit: 4 } },
    },
    { env: {} },
  );
  assert.equal(similar.result.structuredContent.kind, "gallery");
  assert.equal(similar.result.structuredContent.sites.length, 4);
  assert.ok(!similar.result.structuredContent.sites.some((s) => s.id === "linear"));

  const random = await handleMcpMessage(
    {
      jsonrpc: "2.0",
      id: 23,
      method: "tools/call",
      params: { name: "discover_random", arguments: { count: 4 } },
    },
    { env: {} },
  );
  assert.equal(random.result.structuredContent.mode, "random");
  assert.equal(random.result.structuredContent.sites.length, 4);

  const search = await handleMcpMessage(
    {
      jsonrpc: "2.0",
      id: 3,
      method: "tools/call",
      params: { name: "search_sites", arguments: { query: "anywr", limit: 5 } },
    },
    { env: {} },
  );
  const parsedSearch = JSON.parse(search.result.content[0].text);
  assert.ok(parsedSearch.sites.some((s) => s.id === "anywr"));

  const made = await handleMcpMessage(
    {
      jsonrpc: "2.0",
      id: 4,
      method: "tools/call",
      params: {
        name: "create_saved_list",
        arguments: { ids: ["anywr", "linear"], title: "Agent Moodboard" },
      },
    },
    { env: {}, clientKey: "198.51.100.8" },
  );
  const madeJson = JSON.parse(made.result.content[0].text);
  assert.match(madeJson.id, /^dt_[a-z0-9]{8}$/);
  assert.equal(made.result.structuredContent.kind, "list");

  const fetched = await handleMcpMessage(
    {
      jsonrpc: "2.0",
      id: 5,
      method: "tools/call",
      params: { name: "get_saved_list", arguments: { id: madeJson.id } },
    },
    { env: {} },
  );
  const fetchedJson = JSON.parse(fetched.result.content[0].text);
  assert.deepEqual(fetchedJson.ids, ["anywr", "linear"]);
  assert.equal(fetched.result.structuredContent.kind, "list");

  const mcpPage = dom(info("mcp"));
  assert.match(mcpPage.window.document.body.textContent, /https:\/\/designtaste\.wtf\/api\/mcp\//);
  mcpPage.window.close();
});

test("outbound links include ref=designtaste.wtf and preserve Referer while keeping canonical URLs clean", () => {
  const sellbird = sites.find((s) => s.id === "sellbird");
  assert.ok(sellbird, "sellbird should be in catalog");
  assert.equal(sellbird.url, "https://sellbird.ai/");

  const homeDom = dom(gallery(sites));
  const card = homeDom.window.document.querySelector('[data-id="sellbird"]');
  const previewLink = card.querySelector("a.preview");
  const titleLink = card.querySelector("a.site-name");
  assert.equal(previewLink.getAttribute("href"), "https://sellbird.ai/?ref=designtaste.wtf");
  assert.equal(titleLink.getAttribute("href"), "https://sellbird.ai/?ref=designtaste.wtf");
  assert.equal(previewLink.getAttribute("rel"), "noopener");
  assert.equal(titleLink.getAttribute("rel"), "noopener");
  homeDom.window.close();

  const detailDom = dom(detail(sellbird, sites));
  const visitBtn = detailDom.window.document.querySelector(".detail-actions a.btn-primary");
  const shareBtn = detailDom.window.document.querySelector(".detail-actions [data-share-site]");
  const heroLink = detailDom.window.document.querySelector("a.detail-image");
  assert.ok(shareBtn, "detail page should expose Share card trigger");
  assert.equal(shareBtn.getAttribute("data-site-id"), "sellbird");
  assert.equal(visitBtn.getAttribute("href"), "https://sellbird.ai/?ref=designtaste.wtf");
  assert.equal(heroLink.getAttribute("href"), "https://sellbird.ai/?ref=designtaste.wtf");
  assert.equal(visitBtn.getAttribute("rel"), "noopener");
  const ldJson = JSON.parse(
    detailDom.window.document.querySelector('script[type="application/ld+json"]').textContent,
  );
  assert.equal(ldJson.about.url, "https://sellbird.ai/");
  detailDom.window.close();
});

test("scroll-motion sites expose lazy hover video previews, detail video players, and validated video hashes", async () => {
  const anywr = sites.find((s) => s.id === "anywr");
  assert.ok(anywr?.video, "anywr should have a recorded scroll video");
  assert.equal(anywr.video, "assets/anywr.mp4");
  assert.equal(anywr.imageDimensions.width, 1280);
  assert.equal(anywr.imageDimensions.height, 800);

  const homeDom = dom(gallery(sites));
  const card = homeDom.window.document.querySelector('[data-id="anywr"]');
  const preview = card.querySelector("a.preview");
  assert.equal(preview.getAttribute("data-video"), "/assets/anywr.mp4");
  assert.ok(preview.classList.contains("has-video"));
  assert.equal(preview.querySelector("video"), null, "video should load lazily on hover/focus");
  assert.ok(preview.querySelector(".preview-motion-badge"));
  homeDom.window.close();

  const detailDom = dom(detail(anywr, sites));
  const vid = detailDom.window.document.querySelector("video.detail-video");
  assert.ok(vid, "detail page should render recorded scroll video");
  assert.equal(vid.getAttribute("src"), "/assets/anywr.mp4");
  assert.equal(vid.getAttribute("poster"), "/assets/anywr.jpg");
  assert.ok(detailDom.window.document.querySelector("[data-detail-video-toggle]"));
  detailDom.window.close();

  await assert.rejects(
    validateSites(
      sites.map((s) => (s.id === "anywr" ? { ...s, videoSha256: "0".repeat(64) } : s)),
      root,
    ),
    /video hash does not match/,
  );
});