Cotton code
131 lines · 9.9 KB · TypeScriptRaw
/** * STRANGER BLIND (coordinator, 23 Nov 2026): to a stranger, a personal database answers exactly as a database that * does not exist answers, route by route, so nothing says whether one is there. Its own people are served as before. */import { runInDurableObject, env, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { personalObject } from "./personal.ts";const REAL = "blind-real";const MISSING = "blind-missing";const REDIRECT = "https://claude.ai/api/mcp/auth_callback";const STRANGER = "+15550100777";interface Answer { status: number; text: string; challenge: string | null }async function ask(slug: string, method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<Answer> {  const form = typeof body === "string";  const res = await SELF.fetch(`https://example.test/b/${slug}${path}`, {    method,    headers: { "content-type": form ? "application/x-www-form-urlencoded" : "application/json", ...headers },    body: body === undefined ? undefined : form ? (body as string) : JSON.stringify(body),    redirect: "manual",  });  const text = (await res.text())    .replaceAll(slug, "<slug>")    .replace(/cc_[A-Za-z0-9_-]+/g, "cc_<id>")    .replace(/"client_id_issued_at":\d+/g, '"client_id_issued_at":0');  return { status: res.status, text, challenge: res.headers.get("www-authenticate")?.replaceAll(slug, "<slug>") ?? null };}async function version(slug: string): Promise<unknown[]> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_o, state) => state.storage.sql.exec("SELECT key, value FROM meta").toArray());}describe("a stranger at a personal database's door", () => {  it("is answered as where no database is, on every route a stranger reaches", async () => {    await personalObject(REAL);    const before = await version(MISSING);    const clients: Record<string, string> = {};    for (const slug of [REAL, MISSING]) {      const res = await SELF.fetch(`https://example.test/b/${slug}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: [REDIRECT] }) });      expect(res.status).toBe(201);      clients[slug] = ((await res.json()) as { client_id: string }).client_id;    }    const authorize = (client: string) => `client_id=${client}&redirect_uri=${encodeURIComponent(REDIRECT)}&response_type=code&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&state=s1`;    const asks: [string, (slug: string, client: string) => Promise<Answer>][] = [      ["definitions", (s) => ask(s, "GET", "/v1/definitions")],      ["definitions, a made-up credential", (s) => ask(s, "GET", "/v1/definitions", undefined, { authorization: "Bearer ctd_nobody_x" })],      ["a code", (s) => ask(s, "POST", "/v1/code", { phone: STRANGER, device_id: "d" })],      ["a sign-in", (s) => ask(s, "POST", "/v1/sign-in", { challenge_id: "00000000-0000-0000-0000-000000000000", code: "123456", device_id: "d" })],      ["a pass", (s) => ask(s, "GET", "/v1/sync")],      ["a pass, a made-up credential", (s) => ask(s, "GET", "/v1/sync", undefined, { authorization: "Bearer ctd_nobody_x" })],      ["an act", (s) => ask(s, "POST", "/v1/act", { act: "create", table: "todo", data: {} })],      ["me", (s) => ask(s, "GET", "/v1/me")],      ["/mcp by GET", (s) => ask(s, "GET", "/mcp")],      ["/mcp with no token", (s) => ask(s, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" })],      ["/mcp with a made-up token", (s) => ask(s, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, { authorization: "Bearer ctn_x_y" })],      ["the server document", (s) => ask(s, "GET", "/.well-known/oauth-authorization-server")],      ["the connect page", (s, c) => ask(s, "GET", `/oauth/authorize?${authorize(c)}`)],      ["the connect page, an unknown client", (s) => ask(s, "GET", `/oauth/authorize?${authorize("cc_nobody")}`)],      ["the phone step, a stranger's number", (s, c) => ask(s, "POST", "/oauth/authorize", `${authorize(c)}&step=phone&phone=${encodeURIComponent(STRANGER)}`)],      ["the code step, a made-up challenge", (s, c) => ask(s, "POST", "/oauth/authorize", `${authorize(c)}&step=code&phone=${encodeURIComponent(STRANGER)}&challenge_id=00000000-0000-0000-0000-000000000000&device_id=oauth:x&code=123456`)],      ["a token, a made-up code", (s, c) => ask(s, "POST", "/oauth/token", `grant_type=authorization_code&client_id=${c}&code=ctc_x_y&redirect_uri=${encodeURIComponent(REDIRECT)}&code_verifier=${"a".repeat(43)}`)],      ["a token, a made-up refresh", (s, c) => ask(s, "POST", "/oauth/token", `grant_type=refresh_token&client_id=${c}&refresh_token=ctr_x_y`)],      ["a token, an unknown client", (s) => ask(s, "POST", "/oauth/token", "grant_type=refresh_token&client_id=cc_nobody&refresh_token=ctr_x_y")],      // AUDIT B (28 Nov 2026, attacker 1): the allowlist's change was answered `bad_list` at a real door and      // `invalid_credential` where no database is.      ["the allowlist's change, an empty body", (s) => ask(s, "POST", "/v1/allowlist", {})],      ["the allowlist's change, an unsigned statement", (s) => ask(s, "POST", "/v1/allowlist", { list: [], nonce: "a".repeat(22), issued_at: new Date().toISOString(), signer: "made-up", sig: "x" })],    ];    for (const [named, asking] of asks) {      const real = await asking(REAL, clients[REAL]!);      const missing = await asking(MISSING, clients[MISSING]!);      expect(real, named).toEqual(missing);    }    // Asking where no database is made none: nothing was kept.    expect(await version(MISSING)).toEqual(before);  });});describe("the coordinator's call on live, through the front Worker on the open host", () => {  it("answers a stranger's code at a real personal door as at a made-up one", async () => {    const OPEN = "https://cottondb.com";    const post = async (path: string, body: unknown, ip: string) => {      const res = await SELF.fetch(`${OPEN}${path}`, { method: "POST", headers: { "content-type": "application/json", "cf-connecting-ip": ip }, body: JSON.stringify(body) });      return { status: res.status, body: (await res.json()) as Record<string, unknown> };    };    // A person signs up at the door, as a phone does: their database is p-<id>.    const code = await post("/v1/code", { phone: "+15550100701", device_id: "phone-1" }, "203.0.113.71");    expect(code.status, JSON.stringify(code.body)).toBe(200);    const id = String(code.body.database_id);    const signed = await post("/v1/sign-in", { database_id: id, challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-1" }, "203.0.113.71");    expect(signed.status, JSON.stringify(signed.body)).toBe(200);    // A stranger at that door, and at a door nobody has.    const madeUp = "6f1c2b9e-0d4a-4c1e-9b7a-2f3e4d5c6b7a";    const real = await post(`/b/p-${id}/v1/code`, { phone: STRANGER, device_id: "x" }, "203.0.113.72");    const missing = await post(`/b/p-${madeUp}/v1/code`, { phone: STRANGER, device_id: "x" }, "203.0.113.73");    expect([real.status, JSON.stringify(real.body).replaceAll(id, "<id>")]).toEqual([missing.status, JSON.stringify(missing.body).replaceAll(madeUp, "<id>")]);    expect(JSON.stringify(real.body)).not.toContain("not_owner");  });});/** Every route of the families only a signed-in device reaches (24 Nov 2026). */const SIGNED_ONLY: [string, string][] = [  ["GET", "/v1/recovery"], ["GET", "/v1/recovery/help"], ["GET", "/v1/recovery/help/ask"], ["POST", "/v1/recovery/help/answer"], ["POST", "/v1/recovery/help/ask"], ["POST", "/v1/recovery/open"], ["POST", "/v1/recovery/retire"], ["POST", "/v1/recovery/set"],  ["GET", "/v1/approvals"], ["POST", "/v1/approvals/nonce"], ["POST", "/v1/approvals/wrong"], ["POST", "/v1/approvals/approve"], ["POST", "/v1/approvals/refuse"], ["POST", "/v1/approvals/ask"], ["GET", "/v1/approvals/x"],  ["GET", "/v1/passkeys"], ["POST", "/v1/passkeys"], ["POST", "/v1/passkeys/options"], ["POST", "/v1/passkeys/sign-in"], ["DELETE", "/v1/passkeys/x"],  ["GET", "/v1/chat/inbox"], ["GET", "/v1/chat/keys"], ["GET", "/v1/chat/people"], ["GET", "/v1/chat/reach"], ["POST", "/v1/chat/ack"], ["POST", "/v1/chat/discover"], ["POST", "/v1/chat/group"], ["POST", "/v1/chat/group/send"], ["POST", "/v1/chat/keys"], ["POST", "/v1/chat/prekeys"], ["POST", "/v1/chat/prekeys/claim"], ["POST", "/v1/chat/send"], ["POST", "/v1/chat/socket"],  ["GET", "/v1/invite/inbox"], ["POST", "/v1/invite/send"], ["POST", "/v1/invite/taken"],  ["GET", "/v1/send/inbox"], ["GET", "/v1/send/key"], ["GET", "/v1/send/people"], ["GET", "/v1/send/offer"], ["POST", "/v1/send/decline"], ["POST", "/v1/send/keep"], ["POST", "/v1/send/key"], ["POST", "/v1/send/landed"], ["POST", "/v1/send/make"], ["POST", "/v1/send/trust"], ["POST", "/v1/send/undo"], ["POST", "/v1/send/weigh"],  ["GET", "/v1/shared/list"], ["GET", "/v1/shared/lists"], ["POST", "/v1/shared/lists"], ["POST", "/v1/shared/list/item"],  ["GET", "/v1/agents/feed"], ["POST", "/v1/agents/chat"], ["POST", "/v1/agents/done"],  ["GET", "/v1/calls/blocked"], ["GET", "/v1/calls/ice"], ["POST", "/v1/calls"], ["POST", "/v1/calls/block"], ["POST", "/v1/calls/device"], ["GET", "/v1/calls/x"],];describe("the routes only a signed-in device reaches", () => {  it("answer a stranger at a personal database as where no database is: sign in first", { timeout: 600_000 }, async () => {    await personalObject("blind-families");    for (const [method, path] of SIGNED_ONLY) {      const asked = async (slug: string) => {        const res = await SELF.fetch(`https://example.test/b/${slug}${path}`, { method, headers: { "content-type": "application/json" }, body: method === "GET" ? undefined : "{}" });        return [res.status, (await res.text()).replaceAll(slug, "<slug>")];      };      const real = await asked("blind-families");      expect(real, `${method} ${path}`).toEqual(await asked("blind-families-missing"));      expect(real[0], `${method} ${path}`).toBe(401);    }  });});