Cotton code
122 lines · 7.3 KB · TypeScriptRaw
/** * The open host is the site's address too (owner, 27 Oct 2026): the door * keeps its own business and hands the site Worker (SITE) everything else, * unchanged both ways (src/open.ts `forSite`). */import { env, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Env } from "../src/env.ts";import { forSite, openDoor } from "../src/open.ts";const OPEN = "https://cottondb.com";type Seen = { method: string; url: string; headers: [string, string][]; body: string };/** A SITE that keeps what reached it and answers a page of its own. */function stubSite(): { site: Fetcher; seen: Seen[] } {  const seen: Seen[] = [];  const site = {    async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {      const request = new Request(input as RequestInfo, init);      seen.push({ method: request.method, url: request.url, headers: [...request.headers], body: new TextDecoder().decode(await request.arrayBuffer()) });      return new Response(`<!doctype html><title>${new URL(request.url).pathname}</title>`, {        status: 200,        headers: { "content-type": "text/html; charset=utf-8", "x-site": "cotton-site", "cache-control": "public, max-age=60", "content-security-policy": "default-src 'self'" },      });    },  } as unknown as Fetcher;  return { site, seen };}const withSite = (site: Fetcher | undefined): Env => ({ ...(env as unknown as Env), SITE: site });describe("forSite: which requests on the open host are the site's", () => {  it("gives the site its pages, assets, waitlist and Mac feed", () => {    for (const path of ["/", "/privacy", "/privacy/", "/terms", "/beta", "/testers", "/docs", "/docs/connect-claude", "/api/waitlist", "/_health", "/mac/appcast.xml", "/mac/download/latest", "/mac/download/Cotton-1.0.zip", "/mac/runner/forgejo-runner-arm64", "/m/someone", "/404.html", "/brand/og.png", "/assets/index-abc.js", "/.well-known/openid-configuration", "/.well-known/apple-app-site-association", "/.well-known/oauth-protected-resourcex", "/oauth", "/oauth/other", "/v1beta", "/mcpx", "/internal"]) {      expect(forSite(path, null), path).toBe(true);    }  });  it("keeps the door's own paths, with or without a bearer", () => {    for (const path of ["/v1", "/v1/code", "/v1/sign-in", "/v1/admin/directory", "/v1/google/callback", "/v1/sync", "/mcp", "/mcp/", "/mcp/sse", "/health", "/internal/mcp-call", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp", "/.well-known/oauth-authorization-server", "/.well-known/oauth-authorization-server/mcp", "/oauth/register", "/oauth/authorize", "/oauth/token"]) {      expect(forSite(path, null), path).toBe(false);      expect(forSite(path, "Bearer ctd_x"), path).toBe(false);    }  });  it("keeps any request carrying Authorization, whatever its path", () => {    for (const path of ["/", "/privacy", "/anything", "/api/waitlist"]) {      expect(forSite(path, "Bearer ctd_x"), path).toBe(false);      expect(forSite(path, ""), path).toBe(false);    }  });});describe("the open door hands the site its pages", () => {  it("passes / and /privacy to SITE unchanged, and its answer back untouched", async () => {    const { site, seen } = stubSite();    for (const path of ["/", "/privacy"]) {      const res = await openDoor(new Request(`${OPEN}${path}?ref=consent`, { headers: { accept: "text/html", "user-agent": "synthetic-browser", "cf-connecting-ip": "198.51.100.200" } }), withSite(site));      expect(res.status).toBe(200);      expect(res.headers.get("x-site")).toBe("cotton-site");      expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");      expect(res.headers.get("cache-control")).toBe("public, max-age=60");      expect(res.headers.get("content-security-policy")).toBe("default-src 'self'");      expect(await res.text()).toBe(`<!doctype html><title>${path}</title>`);    }    expect(seen.map((r) => [r.method, r.url])).toEqual([      ["GET", `${OPEN}/?ref=consent`],      ["GET", `${OPEN}/privacy?ref=consent`],    ]);    expect(Object.fromEntries(seen[1]!.headers)).toEqual({ accept: "text/html", "user-agent": "synthetic-browser", "cf-connecting-ip": "198.51.100.200" });  });  it("passes a waitlist POST with its body", async () => {    const { site, seen } = stubSite();    const res = await openDoor(new Request(`${OPEN}/api/waitlist`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "email=someone%40example.com" }), withSite(site));    expect(res.status).toBe(200);    expect(seen).toEqual([{ method: "POST", url: `${OPEN}/api/waitlist`, headers: [["content-type", "application/x-www-form-urlencoded"]], body: "email=someone%40example.com" }]);  });  it("keeps its own business: /v1/code, /mcp, a bearer anywhere, /internal/", async () => {    const { site, seen } = stubSite();    const door = withSite(site);    const code = await openDoor(new Request(`${OPEN}/v1/code`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ phone: "12345", device_id: "d" }) }), door);    expect(code.status).toBe(400);    expect(await code.json()).toMatchObject({ code: "bad_phone" });    const mcp = await openDoor(new Request(`${OPEN}/mcp`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }), door);    expect(mcp.status).toBe(401);    expect(mcp.headers.get("www-authenticate")).toBe(`Bearer resource_metadata="${OPEN}/.well-known/oauth-protected-resource/mcp", scope="owner"`);    expect(await mcp.json()).toMatchObject({ code: "no_database" });    const anything = await openDoor(new Request(`${OPEN}/anything`, { headers: { authorization: "Bearer not-a-cotton-token" } }), door);    expect(anything.status).toBe(401);    expect(await anything.json()).toMatchObject({ code: "no_database" });    const named = await openDoor(new Request(`${OPEN}/`, { headers: { authorization: "Bearer ctd_00000000-0000-4000-8000-000000000000_abcdef" } }), door);    expect(named.status).toBe(401);    expect(await named.json()).toMatchObject({ code: "invalid_credential" });    const internal = await openDoor(new Request(`${OPEN}/internal/x`), door);    expect(internal.status).toBe(404);    expect(await internal.json()).toMatchObject({ code: "not_found" });    expect(seen).toEqual([]);  });  it("answers a typed 503 when no site is bound, never a page", async () => {    const res = await openDoor(new Request(`${OPEN}/privacy`), withSite(undefined));    expect(res.status).toBe(503);    expect(res.headers.get("content-type")).toContain("application/json");    expect(await res.json()).toEqual({ code: "no_site", message: "the site Worker is not bound" });  });  it("splits the same way through the Worker itself", async () => {    const privacy = await SELF.fetch(`${OPEN}/privacy`);    expect(privacy.headers.get("x-test-site")).toBe("1");    expect(await privacy.text()).toBe("site: GET /privacy");    expect(await (await SELF.fetch(`${OPEN}/`)).text()).toBe("site: GET /");    // Another host's request never reaches the site.    expect((await SELF.fetch("https://elsewhere.example/privacy")).headers.get("x-test-site")).toBeNull();    expect((await SELF.fetch(`${OPEN}/health`)).status).toBe(200);    expect(await (await SELF.fetch(`${OPEN}/mcp`, { method: "POST", body: "{}" })).json()).toMatchObject({ code: "no_database" });    expect((await SELF.fetch(`${OPEN}/internal/x`)).status).toBe(404);  });});