330 lines · 20.5 KB · TypeScriptRaw
/** * One assistant address for everyone (owner, 6 Nov 2026): a person connects * Claude, ChatGPT or any MCP client at https://<open host>/mcp and signs in * with their number and code in the browser; the door finds or makes the * number's database, and that object's own OAuth code does the rest * (src/open.ts, src/oauth.ts). */import { SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { REGISTRATIONS_PER_HOUR, SIGN_UPS_PER_HOUR } from "../src/directory.ts";import { ADMIN, personalObject } from "./personal.ts";const OPEN = "https://cottondb.com";const REDIRECT = "https://claude.ai/api/mcp/auth_callback";const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";let ips = 0;/** A network of its own, so one test's counts never reach another's. */function network(): string { ips += 1; return `203.0.113.${ips}`;}let numbers = 0;/** A synthetic number no other test signs in with. */function number(): string { numbers += 1; return `+9190007${String(numbers).padStart(5, "0")}`;}function get(url: string, headers: Record<string, string> = {}): Promise<Response> { return SELF.fetch(url, { redirect: "manual", headers });}function post(url: string, body: Record<string, string>, headers: Record<string, string> = {}): Promise<Response> { return SELF.fetch(url, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", ...headers }, body: new URLSearchParams(body).toString() });}async function s256(verifier: string): Promise<string> { const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))); return btoa(String.fromCharCode(...digest)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}function verifier(): string { const bytes = crypto.getRandomValues(new Uint8Array(40)); return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** The hidden fields of a page's form. */function fields(html: string): Record<string, string> { const out: Record<string, string> = {}; for (const m of html.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)) out[m[1]!] = m[2]!.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&"); return out;}async function register(ip = network(), base = OPEN): Promise<string> { const res = await SELF.fetch(`${base}/oauth/register`, { method: "POST", headers: { "content-type": "application/json", "cf-connecting-ip": ip }, body: JSON.stringify({ client_name: "Claude", redirect_uris: [REDIRECT], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }), }); expect(res.status, await res.clone().text()).toBe(201); return ((await res.json()) as { client_id: string }).client_id;}function query(clientId: string, challenge: string, extra: Record<string, string> = {}): URLSearchParams { return new URLSearchParams({ client_id: clientId, redirect_uri: REDIRECT, response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state: "st-1", scope: "owner", resource: `${OPEN}/mcp`, ...extra });}/** The phone page, then the number: answers the code page (or whatever refused the number). */async function askCode(clientId: string, challenge: string, phone: string, ip: string, headers: Record<string, string> = {}): Promise<Response> { const start = await get(`${OPEN}/oauth/authorize?${query(clientId, challenge)}`, { "cf-connecting-ip": ip, ...headers }); const html = await start.text(); expect(start.status, html).toBe(200); return post(`${OPEN}/oauth/authorize`, { ...fields(html), phone }, { "cf-connecting-ip": ip, ...headers });}interface Grant { databaseId: string; access: string; refresh: string;}/** A number's whole connection on the open host: the code, the redirect, the redemption. */async function connect(clientId: string, phone: string, ip = network()): Promise<Grant> { const v = verifier(); const sent = await askCode(clientId, await s256(v), phone, ip); const html = await sent.text(); expect(sent.status, html).toBe(200); expect(html).toContain(`Enter the code sent to ${phone}`); const proved = await post(`${OPEN}/oauth/authorize`, { ...fields(html), code: "123456" }, { "cf-connecting-ip": ip }); expect(proved.status, await proved.clone().text()).toBe(302); const to = new URL(proved.headers.get("location")!); expect(`${to.origin}${to.pathname}`).toBe(REDIRECT); expect(to.searchParams.get("state")).toBe("st-1"); const code = to.searchParams.get("code")!; const named = new RegExp(`^ctc_(${UUID})_`).exec(code); expect(named, code.slice(0, 4)).not.toBeNull(); const redeemed = await redeem(clientId, code, v); expect(redeemed.status, JSON.stringify(redeemed.body)).toBe(200); const databaseId = named![1]!; expect(String(redeemed.body.access_token).startsWith(`ctn_${databaseId}_`)).toBe(true); expect(String(redeemed.body.refresh_token).startsWith(`ctr_${databaseId}_`)).toBe(true); return { databaseId, access: String(redeemed.body.access_token), refresh: String(redeemed.body.refresh_token) };}async function redeem(clientId: string, code: string, v: string, redirect = REDIRECT): Promise<{ status: number; body: Record<string, unknown> }> { const res = await post(`${OPEN}/oauth/token`, { grant_type: "authorization_code", client_id: clientId, code, code_verifier: v, redirect_uri: redirect, resource: `${OPEN}/mcp` }); return { status: res.status, body: (await res.json()) as Record<string, unknown> };}async function refresh(clientId: string, token: string): Promise<{ status: number; body: Record<string, unknown> }> { const res = await post(`${OPEN}/oauth/token`, { grant_type: "refresh_token", client_id: clientId, refresh_token: token }); return { status: res.status, body: (await res.json()) as Record<string, unknown> };}/** One JSON-RPC call at the one address. */async function rpc<T = Record<string, unknown>>(token: string, method: string, params: Record<string, unknown> = {}, headers: Record<string, string> = {}): Promise<{ status: number; body: { result?: T; error?: unknown } }> { const res = await SELF.fetch(`${OPEN}/mcp`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}`, ...headers }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) }); const text = await res.text(); return { status: res.status, body: text ? JSON.parse(text) : {} };}async function callTool(token: string, name: string, args: Record<string, unknown> = {}): Promise<string> { const res = await rpc<{ content: { text: string }[]; isError?: boolean }>(token, "tools/call", { name, arguments: args }); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(res.body.result?.isError, JSON.stringify(res.body)).toBeFalsy(); return res.body.result!.content.map((c) => c.text).join("\n");}/** RULE (owner, 6 Nov 2026): every person connects their assistant at one address, https://cottondb.com/mcp, and signs in with their number and code; no per-person URL, no pasted token. */describe("the one address speaks MCP authorization", () => { it("challenges /mcp with no bearer, a stranger's bearer, or one naming no database, with where to sign in", async () => { const metadata = `resource_metadata="${OPEN}/.well-known/oauth-protected-resource/mcp"`; const none = await SELF.fetch(`${OPEN}/mcp`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }) }); expect(none.status).toBe(401); expect(none.headers.get("www-authenticate")).toBe(`Bearer ${metadata}, scope="owner"`); expect(await none.json()).toMatchObject({ code: "no_database" }); expect((await get(`${OPEN}/mcp`)).headers.get("www-authenticate")).toBe(`Bearer ${metadata}, scope="owner"`); for (const token of ["junk", "ctn_00000000-0000-4000-8000-000000000000_abcdef"]) { const res = await SELF.fetch(`${OPEN}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}` }, body: "{}" }); expect(res.status, token).toBe(401); expect(res.headers.get("www-authenticate"), token).toBe(`Bearer error="invalid_token", ${metadata}, scope="owner"`); } // A /v1 call is no MCP client's: no challenge there. expect((await SELF.fetch(`${OPEN}/v1/sync`)).headers.get("www-authenticate")).toBeNull(); }); it("publishes both documents on the open host itself, in both spellings, naming only it", async () => { for (const path of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) { const res = await get(`${OPEN}${path}`); expect(res.status, path).toBe(200); expect(await res.json(), path).toEqual({ resource: `${OPEN}/mcp`, authorization_servers: [OPEN], scopes_supported: ["owner"], bearer_methods_supported: ["header"], resource_name: "Cotton" }); } for (const path of ["/.well-known/oauth-authorization-server", "/.well-known/oauth-authorization-server/mcp"]) { const res = await get(`${OPEN}${path}`); expect(res.headers.get("access-control-allow-origin")).toBe("*"); expect(await res.json(), path).toMatchObject({ issuer: OPEN, authorization_endpoint: `${OPEN}/oauth/authorize`, token_endpoint: `${OPEN}/oauth/token`, registration_endpoint: `${OPEN}/oauth/register`, code_challenge_methods_supported: ["S256"] }); } expect((await SELF.fetch(`${OPEN}/oauth/token`, { method: "OPTIONS" })).status).toBe(204); }); it("leaves the site every other well-known path and its pages", async () => { for (const path of ["/.well-known/openid-configuration", "/oauth", "/oauth/other", "/privacy"]) { const res = await get(`${OPEN}${path}`); expect(res.headers.get("x-test-site"), path).toBe("1"); expect(await res.text(), path).toBe(`site: GET ${path}`); } });});describe("two people at the one address", () => { it("each signs in to a database of their own, made for an unknown number, with one client registered once", async () => { const clientId = await register(); const [phoneA, phoneB] = [number(), number()]; const a = await connect(clientId, phoneA); const b = await connect(clientId, phoneB); expect(a.databaseId).not.toBe(b.databaseId); // Each number's database is the one the directory made for it: the phone's own sign-in finds the same one. for (const [grant, phone] of [[a, phoneA], [b, phoneB]] as const) { const code = await SELF.fetch(`${OPEN}/v1/code`, { method: "POST", headers: { "content-type": "application/json", "cf-connecting-ip": network() }, body: JSON.stringify({ phone, device_id: "phone-1" }) }); expect(code.status).toBe(200); expect(await code.json()).toMatchObject({ database_id: grant.databaseId }); } // A real client's session: initialize, tools/list, brief, one write and one read. const init = await rpc<{ serverInfo: { name: string; title: string }; instructions: string }>(a.access, "initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "test", version: "1" } }); expect(init.status).toBe(200); expect(init.body.result!.serverInfo).toMatchObject({ name: "cotton", title: "Cotton" }); expect(init.body.result!.instructions.split("\n")[0]).toBe(JSON.stringify({ database: { id: a.databaseId, name: "Personal" }, app: "Cotton" })); expect(init.body.result!.instructions).toContain("this person's own database"); const listed = await rpc<{ tools: { name: string }[] }>(a.access, "tools/list"); // A new connection carries the narrowest useful set (ADMIN KEYS 2): its memory and sessions, no app's table. expect(listed.body.result!.tools.map((t) => t.name)).toEqual(expect.arrayContaining(["brief", "remember", "recall"])); await callTool(a.access, "brief", { machine: "synthetic" }); const todo = await rpc<{ content: { text: string }[]; isError?: boolean }>(a.access, "tools/call", { name: "create_todo", arguments: { title: "A's synthetic todo" } }); expect([todo.body.result?.isError, todo.body.result?.content[0]?.text]).toEqual([true, expect.stringContaining("does not write todo")]); // B is a database of its own, and A's secret under B's database id is refused. await callTool(b.access, "brief", { machine: "synthetic" }); const forged = `ctn_${b.databaseId}_${a.access.split("_").at(-1)!}`; expect((await rpc(forged, "tools/list")).status).toBe(401); // The Worker's own headers, sent from outside, are dropped: A's token still lands in A's database. const steered = await rpc<{ instructions: string }>(a.access, "initialize", {}, { "x-cotton-business": `p-${b.databaseId}`, "x-cotton-prefix": `/b/p-${b.databaseId}` }); expect(steered.body.result!.instructions.split("\n")[0]).toContain(a.databaseId); }); it("refuses A's code at B: a challenge proven at another database, and a code renamed to it", async () => { const clientId = await register(); const b = await connect(clientId, number()); // A asks for a code, then posts the code step naming B's database. const ip = network(); const v = verifier(); const sent = await askCode(clientId, await s256(v), number(), ip); const html = await sent.text(); const atB = await post(`${OPEN}/oauth/authorize`, { ...fields(html), database_id: b.databaseId, code: "123456" }, { "cf-connecting-ip": ip }); expect(atB.status).toBe(401); expect(await atB.text()).toContain("Invalid or expired code."); // A's own redirect code, renamed to B's database, is no code there. const proved = await post(`${OPEN}/oauth/authorize`, { ...fields(html), code: "123456" }, { "cf-connecting-ip": ip }); expect(proved.status).toBe(302); const code = new URL(proved.headers.get("location")!).searchParams.get("code")!; const renamed = code.replace(/^ctc_[^_]+_/, `ctc_${b.databaseId}_`); expect(await redeem(clientId, renamed, v)).toEqual({ status: 400, body: { error: "invalid_grant", error_description: "authorization code is not valid" } }); expect((await redeem(clientId, code, v)).status).toBe(200); }); it("rotates on refresh, inside A's database only; a refresh renamed to B's yields nothing", async () => { const clientId = await register(); const a = await connect(clientId, number()); const b = await connect(clientId, number()); const renamed = a.refresh.replace(/^ctr_[^_]+_/, `ctr_${b.databaseId}_`); expect(await refresh(clientId, renamed)).toEqual({ status: 400, body: { error: "invalid_grant", error_description: "refresh token is not valid" } }); const next = await refresh(clientId, a.refresh); expect(next.status, JSON.stringify(next.body)).toBe(200); expect(String(next.body.access_token).startsWith(`ctn_${a.databaseId}_`)).toBe(true); expect(String(next.body.refresh_token).startsWith(`ctr_${a.databaseId}_`)).toBe(true); expect((await rpc(a.access, "tools/list")).status).toBe(401); expect((await rpc(String(next.body.access_token), "tools/list")).status).toBe(200); // The spent one, replayed, ends the connection. expect((await refresh(clientId, a.refresh)).body.error).toBe("invalid_grant"); expect((await rpc(String(next.body.access_token), "tools/list")).status).toBe(401); // B's connection is untouched by all of it. expect((await rpc(b.access, "tools/list")).status).toBe(200); });});describe("the open host's checks", () => { it(`makes at most ${SIGN_UPS_PER_HOUR} databases from one network, and says so on the page`, async () => { const clientId = await register(); const ip = network(); const challenge = await s256(verifier()); for (let i = 0; i < SIGN_UPS_PER_HOUR; i++) expect((await askCode(clientId, challenge, number(), ip)).status).toBe(200); const refused = await askCode(clientId, challenge, number(), ip); expect(refused.status).toBe(429); const html = await refused.text(); expect(html).toContain("Too many new accounts from this network in the last hour; try again later."); expect(html).toContain('name="step" value="phone"'); }); it(`registers at most ${REGISTRATIONS_PER_HOUR} clients from one network an hour`, async () => { const ip = network(); for (let i = 0; i < REGISTRATIONS_PER_HOUR; i++) await register(ip); const res = await SELF.fetch(`${OPEN}/oauth/register`, { method: "POST", headers: { "content-type": "application/json", "cf-connecting-ip": ip }, body: JSON.stringify({ redirect_uris: [REDIRECT] }) }); expect(res.status).toBe(429); expect(await register()).toMatch(/^cc_/); }); it("speaks plainly to any person, at phone width, and ignores a forged prefix", async () => { const clientId = await register(); const res = await get(`${OPEN}/oauth/authorize?${query(clientId, await s256(verifier()))}`, { "x-cotton-prefix": "/b/someone", "x-cotton-business": "someone" }); const html = await res.text(); expect(res.status, html).toBe(200); expect(html).toContain('<meta name="viewport" content="width=device-width, initial-scale=1">'); expect(html).toContain("<h1>Connect to Cotton</h1>"); expect(html).toContain("Enter your phone number and Cotton sends it a code."); expect(html).not.toContain("owner's phone"); expect(html).toContain(`action="${OPEN}/oauth/authorize"`); }); it("holds PKCE and the redirect as strictly as an object's own host", async () => { const bad = await SELF.fetch(`${OPEN}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ redirect_uris: ["http://claude.ai/callback"] }) }); expect(bad.status).toBe(400); expect(await bad.json()).toMatchObject({ error: "invalid_redirect_uri" }); const clientId = await register(); const elsewhere = await get(`${OPEN}/oauth/authorize?${query(clientId, await s256(verifier()), { redirect_uri: "https://evil.example/cb" })}`); expect(elsewhere.status).toBe(400); expect(await elsewhere.text()).toContain("did not register"); const unknown = await get(`${OPEN}/oauth/authorize?${query("cc_nobody", await s256(verifier()))}`); expect(unknown.status).toBe(400); const plain = await get(`${OPEN}/oauth/authorize?${query(clientId, "x".repeat(43), { code_challenge_method: "plain" })}`); expect(plain.status).toBe(302); expect(new URL(plain.headers.get("location")!).searchParams.get("error")).toBe("invalid_request"); const elsewhereResource = await get(`${OPEN}/oauth/authorize?${query(clientId, await s256(verifier()), { resource: "https://elsewhere.example/mcp" })}`); expect(new URL(elsewhereResource.headers.get("location")!).searchParams.get("error")).toBe("invalid_target"); // A wrong verifier spends the code. const ip = network(); const v = verifier(); const html = await (await askCode(clientId, await s256(v), number(), ip)).text(); const proved = await post(`${OPEN}/oauth/authorize`, { ...fields(html), code: "123456" }, { "cf-connecting-ip": ip }); const code = new URL(proved.headers.get("location")!).searchParams.get("code")!; expect((await redeem(clientId, code, verifier())).body.error).toBe("invalid_grant"); expect((await redeem(clientId, code, v)).body.error).toBe("invalid_grant"); // Another client's code is not this one's. expect((await redeem("cc_nobody", code, v)).status).toBe(401); expect((await post(`${OPEN}/oauth/token`, { grant_type: "password", client_id: clientId })).status).toBe(400); }); it("knows one client at the open host and a named host alike: one registry, the directory's (STRANGER BLIND, 24 Nov 2026)", async () => { await personalObject("oneaddr"); const open = await register(); const named = await register(network(), "https://example.test/b/oneaddr"); const challenge = await s256(verifier()); const page = async (url: string) => { const res = await get(url); return { status: res.status, phone: (await res.text()).includes('name="phone"') }; }; const atNamed = (client: string) => `https://example.test/b/oneaddr/oauth/authorize?${new URLSearchParams({ client_id: client, redirect_uri: REDIRECT, response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state: "st-1" })}`; expect((await page(atNamed(open))).phone, "the open host's client at a named host").toBe(true); expect((await page(`${OPEN}/oauth/authorize?${query(named, challenge)}`)).phone, "a named host's client at the open host").toBe(true); expect((await page(atNamed("cc_nobody"))).phone, "a client nobody registered").toBe(false); // The admin token is no MCP sign-in at the one address. expect((await rpc(ADMIN.authorization.replace(/^Bearer /, ""), "tools/list")).status).toBe(401); });});