Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
15.7 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from "vitest";
import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
import { NextRequest, type NextFetchEvent } from "next/server";
import { MULTICA_LOCALE_HEADER } from "./lib/locale-routing";
import { config, proxy } from "./proxy";

function makeRequest(
  path: string,
  cookies: Record<string, string> = {},
  host = "app.multica.test",
) {
  const cookieHeader = Object.entries(cookies)
    .map(([key, value]) => `${key}=${value}`)
    .join("; ");

  return new NextRequest(`https://${host}${path}`, {
    headers: cookieHeader ? { cookie: cookieHeader } : undefined,
  });
}

function redirectLocation(
  path: string,
  cookies: Record<string, string> = {},
  host?: string,
) {
  return proxy(makeRequest(path, cookies, host)).headers.get("location");
}

function restoreEnv(key: string, value: string | undefined) {
  if (value === undefined) delete process.env[key];
  else process.env[key] = value;
}

function withoutRuntimeUpstreams(run: () => void) {
  const previousRemoteApiUrl = process.env.REMOTE_API_URL;
  const previousDocsUrl = process.env.DOCS_URL;
  const previousPublicApiUrl = process.env.NEXT_PUBLIC_API_URL;
  const previousPort = process.env.PORT;
  delete process.env.REMOTE_API_URL;
  delete process.env.DOCS_URL;
  delete process.env.NEXT_PUBLIC_API_URL;
  process.env.PORT = "3000";

  try {
    run();
  } finally {
    restoreEnv("REMOTE_API_URL", previousRemoteApiUrl);
    restoreEnv("DOCS_URL", previousDocsUrl);
    restoreEnv("NEXT_PUBLIC_API_URL", previousPublicApiUrl);
    restoreEnv("PORT", previousPort);
  }
}

describe("proxy legacy workspace route redirects", () => {
  const sessionCookies = {
    multica_logged_in: "1",
    last_workspace_slug: "acme",
  };

  it.each([
    ["issues", "/acme/issues"],
    ["projects", "/acme/projects"],
    ["agents", "/acme/agents"],
    ["squads", "/acme/squads"],
    ["inbox", "/acme/inbox"],
    ["my-issues", "/acme/my-issues"],
    ["autopilots", "/acme/autopilots"],
    ["runtimes", "/acme/runtimes"],
    ["skills", "/acme/skills"],
    ["settings", "/acme/settings"],
    ["usage", "/acme/usage"],
  ])(
    "redirects legacy /%s URLs through the last workspace slug",
    (segment, expectedPath) => {
      expect(redirectLocation(`/${segment}?tab=all`, sessionCookies)).toBe(
        `https://app.multica.test${expectedPath}?tab=all`,
      );
    },
  );

  it("preserves nested legacy paths and query strings", () => {
    expect(
      redirectLocation("/squads/squad-123?view=members", sessionCookies),
    ).toBe("https://app.multica.test/acme/squads/squad-123?view=members");
  });

  it("sends logged-out legacy URLs to login", () => {
    expect(redirectLocation("/usage?tab=billing")).toBe(
      "https://app.multica.test/login?tab=billing",
    );
  });

  it("sends logged-in legacy URLs without a last workspace cookie to login", () => {
    // Not root: the root-path rule below leaves "/" on the public site for the
    // official marketing hosts even with a session, so bouncing there would
    // dead-end on the landing page. /login resolves against the workspace list
    // instead. The deep-link query is dropped because feeding a legacy path
    // back through `next` would return here and loop.
    expect(
      redirectLocation("/squads?view=members", { multica_logged_in: "1" }),
    ).toBe("https://app.multica.test/login");
  });

  it.each(["multica.ai", "www.multica.ai"])(
    "resolves a slugless session off the marketing host %s instead of stranding it",
    (host) => {
      expect(
        redirectLocation("/inbox", { multica_logged_in: "1" }, host),
      ).toBe(`https://${host}/login`);
    },
  );

  it("does not redirect workspace-scoped URLs whose first segment is already a slug", () => {
    expect(redirectLocation("/acme/squads", sessionCookies)).toBeNull();
  });

  it("redirects app-host root URLs to the last workspace", () => {
    expect(redirectLocation("/", sessionCookies)).toBe(
      "https://app.multica.test/acme/issues",
    );
  });

  it.each(["multica.ai", "www.multica.ai"])(
    "does not redirect public marketing root on %s",
    (host) => {
      expect(redirectLocation("/", sessionCookies, host)).toBeNull();
    },
  );

  it("still redirects explicit legacy app routes on the public marketing host", () => {
    expect(redirectLocation("/issues/ABC-123", sessionCookies, "multica.ai")).toBe(
      "https://multica.ai/acme/issues/ABC-123",
    );
  });
});

describe("proxy runtime upstream rewrites", () => {
  it("matches globally versioned Plugin API requests", () => {
    expect(config.matcher).toContain("/v1/:path*");
  });

  it("does not rewrite API requests when no runtime API origin is configured", () => {
    withoutRuntimeUpstreams(() => {
      const res = proxy(makeRequest("/api/config?x=1"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBeNull();
      expect(
        res.headers.get(`x-middleware-request-${MULTICA_LOCALE_HEADER}`),
      ).toBe("en");
    });
  });

  it("does not rewrite Plugin API requests when no runtime API origin is configured", () => {
    withoutRuntimeUpstreams(() => {
      const res = proxy(makeRequest("/v1/context?x=1"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBeNull();
    });
  });

  it("does not rewrite docs requests when no runtime docs origin is configured", () => {
    withoutRuntimeUpstreams(() => {
      const res = proxy(makeRequest("/docs/zh"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBeNull();
      expect(
        res.headers.get(`x-middleware-request-${MULTICA_LOCALE_HEADER}`),
      ).toBe("en");
    });
  });

  it("rewrites API requests to the runtime API origin", () => {
    const previous = process.env.REMOTE_API_URL;
    process.env.REMOTE_API_URL = "http://backend:8080";
    try {
      const res = proxy(makeRequest("/api/config?x=1"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBe(
        "http://backend:8080/api/config?x=1",
      );
    } finally {
      restoreEnv("REMOTE_API_URL", previous);
    }
  });

  it("rewrites the CLI health probe to the runtime API origin", () => {
    const previous = process.env.REMOTE_API_URL;
    process.env.REMOTE_API_URL = "http://backend:8080";
    try {
      const res = proxy(makeRequest("/health"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBe(
        "http://backend:8080/health",
      );
    } finally {
      restoreEnv("REMOTE_API_URL", previous);
    }
  });

  it("rewrites Plugin API requests to the runtime API origin", () => {
    const previous = process.env.REMOTE_API_URL;
    process.env.REMOTE_API_URL = "http://backend:8080";
    try {
      const res = proxy(makeRequest("/v1/issues/MUL-6581?x=1"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBe(
        "http://backend:8080/v1/issues/MUL-6581?x=1",
      );
    } finally {
      restoreEnv("REMOTE_API_URL", previous);
    }
  });

  it("rewrites docs requests to the runtime docs origin", () => {
    const previous = process.env.DOCS_URL;
    process.env.DOCS_URL = "http://docs:4000";
    try {
      const res = proxy(makeRequest("/docs/zh/agents"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBe(
        "http://docs:4000/docs/zh/agents",
      );
    } finally {
      restoreEnv("DOCS_URL", previous);
    }
  });

  it("rewrites websocket requests to the runtime API origin", () => {
    const previous = process.env.REMOTE_API_URL;
    process.env.REMOTE_API_URL = "http://backend:8080";
    try {
      const res = proxy(makeRequest("/ws"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBe(
        "http://backend:8080/ws",
      );
    } finally {
      restoreEnv("REMOTE_API_URL", previous);
    }
  });

  it("does not rewrite frontend auth callback pages", () => {
    const previous = process.env.REMOTE_API_URL;
    process.env.REMOTE_API_URL = "http://backend:8080";
    try {
      const res = proxy(makeRequest("/auth/callback"));

      expect(res.status).toBe(200);
      expect(res.headers.get("x-middleware-rewrite")).toBeNull();
      expect(
        res.headers.get(`x-middleware-request-${MULTICA_LOCALE_HEADER}`),
      ).toBe("en");
    } finally {
      restoreEnv("REMOTE_API_URL", previous);
    }
  });
});

describe("proxy root and locale handling", () => {
  it("redirects logged-in root visits to the last workspace", () => {
    const res = proxy(
      makeRequest("/", {
        multica_logged_in: "1",
        last_workspace_slug: "acme",
      }),
    );

    expect(res.status).toBe(307);
    expect(res.headers.get("location")).toBe(
      "https://app.multica.test/acme/issues",
    );
  });

  it("forwards locale on login requests", () => {
    const res = proxy(makeRequest("/login", { "multica-locale": "zh-Hans" }));

    expect(res.status).toBe(200);
    expect(res.headers.get("location")).toBeNull();
    expect(
      res.headers.get(`x-middleware-request-${MULTICA_LOCALE_HEADER}`),
    ).toBe("zh-Hans");
  });
});

describe("proxy marketing-site language URLs", () => {
  const localeOf = (res: Response) => res.headers.get(`x-middleware-request-${MULTICA_LOCALE_HEADER}`);
  const withAcceptLanguage = (path: string, acceptLanguage: string) =>
    new NextRequest(`https://www.multica.ai${path}`, { headers: { "accept-language": acceptLanguage } });

  it.each([
    ["/zh", "/", "zh-Hans"],
    ["/zh/download", "/download", "zh-Hans"],
    ["/ko/usecases/auto-data-analysis", "/usecases/auto-data-analysis", "ko"],
    ["/ja/about?ref=x", "/about?ref=x", "ja"],
  ])("serves %s as %s in its language", (path, page, locale) => {
    const res = proxy(makeRequest(path, { "multica-locale": "en" }));

    expect(res.headers.get("location")).toBeNull();
    expect(res.headers.get("x-middleware-rewrite")).toBe(`https://app.multica.test${page}`);
    expect(localeOf(res)).toBe(locale);
  });

  it("keeps English URLs English for visitors who have not picked a language", () => {
    const res = proxy(withAcceptLanguage("/download", "zh-CN,zh;q=0.9"));

    expect(res.headers.get("location")).toBeNull();
    expect(res.headers.get("x-middleware-rewrite")).toBeNull();
    expect(localeOf(res)).toBe("en");
  });

  it("keeps locales without a translated site on the English URL", () => {
    const res = proxy(makeRequest("/about", { "multica-locale": "fr" }));

    expect(res.headers.get("location")).toBeNull();
    expect(localeOf(res)).toBe("fr");
  });

  it.each([
    ["/", { "multica-locale": "zh-Hans" }, "/zh"],
    ["/download?started=mac", { "multica-locale": "ko" }, "/ko/download?started=mac"],
    ["/about", { "multica-locale": "zh-Hant" }, "/zh/about"],
  ])("sends %s to the language the visitor picked", (path, cookies, location) => {
    expect(redirectLocation(path, cookies, "www.multica.ai")).toBe(`https://www.multica.ai${location}`);
  });

  it("leaves app routes under a language-like slug to the app", () => {
    const res = proxy(makeRequest("/zh/issues", { "multica-locale": "ja" }));

    expect(res.headers.get("x-middleware-rewrite")).toBeNull();
    expect(localeOf(res)).toBe("ja");
  });

  it("keeps the bare root of an existing workspace with a language slug", () => {
    const res = proxy(makeRequest("/ko", { multica_logged_in: "1", last_workspace_slug: "ko" }));

    expect(res.headers.get("x-middleware-rewrite")).toBeNull();
  });
});


describe("upload route bypasses the buffering proxy", () => {
  it.each(["/api/upload-file", "/api/upload-file/"])(
    "excludes %s from Proxy matching",
    (url) => expect(unstable_doesMiddlewareMatch({ config, url })).toBe(false),
  );

  it.each(["/api", "/api/config", "/api/upload-file-extra", "/v1/issues", "/auth/token", "/docs/intro", "/login"])(
    "keeps the existing proxy behavior for %s",
    (url) => expect(unstable_doesMiddlewareMatch({ config, url })).toBe(true),
  );
});

describe("proxy AI visit log", () => {
  const CLAUDE_BOT = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; [email protected])";
  const visit = (path: string, headers: Record<string, string>, host = "www.multica.ai") =>
    proxy(new NextRequest(`https://${host}${path}`, { headers }));
  const loggedLines = (info: { mock: { calls: unknown[][] } }) =>
    info.mock.calls.map((call) => JSON.parse(String(call[0])) as Record<string, unknown>);

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it.each(["/llms.txt", "/robots.txt"])("observes %s without changing the response", (url) => {
    expect(unstable_doesMiddlewareMatch({ config, url })).toBe(true);
    vi.spyOn(console, "info").mockImplementation(() => {});
    const res = visit(url, { "user-agent": CLAUDE_BOT });
    expect(res.headers.get("x-middleware-next")).toBe("1");
    expect(res.headers.get("x-middleware-rewrite")).toBeNull();
  });

  it("logs AI crawlers on marketing pages and root crawler files", () => {
    const info = vi.spyOn(console, "info").mockImplementation(() => {});
    visit("/download", { "user-agent": CLAUDE_BOT, cookie: "multica_logged_in=1" });
    visit("/zh/about", { "user-agent": "ChatGPT-User/1.0" });
    visit("/llms.txt", { "user-agent": "curl/8.7.1" });

    expect(loggedLines(info)).toEqual([
      expect.objectContaining({ app: "web", path: "/download", agent: "ClaudeBot", format: "html", status: null }),
      expect.objectContaining({ path: "/zh/about", agent: "ChatGPT-User" }),
      expect.objectContaining({ path: "/llms.txt", signal: "markdown-request", format: "markdown" }),
    ]);
    expect(JSON.stringify(info.mock.calls)).not.toContain("multica_logged_in");
  });

  it("trusts the Host header over the address the server is bound to", () => {
    const info = vi.spyOn(console, "info").mockImplementation(() => {});
    visit("/llms.txt", { "user-agent": CLAUDE_BOT, host: "multica.ai" }, "localhost:3000");
    visit("/llms.txt", { "user-agent": CLAUDE_BOT, host: "localhost:3000" }, "localhost:3000");
    expect(loggedLines(info)).toEqual([expect.objectContaining({ path: "/llms.txt", agent: "ClaudeBot" })]);
  });

  it("retains visits in PostHog after the response when a key is configured", () => {
    vi.spyOn(console, "info").mockImplementation(() => {});
    vi.stubEnv("POSTHOG_API_KEY", "phc_test");
    const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
    const waitUntil = vi.fn();
    try {
      const req = new NextRequest("https://www.multica.ai/llms.txt", { headers: { "user-agent": CLAUDE_BOT } });
      proxy(req, { waitUntil } as unknown as NextFetchEvent);
    } finally {
      vi.unstubAllEnvs();
    }
    expect(waitUntil).toHaveBeenCalledWith(expect.any(Promise));
    expect(fetchMock).toHaveBeenCalledWith("https://us.i.posthog.com/batch/", expect.anything());
  });

  it("records the redirect status the proxy answers with", () => {
    const info = vi.spyOn(console, "info").mockImplementation(() => {});
    visit("/about", { "user-agent": "GPTBot/1.1", cookie: "multica-locale=ko" });
    expect(loggedLines(info)).toEqual([expect.objectContaining({ path: "/about", status: 307 })]);
  });

  it("skips browsers, app routes, docs, and other hosts", () => {
    const info = vi.spyOn(console, "info").mockImplementation(() => {});
    visit("/", {
      "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
      "sec-fetch-mode": "navigate",
    });
    visit("/acme/issues", { "user-agent": CLAUDE_BOT });
    visit("/docs/agents", { "user-agent": CLAUDE_BOT });
    visit("/download", { "user-agent": CLAUDE_BOT }, "app.multica.test");
    expect(info).not.toHaveBeenCalled();
  });
});