import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("MCP requested read scope caps Auto and Full access approvals", WEB, async ({ t3, app, browser, screen }) => {
  const workspace = await t3.project("OAuth scope demonstration");
  await mkdir(`${workspace}/created-through-mcp`);
  await t3.open();
  const origin = app.baseUrl!;
  const cookie = (await browser.cookies()).map(c => `${c.name}=${c.value}`).join("; ");
  const post = async (path: string, body: unknown) => {
    const response = await fetch(`${origin}${path}`, { method: "POST", headers: { "content-type": "application/json", cookie }, body: JSON.stringify(body) });
    const result = await response.json();
    if (!response.ok) throw new Error(`${path}: ${response.status} ${JSON.stringify(result)}`);
    return result;
  };
  const verifier = "oauth-scope-proof-verifier-abcdefghijklmnopqrstuvwxyz-0123456789";
  const client = await post("/oauth/mcp/register", { client_name: "Read-only scope demonstration", redirect_uris: ["http://localhost:51234/callback"], grant_types: ["authorization_code"], token_endpoint_auth_method: "none" });
  const authorization = { response_type: "code", client_id: client.client_id, redirect_uri: "http://localhost:51234/callback", code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", state: "scope-proof", resource: `${origin}/mcp`, scope: "orchestration:read" };
  const handoff = await fetch(`${origin}/oauth/mcp/authorize?${new URLSearchParams(authorization)}`, { redirect: "manual" });
  await app.open(handoff.headers.get("location")!);
  await screen.getByRole("button", "Approve Read only").textContent();
  await app.screenshot("read-only-request-consent");
  const results = [];
  for (const access of ["auto", "full-access"]) {
    const details = await post("/oauth/mcp/approval", authorization);
    const decision = await post("/oauth/mcp/decision", { authorization, decision: { _tag: "browser-session", access, csrfToken: details.csrfToken } });
    const tokenResponse = await fetch(`${origin}/oauth/mcp/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code: new URL(decision.redirectTo).searchParams.get("code")!, redirect_uri: authorization.redirect_uri, client_id: client.client_id, code_verifier: verifier, resource: authorization.resource }) });
    const token = await tokenResponse.json();
    let session: string | null = null;
    const rpc = async (method: string, params: unknown, id: number) => {
      const response = await fetch(`${origin}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token.access_token}`, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session } : {}) }, body: JSON.stringify({ jsonrpc: "2.0", id, method, params }) });
      session = response.headers.get("mcp-session-id") ?? session;
      const text = await response.text();
      const data = text.startsWith("event:") || text.startsWith("data:") ? text.split("\n").filter(l => l.startsWith("data: ")).map(l => l.slice(6)).join("") : text;
      return JSON.parse(data);
    };
    await rpc("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "scope-proof", version: "1" } }, 1);
    const listed = await rpc("tools/list", {}, 2);
    const refused = await rpc("tools/call", { name: "t3_thread_send", arguments: { threadId: "scope-proof-nonexistent", message: "Read-only clients must not send" } }, 3);
    const projectCall = await rpc("tools/call", { name: "t3_project_create", arguments: { title: "Created through read-only OAuth request", workspaceRoot: `${workspace}/created-through-mcp` } }, 4);
    const projectText = JSON.stringify(projectCall);
    const projectCreation = projectText.includes("capability_denied") ? "capability_denied" : projectCall.result?.isError ? "other error" : "project created";
    results.push({ projectCreation, requestedScope: authorization.scope, approverChoice: access, grantedScope: token.scope, consentRequestedAccess: details.requestedAccess ?? "not supplied", listedToolNames: listed.result?.tools?.map((t: { name: string }) => t.name), writeToolCall: refused });
  }
  console.log("OAUTH SCOPE PROOF", JSON.stringify(results, null, 2));
  await writeFile(`/tmp/factory-issue-38296-evidence-2/oauth-${Date.now()}.json`, JSON.stringify(results, null, 2));
  for (const result of results) {
    expect(result.grantedScope).toBe("orchestration:read");
    expect(result.listedToolNames).not.toContain("t3_thread_send");
    expect(JSON.stringify(result.writeToolCall)).toContain("capability_denied");
  }
});
