Cotton code
212 lines · 12.8 KB · TypeScriptRaw
/** * Walk the one assistant address as a real MCP client does (owner, 6 Nov 2026): * *   pnpm -s --filter @cottondb/business mcp-walk --base <open host> --otp-file <path> [--out <dir>] * * For two fresh synthetic numbers, each: discover the sign-in from the 401 at * /mcp, read both documents, register (once, for both), open the authorize * page, type the number, type the code, redeem the code with PKCE, then * `initialize`, `tools/list`, `brief`, one write and one read. Then: the * second number never sees the first's row, the first's secret under the * second's database is refused, a refresh rotates (the old token dies, the * new one works) and a replayed refresh ends the connection. * * --base      the Worker's open host, or `dev` for the dev Worker (config/dev-server.json) * --otp-file  the fixed development code; read, never printed * --out       where steps.json goes (default: print the steps only) * * Nothing secret is printed or written: a code or token is shown as its prefix. * Never point it at the live Worker. */import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import path from "node:path";import { devBase } from "./dev-server";const REDIRECT = "http://127.0.0.1:33418/callback";export class WalkFailed extends Error {}/** The hidden fields of the authorize page's form. */export 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(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");  return out;}/** A secret shown as what it names: `ctn_<database id>_…`. */export function shown(secret: string): string {  const m = /^(ct[a-z]_[0-9a-f-]{36}_)/.exec(secret);  return m ? `${m[1]}…` : `${secret.slice(0, 4)}…`;}/** The resource metadata URL a 401's WWW-Authenticate names. */export function resourceMetadata(header: string | null): string | null {  return /resource_metadata="([^"]+)"/.exec(header ?? "")?.[1] ?? null;}/** A synthetic number in the walk's own range, fresh each run. */export function syntheticNumber(): string {  return `+9190009${String(Math.floor(Math.random() * 100_000)).padStart(5, "0")}`;}function b64url(bytes: Uint8Array): string {  return Buffer.from(bytes).toString("base64url");}async function s256(verifier: string): Promise<string> {  return b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));}interface Step {  step: string;  ok: boolean;  detail: string;}class Walk {  readonly base: string;  private readonly code: string;  readonly steps: Step[];  constructor(base: string, code: string, steps: Step[]) {    this.base = base;    this.code = code;    this.steps = steps;  }  note(step: string, ok: boolean, detail: string): void {    this.steps.push({ step, ok, detail });    console.log(`${ok ? "ok  " : "FAIL"} ${step}: ${detail}`);    if (!ok) throw new WalkFailed(`${step}: ${detail}`);  }  async discover(): Promise<{ authorize: string; token: string; register: string; resource: string }> {    const res = await fetch(`${this.base}/mcp`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }) });    const metadataUrl = resourceMetadata(res.headers.get("www-authenticate"));    this.note("401 names where to sign in", res.status === 401 && metadataUrl !== null, `${res.status} resource_metadata=${metadataUrl}`);    const pr = (await (await fetch(metadataUrl!)).json()) as { resource: string; authorization_servers: string[] };    this.note("protected-resource document", pr.resource === `${this.base}/mcp`, `resource=${pr.resource} servers=${pr.authorization_servers.join(",")}`);    const as = (await (await fetch(`${pr.authorization_servers[0]}/.well-known/oauth-authorization-server`)).json()) as Record<string, string>;    this.note("authorization-server document", as.issuer === this.base, `issuer=${as.issuer}`);    return { authorize: as.authorization_endpoint!, token: as.token_endpoint!, register: as.registration_endpoint!, resource: pr.resource };  }  async register(url: string): Promise<string> {    const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "mcp-walk", redirect_uris: [REDIRECT], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }) });    const body = (await res.json()) as { client_id?: string };    this.note("register", res.status === 201 && typeof body.client_id === "string", `${res.status}`);    return body.client_id!;  }  async connect(who: string, phone: string, ends: Awaited<ReturnType<Walk["discover"]>>, clientId: string): Promise<{ databaseId: string; access: string; refresh: string }> {    const verifier = b64url(crypto.getRandomValues(new Uint8Array(40)));    const q = new URLSearchParams({ client_id: clientId, redirect_uri: REDIRECT, response_type: "code", code_challenge: await s256(verifier), code_challenge_method: "S256", state: `walk-${who}`, scope: "owner", resource: ends.resource });    const start = await fetch(`${ends.authorize}?${q}`, { redirect: "manual" });    const startHtml = await start.text();    this.note(`${who}: phone page`, start.status === 200 && startHtml.includes("Connect to Cotton"), `${start.status}`);    const form = (body: Record<string, string>) => fetch(ends.authorize, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString() });    const sent = await form({ ...fields(startHtml), phone });    const sentHtml = await sent.text();    this.note(`${who}: code page`, sent.status === 200 && sentHtml.includes("Enter the code sent to"), `${sent.status}`);    const proved = await form({ ...fields(sentHtml), code: this.code });    const location = proved.headers.get("location");    const back = location ? new URL(location) : null;    const grant = back?.searchParams.get("code") ?? "";    this.note(`${who}: redirect with a code naming its database`, proved.status === 302 && back?.searchParams.get("state") === `walk-${who}` && /^ctc_[0-9a-f-]{36}_/.test(grant), `${proved.status} ${shown(grant)}`);    const tokens = await this.token(ends.token, { grant_type: "authorization_code", client_id: clientId, code: grant, code_verifier: verifier, redirect_uri: REDIRECT, resource: ends.resource });    const databaseId = grant.slice(4, 40);    this.note(`${who}: redeem`, tokens.status === 200 && tokens.access.startsWith(`ctn_${databaseId}_`) && tokens.refresh.startsWith(`ctr_${databaseId}_`), `${tokens.status} ${shown(tokens.access)} ${shown(tokens.refresh)}`);    return { databaseId, access: tokens.access, refresh: tokens.refresh };  }  async token(url: string, body: Record<string, string>): Promise<{ status: number; access: string; refresh: string; error: string }> {    const res = await fetch(url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString() });    const json = (await res.json()) as Record<string, string>;    return { status: res.status, access: json.access_token ?? "", refresh: json.refresh_token ?? "", error: json.error ?? "" };  }  async rpc(token: string, method: string, params: Record<string, unknown> = {}): Promise<{ status: number; result: Record<string, unknown> | null }> {    const res = await fetch(`${this.base}/mcp`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });    const text = await res.text();    return { status: res.status, result: res.ok && text ? ((JSON.parse(text) as { result?: Record<string, unknown> }).result ?? null) : null };  }  async tool(token: string, name: string, args: Record<string, unknown> = {}): Promise<{ ok: boolean; text: string }> {    const res = await this.rpc(token, "tools/call", { name, arguments: args });    const content = (res.result?.content as { text: string }[] | undefined) ?? [];    return { ok: res.status === 200 && !res.result?.isError, text: content.map((c) => c.text).join("\n") };  }}/** Every step lands in `steps` as it is taken, so a failed walk still says how far it got. */export async function walk(base: string, code: string, steps: Step[] = []): Promise<Step[]> {  const w = new Walk(base.replace(/\/+$/, ""), code, steps);  const ends = await w.discover();  const clientId = await w.register(ends.register);  const [phoneA, phoneB] = [syntheticNumber(), syntheticNumber()];  const a = await w.connect("A", phoneA, ends, clientId);  const init = await w.rpc(a.access, "initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "mcp-walk", version: "1" } });  const instructions = String(init.result?.instructions ?? "");  w.note("A: initialize", init.status === 200 && instructions.includes(a.databaseId) && instructions.includes("this person's own database"), `${JSON.stringify(init.result?.serverInfo)} ${instructions.split("\n")[0]}`);  const listed = await w.rpc(a.access, "tools/list");  const names = ((listed.result?.tools as { name: string }[] | undefined) ?? []).map((t) => t.name);  w.note("A: tools/list", names.includes("brief") && names.includes("create_todo"), `${names.length} tools`);  const brief = await w.tool(a.access, "brief", { machine: "mcp-walk" });  w.note("A: brief", brief.ok, `${brief.text.length} characters`);  const title = `mcp-walk ${new Date().toISOString()}`;  w.note("A: write (create_todo)", (await w.tool(a.access, "create_todo", { title })).ok, title);  const read = await w.tool(a.access, "list_todos");  w.note("A: read (list_todos)", read.ok && read.text.includes(title), "the todo is there");  const b = await w.connect("B", phoneB, ends, clientId);  w.note("B: its own database", b.databaseId !== a.databaseId, `${shown(`ctn_${b.databaseId}_x`)}`);  const bRead = await w.tool(b.access, "list_todos");  w.note("B: never sees A's todo", bRead.ok && !bRead.text.includes(title), "absent");  const forged = `ctn_${b.databaseId}_${a.access.split("_").at(-1)!}`;  w.note("A's secret under B's database is refused", (await w.rpc(forged, "tools/list")).status === 401, "401");  const renamed = await w.token(ends.token, { grant_type: "refresh_token", client_id: clientId, refresh_token: a.refresh.replace(/^ctr_[0-9a-f-]{36}_/, `ctr_${b.databaseId}_`) });  w.note("A's refresh under B's database yields nothing", renamed.status === 400 && renamed.error === "invalid_grant", `${renamed.status} ${renamed.error}`);  const next = await w.token(ends.token, { grant_type: "refresh_token", client_id: clientId, refresh_token: a.refresh });  w.note("A: refresh rotates", next.status === 200 && next.access.startsWith(`ctn_${a.databaseId}_`) && next.refresh !== a.refresh, `${next.status} ${shown(next.access)}`);  w.note("A: the old token is dead", (await w.rpc(a.access, "tools/list")).status === 401, "401");  w.note("A: the new token works", (await w.rpc(next.access, "tools/list")).status === 200, "200");  const replay = await w.token(ends.token, { grant_type: "refresh_token", client_id: clientId, refresh_token: a.refresh });  w.note("A: a replayed refresh ends the connection", replay.error === "invalid_grant" && (await w.rpc(next.access, "tools/list")).status === 401, `${replay.status} ${replay.error}`);  w.note("B: untouched", (await w.rpc(b.access, "tools/list")).status === 200, "200");  return w.steps;}function arg(argv: string[], name: string): string | undefined {  const i = argv.indexOf(`--${name}`);  return i >= 0 ? argv[i + 1] : undefined;}async function main(): Promise<void> {  const argv = process.argv.slice(2);  const asked = arg(argv, "base");  const base = asked === "dev" ? devBase() : asked;  const file = arg(argv, "otp-file");  if (!base || !file) throw new WalkFailed("--base <open host> and --otp-file <path> are required");  if (/cottondb\.com/.test(base)) throw new WalkFailed("never walk the live Worker: use the development one");  const code = readFileSync(file.replace(/^~(?=\/)/, homedir()), "utf8").trim();  const out = arg(argv, "out");  const steps: Step[] = [];  try {    await walk(base, code, steps);  } finally {    if (out) {      mkdirSync(out, { recursive: true });      writeFileSync(path.join(out, "steps.json"), `${JSON.stringify({ base, at: new Date().toISOString(), steps }, null, 2)}\n`);    }  }  console.log(`walked: ${steps.length} steps`);}if (import.meta.url === `file://${process.argv[1]}`) {  main().catch((error: unknown) => {    console.error(error instanceof Error ? error.message : error);    process.exit(1);  });}