diff --git a/docs/internal/mcp-existing-application-actor.md b/docs/internal/mcp-existing-application-actor.md index 66c992aa2..b24fefd3f 100644 --- a/docs/internal/mcp-existing-application-actor.md +++ b/docs/internal/mcp-existing-application-actor.md @@ -82,3 +82,62 @@ harness compatibility; this suite does not repeat the expiry-policy matrix. No source test proves deployment, intended-client authentication, native parity, SQL entitlement or live MCP availability. Those gates remain unchanged. + +## Inactive direct-SDK transport composition + +`handleProposedRegistrationMcpRequest` composes a request-local SDK server and +stateless JSON Streamable HTTP transport with the existing verifier and proposed +create/read domains. It is unregistered: current `/mcp`, its onboarding, catalogs +and delegated allowlists are unchanged. It has no production dependency factory. +Only server-owned proposed policy/storage dependencies may be supplied. There is +no adopted query mode or public registration endpoint. + +The exact original NextRequest is retained once; its body is read once and passed +to the SDK as `parsedBody`. No AuthInfo or token is manufactured. A frozen admission +observation is compared with each call's actual credential tuple (including key ID +or Privy subject), actor and workspace. Domain authentication runs independently; +a per-invocation port wrapper checks its actual actor/workspace and intended method +before invoking the original port. Nothing substitutes the earlier identity into a +fresh domain call. The domain exposes no credential tuple at that third observation, +so same-actor credential-only changes there are not claimed detectable. These are +observations, not atomic revocation or SQL entitlement checks. + +Internal source constants are 64KiB wire bytes, a five-second total body read, +a 30-second whole-request deadline, and a separately bounded one-second cleanup. +Authentication precedes body reads. All arrays and id-less tool calls are rejected +before effects; unsupported Accept/content type yield406/415; malformed JSON400, +oversize413, body timeout408 and whole-request timeout504. Abort yields408 when a +response can still be delivered. Cleanup uncertainty yields503. Early denial owns +and cancels unread input too. These are inactive source contracts, not deployed +limits or client acceptance. + +Media admission parses complete case-insensitive type tokens and quoted parameters. +Accept must explicitly allow both JSON and event-stream with valid positive quality; +wildcards do not replace that MCP requirement, and a zero-quality duplicate excludes +the type. Parameter text cannot establish a media type. After validation, only media +type tokens are lowercased on the same original request for the pinned SDK's own +case-sensitive checks. Parameters, credentials, protocol headers and body remain +intact; no reconstructed request or SDK check bypass is used. + +The real SDK uses JSON response mode. The owner closes server/transport before +returning a completed JSON response, including202 notifications and errors. Request +abort/deadline races bound every asynchronous stage and observe losing rejections; +closing alone cannot settle the SDK's pending JSON promise. No mcp-handler import, +adapter interval, global owner, session store or response-stream teardown claim is +introduced. A normal returned response body can be abandoned after SDK closure. + +The storage guard checks owner/request/SDK termination immediately before port +entry. Termination before entry prevents execution. Once storage starts, closing +HTTP does not roll it back: a lost response is an unknown outcome, retaining the +original operation/key/input, with no automatic retry. Domain work may settle after +transport cleanup; a never-settling dependency is not reported as settled merely +because the response deadline or process boundary ended. Controlled tests separately +release and await delayed domain/storage work. Known storage errors render fixed +messages, never mutable adapter exception details. + +The controlled `mcpTransport` and `mcpTransportLifecycle` suites exercise real SDK +client/server composition with synthetic credential and storage leaves. Existing +proposal containment and source/golden bindings remain unchanged. The cohesive +request-owner, bounded-reader and guard functions deliberately retain their local +state/control flow despite the review configuration's 50-line function guideline; +splitting that state into a generic lifecycle framework would obscure ownership. diff --git a/lib/applications/proposedRegistration/__tests__/mcpTransport.test.ts b/lib/applications/proposedRegistration/__tests__/mcpTransport.test.ts new file mode 100644 index 000000000..9441e88e8 --- /dev/null +++ b/lib/applications/proposedRegistration/__tests__/mcpTransport.test.ts @@ -0,0 +1,521 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; +import golden from "../../../../scripts/application-registration-proposal/receipt-golden.json"; +import { fixture } from "../../../../scripts/application-registration-proposal/setup"; +import { handleProposedRegistrationMcpRequest as handle } from "@/lib/mcp/applications/handleProposedRegistrationMcpRequest"; +import type { ProposedDependencies } from "../proposedRegistrationContract"; +import supabase from "@/lib/supabase/serverClient"; +import { ProposedStorageFailure } from "../proposedRegistrationContract"; +import { createHmac } from "node:crypto"; +import { guardProposedRegistrationStorage } from "@/lib/mcp/applications/guardProposedRegistrationStorage"; +import { verifyExistingApplicationMcpActor } from "@/lib/mcp/applications/verifyExistingApplicationMcpActor"; +import { createProposedRegistrationMcpLifetime } from "@/lib/mcp/applications/createProposedRegistrationMcpLifetime"; +import { NextResponse } from "next/server"; +vi.mock("@/lib/privy/getOrCreateAccountIdByAuthToken", () => ({ + getOrCreateAccountIdByAuthToken: () => { + throw new Error("Forbidden provisioning"); + }, +})); +const leaves = vi.hoisted(() => ({ + verifyAccess: vi.fn(), + privyCalls: 0, + driftAt: 0, + subject: "synthetic-subject", +})); +vi.mock("@/lib/oauth/getOAuthRuntime", () => ({ + getOAuthRuntime: () => ({ verifyAccess: leaves.verifyAccess }), +})); +vi.mock("@/lib/privy/client", () => ({ + default: { + utils: () => ({ + auth: () => ({ + verifyAuthToken: async (token: string) => { + if (token !== "synthetic-privy") throw new Error("PRIVATE_SENTINEL"); + leaves.privyCalls++; + leaves.subject = + leaves.privyCalls === leaves.driftAt ? "changed-subject" : "synthetic-subject"; + return { app_id: "synthetic-app", issuer: "privy.io", user_id: leaves.subject }; + }, + }), + }), + }, +})); +beforeEach(() => { + vi.stubEnv("OAUTH_ENABLED", "false"); + leaves.verifyAccess.mockReset().mockResolvedValue(undefined); + leaves.privyCalls = leaves.driftAt = 0; + leaves.subject = "synthetic-subject"; + fixture.keyId = "22222222-2222-4222-8222-222222222222"; + vi.stubGlobal( + "fetch", + vi.fn(async (url: unknown, options?: RequestInit) => { + expect(url).toBe(`https://api.privy.io/v1/users/${leaves.subject}`); + expect(options?.method).toBe("GET"); + expect(options?.headers).toEqual({ + "privy-app-id": "synthetic-app", + Authorization: `Basic ${btoa("synthetic-app:synthetic-registration-secret")}`, + }); + return { + ok: true, + json: async () => ({ + id: leaves.subject, + linked_accounts: [{ type: "email", address: "fixture@example.invalid" }], + }), + }; + }), + ); +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); +const deps = () => ({ + policy: { + status: "proposed_unadopted", + version: "proposed-personal-v1", + databaseHead: golden.databaseHead, + } as ProposedDependencies["policy"], + storage: { + create: vi.fn(async () => + structuredClone(golden.createReceipt), + ), + read: vi.fn(async () => + structuredClone(golden.readReceipt), + ), + }, +}); +const input = { + idempotency_key: golden.input.key, + expected_entitlement_revision: 1, + registration: { + name: golden.input.registration.name, + environment: "production", + allowed_origins: golden.input.registration.origins.map(o => o.origin), + return_urls: golden.input.registration.origins.flatMap(o => o.return_urls), + }, +}; +function request(body: unknown, token = fixture.key) { + return new NextRequest("https://fixture.invalid/mcp", { + method: "POST", + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + }, + body: JSON.stringify(body), + }); +} +it.each(["key", "privy"])( + "real client initializes, lists and calls shared domains (%s)", + async mechanism => { + const d = deps(); + const client = new Client({ name: "synthetic", version: "1" }); + const transport = new StreamableHTTPClientTransport(new URL("https://fixture.invalid/mcp"), { + requestInit: { + headers: { + Authorization: `Bearer ${mechanism === "key" ? fixture.key : "synthetic-privy"}`, + }, + }, + fetch: async (url, init) => + handle(new NextRequest(url instanceof Request ? url : String(url), init), d), + }); + try { + await client.connect(transport); + expect((await client.listTools()).tools.map(t => t.name).sort()).toEqual([ + "create_application_registration", + "read_application_registration", + ]); + const created = await client.callTool({ + name: "create_application_registration", + arguments: input, + }); + expect(created.isError).not.toBe(true); + expect(JSON.stringify(created)).not.toMatch( + /recoup_sk_|synthetic-privy|verificationEvidence|authToken/, + ); + expect(d.storage.create).toHaveBeenCalledExactlyOnceWith(golden.input); + const read = await client.callTool({ + name: "read_application_registration", + arguments: { + application_id: golden.readReceipt.application_id, + environment: "production", + receipt_id: golden.readReceipt.receipt_id, + }, + }); + expect(read.isError).not.toBe(true); + expect(d.storage.read).toHaveBeenCalledTimes(1); + } finally { + await client.close(); + } + }, +); +it("denies unknown identity before reading or provisioning during initialize", async () => { + fixture.accountPresent = false; + const req = request({ jsonrpc: "2.0", id: 1, method: "initialize" }, "synthetic-privy"); + const reader = vi.spyOn(req.body!, "getReader"); + expect((await handle(req, deps())).status).toBe(401); + expect(reader).not.toHaveBeenCalled(); +}); +it.each([ + [], + [{ jsonrpc: "2.0", id: 1, method: "tools/list" }], + { + jsonrpc: "2.0", + method: "tools/call", + params: { name: "create_application_registration", arguments: input }, + }, +])("rejects batch/id-less call before effects", async body => { + const parse = vi.spyOn(JSON, "parse"); + const d = deps(); + expect((await handle(request(body), d)).status).toBe(400); + // Pinned Vitest passes whole rows in a mixed object/array table. Prove wire input. + expect(parse).toHaveBeenCalledWith(JSON.stringify(body)); + expect(d.storage.create).not.toHaveBeenCalled(); +}); +it.each(["storage", "policy"])( + "read %s failure retains read-specific safe guidance", + async failure => { + const d = deps(); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + if (failure === "storage") d.storage.read.mockRejectedValue(new Error("PRIVATE_SENTINEL")); + else d.policy.version = "PRIVATE_SENTINEL" as typeof d.policy.version; + const result = await ( + await handle( + request( + call("read_application_registration", { + application_id: golden.readReceipt.application_id, + environment: "production", + receipt_id: golden.readReceipt.receipt_id, + }), + ), + d, + ) + ).json(); + expect(result.result.isError).toBe(true); + expect(JSON.stringify(result)).toContain("retain original read input"); + expect(JSON.stringify(result)).not.toMatch(/PRIVATE_SENTINEL|key and input/); + expect(d.storage.read).toHaveBeenCalledTimes(failure === "storage" ? 1 : 0); + expect(d.storage.create).not.toHaveBeenCalled(); + expect(errors).not.toHaveBeenCalled(); + }, +); +it("bounds bytes before SDK execution", async () => { + const r = request("x".repeat(65536)); + expect((await handle(r, deps())).status).toBe(413); +}); + +function call(name = "create_application_registration", args: unknown = input) { + return { jsonrpc: "2.0", id: 9, method: "tools/call", params: { name, arguments: args } }; +} +it.each(["create", "read"])( + "rejects key and domain actor drift before original %s storage", + async operation => { + for (const [observation, field] of [ + [2, "keyId"], + [2, "actor"], + [3, "actor"], + ] as const) { + fixture.actor = golden.input.actor; + fixture.keyId = "22222222-2222-4222-8222-222222222222"; + const original = supabase.from.bind(supabase); + let seen = 0; + const spy = vi.spyOn(supabase, "from").mockImplementation(table => { + if (++seen === observation) fixture[field] = "33333333-3333-4333-8333-333333333333"; + return original(table); + }); + const d = deps(); + const args = + operation === "create" + ? input + : { + application_id: golden.readReceipt.application_id, + environment: "production", + receipt_id: golden.readReceipt.receipt_id, + }; + try { + const response = await handle( + request(call(`${operation}_application_registration`, args)), + d, + ); + expect(response.status).toBe(200); + expect((await response.json()).result.isError).toBe(true); + expect(d.storage.create).not.toHaveBeenCalled(); + expect(d.storage.read).not.toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + } + }, +); +it("rejects observed Privy subject drift even when account stays the same", async () => { + leaves.driftAt = 2; + const d = deps(); + const response = await handle(request(call(), "synthetic-privy"), d); + expect((await response.json()).result.isError).toBe(true); + expect(d.storage.create).not.toHaveBeenCalled(); +}); +it.each([["mcp:tools"], ["mcp:read"]])( + "denies delegated %j during initialization", + async scopes => { + vi.stubEnv("OAUTH_ENABLED", "true"); + leaves.verifyAccess.mockResolvedValue({ + accountId: fixture.actor, + scopes, + grantId: "fixture", + clientId: "fixture", + expiresAt: 9999999999, + }); + const r = request({ jsonrpc: "2.0", id: 1, method: "initialize" }); + const reader = vi.spyOn(r.body!, "getReader"); + expect((await handle(r, deps())).status).toBe(403); + expect(reader).not.toHaveBeenCalled(); + expect(fixture.queries).toEqual([]); + }, +); +it("classifier failure is bounded without legacy fallback", async () => { + vi.stubEnv("OAUTH_ENABLED", "true"); + leaves.verifyAccess.mockRejectedValue(new Error("PRIVATE_SENTINEL")); + const response = await handle(request(call()), deps()); + expect(response.status).toBe(503); + expect(await response.text()).not.toContain("PRIVATE_SENTINEL"); + expect(fixture.queries).toEqual([]); +}); +it.each(["denied", "conflict", "outcome_unknown"] as const)( + "preserves storage %s without retry", + async kind => { + const d = deps(); + d.storage.create.mockRejectedValue(new ProposedStorageFailure(kind)); + const result = await (await handle(request(call()), d)).json(); + expect(result.result.isError).toBe(true); + expect(d.storage.create).toHaveBeenCalledTimes(1); + expect(JSON.stringify(result)).toContain( + kind === "outcome_unknown" ? "Storage outcome unknown" : kind, + ); + }, +); +it("rejects caller identity and altered receipt", async () => { + const d = deps(); + expect( + ( + await ( + await handle( + request( + call("create_application_registration", { + ...input, + actor: fixture.actor, + policy: d.policy, + }), + ), + d, + ) + ).json() + ).result.isError, + ).toBe(true); + expect(d.storage.create).not.toHaveBeenCalled(); + d.storage.create.mockResolvedValue({ + ...golden.createReceipt, + actor: "33333333-3333-4333-8333-333333333333", + }); + const result = await (await handle(request(call()), d)).json(); + expect(result.result.isError).toBe(true); + expect(d.storage.create).toHaveBeenCalledTimes(1); +}); +it.each([ + ["application/json", "application/json", "{", 406], + ["text/plain", "application/json, text/event-stream", "{", 415], + ["application/json", "application/json, text/event-stream", "{", 400], +])("denies malformed headers/body with finite precedence", async (type, accept, body, status) => { + const r = new NextRequest("https://fixture.invalid/mcp", { + method: "POST", + headers: { + authorization: `Bearer ${fixture.key}`, + "content-type": String(type), + accept: String(accept), + }, + body: String(body), + }); + expect((await handle(r, deps())).status).toBe(status); +}); +it.each([ + ["Application/JSON; charset=utf-8", "Application/JSON, Text/Event-Stream", 200], + ["application/json;q=custom", "application/json, text/event-stream", 200], + ["application/json", 'application/json; note="a,b; c", text/event-stream;q=0.5', 200], + ["text/plain; note=application/json", "application/json, text/event-stream", 415], + ['text/plain; note="application/json"', "application/json, text/event-stream", 415], + ["application/json-seq", "application/json, text/event-stream", 415], + ["application/json", 'text/plain; note="application/json", text/event-stream', 406], + ["application/json", "application/json;q=0, text/event-stream", 406], + ["application/json", "application/json, text/event-stream;Q=0.000", 406], + ["application/json", "application/json;q=0, text/event-stream, */*;q=1", 406], + ["application/json", "application/json;q=1, application/json;q=0, text/event-stream", 406], + ["application/json", "application/json;q=1.1, text/event-stream", 406], + ["application/json", "application/json;q=garbage, text/event-stream", 406], + ["application/json", "application/json;q=0;q=1, text/event-stream", 406], + ["application/json", "*/*", 406], +])("validates actual media ranges through the SDK (%s, %s)", async (type, accept, status) => { + const sdk = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "handleRequest"); + const d = deps(); + const r = request(call()); + r.headers.set("content-type", String(type)); + r.headers.set("accept", String(accept)); + r.headers.set("mcp-protocol-version", "2025-11-25"); + const before = Object.fromEntries(r.headers); + const response = await handle(r, d); + expect(response.status).toBe(status); + expect(r.headers.get("authorization")).toBe(before.authorization); + expect(r.headers.get("mcp-protocol-version")).toBe(before["mcp-protocol-version"]); + expect(d.storage.create).toHaveBeenCalledTimes(status === 200 ? 1 : 0); + if (status === 200) { + expect((await response.json()).result.isError).not.toBe(true); + expect(sdk.mock.calls[0][0]).toBe(r); + expect(r.bodyUsed).toBe(true); + expect(r.headers.get("accept")).toBe( + String(accept) + .replaceAll("Application/JSON", "application/json") + .replaceAll("Text/Event-Stream", "text/event-stream"), + ); + } else { + expect(sdk).not.toHaveBeenCalled(); + expect(Object.fromEntries(r.headers)).toEqual(before); + } +}); +it("accepts exactly 64KiB and counts bytes despite lying length", async () => { + const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + for (const extra of [0, 1]) { + const text = body + " ".repeat(65536 - new TextEncoder().encode(body).length + extra); + const r = new NextRequest("https://fixture.invalid/mcp", { + method: "POST", + headers: { + authorization: `Bearer ${fixture.key}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + "content-length": "1", + }, + body: text, + }); + expect((await handle(r, deps())).status).toBe(extra ? 413 : 200); + } +}); +it.each([2, 3])( + "removed credential at observation %s never enters original port", + async observation => { + const original = supabase.from.bind(supabase); + let seen = 0; + vi.spyOn(supabase, "from").mockImplementation(table => { + if (++seen === observation) fixture.keyPresent = false; + return original(table); + }); + const d = deps(); + const result = await (await handle(request(call()), d)).json(); + expect(result.result.isError).toBe(true); + expect(d.storage.create).not.toHaveBeenCalled(); + }, +); +it("interleaved original requests never share their principal or storage wrapper", async () => { + const actors = [golden.input.actor, "44444444-4444-4444-8444-444444444444"]; + const keys = ["recoup_sk_one", "recoup_sk_two"]; + const hashes = keys.map(key => + createHmac("sha256", "synthetic-registration-secret").update(key).digest("hex"), + ); + vi.spyOn(supabase, "from").mockImplementation(table => { + expect(table).toBe("account_api_keys"); + return { + select(columns: string) { + expect(columns).toBe("*"); + return { + eq(field: string, hash: string) { + expect(field).toBe("key_hash"); + const index = hashes.indexOf(hash); + expect(index).toBeGreaterThanOrEqual(0); + return Promise.resolve({ + error: null, + data: [{ id: actors[index], account: actors[index], expires_at: null }], + }); + }, + }; + }, + } as ReturnType; + }); + const seen: string[] = []; + let release!: () => void; + const both = new Promise(resolve => { + release = resolve; + }); + const d = deps(); + d.storage.create.mockImplementation(async (arg: unknown) => { + const actor = (arg as { actor: string }).actor; + seen.push(actor); + if (seen.length === 2) release(); + await both; + return { + ...structuredClone(golden.createReceipt), + actor, + workspace_id: actor, + billing_owner_id: actor, + snapshot: { ...structuredClone(golden.createReceipt.snapshot), workspace_id: actor }, + }; + }); + const responses = await Promise.all(keys.map(key => handle(request(call(), key), d))); + const results = await Promise.all(responses.map(r => r.json())); + expect(results.every(r => !r.result.isError)).toBe(true); + expect(seen.sort()).toEqual(actors.sort()); + expect(d.storage.create).toHaveBeenCalledTimes(2); +}); +it.each(["denied", "conflict"] as const)("never renders mutable %s exception text", async kind => { + const d = deps(); + const error = new ProposedStorageFailure(kind); + error.message = "PRIVATE_SENTINEL token details"; + d.storage.create.mockRejectedValue(error); + const text = await (await handle(request(call()), d)).text(); + expect(text).not.toContain("PRIVATE_SENTINEL"); + expect(text).toContain(`Proposed storage ${kind}`); +}); +it("guard rejects the wrong port method without forwarding observation metadata", async () => { + const r = request(call()); + const admission = await verifyExistingApplicationMcpActor(r); + if (admission instanceof NextResponse) throw new Error("Fixture admission failed"); + const d = deps(); + const life = createProposedRegistrationMcpLifetime(r); + try { + const wrapped = await guardProposedRegistrationStorage( + { request: r, admission, dependencies: d, life }, + "create", + new AbortController().signal, + ); + expect(() => + wrapped.storage.read({ + actor: fixture.actor, + workspace: fixture.actor, + application: golden.readReceipt.application_id, + environment: "production", + receipt: golden.readReceipt.receipt_id, + }), + ).toThrow(ProposedStorageFailure); + expect(d.storage.read).not.toHaveBeenCalled(); + } finally { + await life.close(); + } +}); +it("counts chunked multibyte wire bytes rather than characters", async () => { + const source = new TextEncoder().encode(JSON.stringify("音".repeat(23000))); + const cancel = vi.fn(); + const original = request(call()); + const body = new ReadableStream({ + start(c) { + c.enqueue(source.slice(0, 32000)); + c.enqueue(source.slice(32000)); + }, + cancel, + }); + const r = new NextRequest(original.url, { + method: "POST", + headers: original.headers, + body, + duplex: "half", + } as RequestInit); + expect((await handle(r, deps())).status).toBe(413); + expect(cancel).toHaveBeenCalledTimes(1); +}); diff --git a/lib/applications/proposedRegistration/__tests__/mcpTransportLifecycle.test.ts b/lib/applications/proposedRegistration/__tests__/mcpTransportLifecycle.test.ts new file mode 100644 index 000000000..91a531703 --- /dev/null +++ b/lib/applications/proposedRegistration/__tests__/mcpTransportLifecycle.test.ts @@ -0,0 +1,424 @@ +import { readProposedRegistrationMcpBody } from "@/lib/mcp/applications/readProposedRegistrationMcpBody"; +import { afterEach, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { createProposedRegistrationMcpLifetime } from "@/lib/mcp/applications/createProposedRegistrationMcpLifetime"; + +import { beforeEach } from "vitest"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; +import { handleProposedRegistrationMcpRequest as handle } from "@/lib/mcp/applications/handleProposedRegistrationMcpRequest"; +import { fixture } from "../../../../scripts/application-registration-proposal/setup"; +import golden from "../../../../scripts/application-registration-proposal/receipt-golden.json"; +import type { ProposedDependencies } from "../proposedRegistrationContract"; +import supabase from "@/lib/supabase/serverClient"; +import * as domain from "../createProposedApplicationRegistration"; +afterEach(() => vi.useRealTimers()); +it("bounds a hung asynchronous stage and closes once", async () => { + vi.useFakeTimers(); + const life = createProposedRegistrationMcpLifetime( + new NextRequest("https://fixture.invalid/mcp"), + ); + const close = vi.fn(async () => {}); + life.own(close); + const result = life.run(() => new Promise(() => {})).catch(e => e); + await vi.advanceTimersByTimeAsync(30000); + expect(await result).toBeInstanceOf(Response); + await life.close(); + await life.close(); + expect(close).toHaveBeenCalledTimes(1); + expect(life.terminated()).toBe(true); + expect(vi.getTimerCount()).toBe(0); +}); +it("separately bounds failed cleanup", async () => { + vi.useFakeTimers(); + const life = createProposedRegistrationMcpLifetime( + new NextRequest("https://fixture.invalid/mcp"), + ); + life.own(() => new Promise(() => {})); + const result = life.close().catch(e => e); + await vi.advanceTimersByTimeAsync(1000); + expect(await result).toBeInstanceOf(Error); + expect(vi.getTimerCount()).toBe(0); +}); +beforeEach(() => { + vi.stubEnv("OAUTH_ENABLED", "false"); +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); +const dependencies = () => ({ + policy: { + status: "proposed_unadopted", + version: "proposed-personal-v1", + databaseHead: golden.databaseHead, + } as ProposedDependencies["policy"], + storage: { + create: vi.fn(async () => + structuredClone(golden.createReceipt), + ), + read: vi.fn(async () => + structuredClone(golden.readReceipt), + ), + }, +}); +function req(signal?: AbortSignal, method = "tools/call") { + return new NextRequest("https://fixture.invalid/mcp", { + method: "POST", + signal, + headers: { + authorization: `Bearer ${fixture.key}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method, + params: { + name: "create_application_registration", + arguments: { + idempotency_key: golden.input.key, + expected_entitlement_revision: 1, + registration: { + name: golden.input.registration.name, + environment: "production", + allowed_origins: golden.input.registration.origins.map(o => o.origin), + return_urls: golden.input.registration.origins.flatMap(o => o.return_urls), + }, + }, + }, + }), + }); +} +function barrier() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +function observeDomainCompletion(onEnter = () => {}) { + const finished = barrier(); + let complete = false; + const actualCreate = domain.createProposedApplicationRegistration; + vi.spyOn(domain, "createProposedApplicationRegistration").mockImplementation(async (...args) => { + onEnter(); + try { + return await actualCreate(...args); + } finally { + complete = true; + finished.resolve(); + } + }); + return { finished: finished.promise, isComplete: () => complete }; +} +it("closes SDK before returning JSON, even when the caller cancels the response body", async () => { + const close = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "close"); + const response = await handle(req(undefined, "tools/list"), dependencies()); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(close).toHaveBeenCalledTimes(1); + await response.body?.cancel(); + expect(close).toHaveBeenCalledTimes(1); +}); +it.each(["resolve", "reject"] as const)( + "after storage entry, abort closes transport but late %s is not rollback or retry", + async settle => { + const abort = new AbortController(); + const entered = barrier(); + const storage = barrier(); + const d = dependencies(); + const completion = observeDomainCompletion(); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + const send = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "send"); + d.storage.create.mockImplementation(async () => { + entered.resolve(); + return storage.promise; + }); + const close = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "close"); + const response = handle(req(abort.signal), d); + await entered.promise; + abort.abort(); + const delivered = await response; + const originalBody = await delivered.clone().text(); + expect(delivered.status).toBe(408); + expect(close).toHaveBeenCalledTimes(1); + expect(completion.isComplete()).toBe(false); + const sendsAtAbort = send.mock.calls.length; + if (settle === "resolve") storage.resolve(golden.createReceipt); + else storage.reject(new Error("PRIVATE_SENTINEL")); + await completion.finished; + expect(completion.isComplete()).toBe(true); + expect(d.storage.create).toHaveBeenCalledTimes(1); + expect(await response).toBe(delivered); + expect(await delivered.text()).toBe(originalBody); + expect(originalBody).not.toMatch(/PRIVATE_SENTINEL|receipt_id/); + expect(send).toHaveBeenCalledTimes(sendsAtAbort); + expect(errors).not.toHaveBeenCalled(); + }, +); +it("abort during fresh domain lookup prevents late storage invocation", async () => { + const abort = new AbortController(); + const entered = barrier(); + const resume = barrier(); + const original = supabase.from.bind(supabase); + let inDomain = false; + const gated = vi.fn(); + vi.spyOn(supabase, "from").mockImplementation(table => { + const query = original(table); + if (!inDomain || table !== "account_api_keys") return query; + const select = query.select.bind(query); + return { + ...query, + select: (...args: Parameters) => { + const selection = select(...args); + const eq = selection.eq.bind(selection); + return { + ...selection, + eq: async (...params: Parameters) => { + expect(params[0]).toBe("key_hash"); + gated(table, params[0]); + entered.resolve(); + await resume.promise; + return eq(...params); + }, + }; + }, + }; + }); + const completion = observeDomainCompletion(() => { + inDomain = true; + }); + const d = dependencies(); + const response = handle(req(abort.signal), d); + await entered.promise; + expect(gated).toHaveBeenCalledExactlyOnceWith("account_api_keys", "key_hash"); + expect(completion.isComplete()).toBe(false); + abort.abort(); + expect((await response).status).toBe(408); + resume.resolve(); + await completion.finished; + expect(d.storage.create).not.toHaveBeenCalled(); +}); +it("bounds truly pending admission and observes its late rejection", async () => { + vi.useFakeTimers(); + const pending = barrier(); + const original = supabase.from.bind(supabase); + vi.spyOn(supabase, "from").mockImplementation(table => { + const query = original(table); + const select = query.select.bind(query); + return { + ...query, + select: (...args: Parameters) => ({ + ...select(...args), + eq: () => pending.promise, + }), + }; + }); + const response = handle(req(), dependencies()); + await vi.advanceTimersByTimeAsync(30000); + expect((await response).status).toBe(504); + pending.reject(new Error("PRIVATE_SENTINEL")); + await vi.advanceTimersByTimeAsync(0); + expect(vi.getTimerCount()).toBe(0); +}); +it("body timeout cancels the owned input and closes its deadline", async () => { + vi.useFakeTimers(); + const cancel = vi.fn(); + const original = req(); + const body = new ReadableStream({ pull() {}, cancel }); + const request = new NextRequest(original.url, { + method: "POST", + headers: original.headers, + body, + duplex: "half", + } as RequestInit); + const response = handle(request, dependencies()); + await vi.advanceTimersByTimeAsync(5001); + expect((await response).status).toBe(408); + expect(await (await response).json()).toEqual({ + jsonrpc: "2.0", + error: { code: -32000, message: "Request body timeout" }, + id: null, + }); + expect(cancel).toHaveBeenCalledTimes(1); + expect(vi.getTimerCount()).toBe(0); +}); +it("close failure cannot be reported as successful cleanup", async () => { + vi.spyOn(McpServer.prototype, "close").mockRejectedValueOnce(new Error("PRIVATE_SENTINEL")); + const response = await handle(req(undefined, "tools/list"), dependencies()); + expect(response.status).toBe(503); + expect(await response.text()).not.toContain("PRIVATE_SENTINEL"); +}); + +it("bounds connect, closes its attached transport, and blocks late continuation", async () => { + vi.useFakeTimers(); + const resume = barrier(); + const original = WebStandardStreamableHTTPServerTransport.prototype.start; + vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "start").mockImplementation( + async function () { + await original.call(this); + await resume.promise; + }, + ); + const close = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "close"); + const dispatch = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "handleRequest"); + const d = dependencies(); + const response = handle(req(), d); + await vi.advanceTimersByTimeAsync(30000); + expect((await response).status).toBe(504); + expect(close).toHaveBeenCalledTimes(1); + resume.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(dispatch).not.toHaveBeenCalled(); + expect(d.storage.create).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); +}); +it("bounds the SDK's pending JSON promise separately from late domain settlement", async () => { + vi.useFakeTimers(); + const pending = barrier(); + const completion = observeDomainCompletion(); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + const send = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "send"); + const d = dependencies(); + d.storage.create.mockImplementation(() => pending.promise); + const response = handle(req(), d); + await vi.advanceTimersByTimeAsync(30000); + const delivered = await response; + const originalBody = await delivered.clone().text(); + expect(delivered.status).toBe(504); + expect(d.storage.create).toHaveBeenCalledTimes(1); + expect(completion.isComplete()).toBe(false); + const sendsAtDeadline = send.mock.calls.length; + pending.resolve(golden.createReceipt); + await completion.finished; + expect(completion.isComplete()).toBe(true); + expect(d.storage.create).toHaveBeenCalledTimes(1); + expect(await response).toBe(delivered); + expect(await delivered.text()).toBe(originalBody); + expect(originalBody).not.toMatch(/PRIVATE_SENTINEL|receipt_id/); + expect(send).toHaveBeenCalledTimes(sendsAtDeadline); + expect(errors).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); +}); +it("bounds an uncooperative SDK close independently", async () => { + vi.useFakeTimers(); + const close = barrier(); + const original = WebStandardStreamableHTTPServerTransport.prototype.close; + vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "close").mockImplementation( + async function () { + await original.call(this); + await close.promise; + }, + ); + const response = handle(req(undefined, "tools/list"), dependencies()); + await vi.advanceTimersByTimeAsync(1001); + expect((await response).status).toBe(503); + close.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(vi.getTimerCount()).toBe(0); +}); +it("pre-aborted requests never enter authentication or SDK allocation", async () => { + const abort = new AbortController(); + abort.abort(); + const connect = vi.spyOn(McpServer.prototype, "connect"); + expect((await handle(req(abort.signal), dependencies())).status).toBe(408); + expect(fixture.queries).toEqual([]); + expect(connect).not.toHaveBeenCalled(); +}); +it.each(["accept", "length", "auth"])("cancels unread body on early %s denial", async kind => { + const cancel = vi.fn(); + const original = req(); + if (kind === "accept") original.headers.set("accept", "application/json"); + if (kind === "length") original.headers.set("content-length", "65537"); + if (kind === "auth") original.headers.set("authorization", "Basic invalid"); + const body = new ReadableStream({ cancel }); + const request = new NextRequest(original.url, { + method: "POST", + headers: original.headers, + body, + duplex: "half", + } as RequestInit); + expect((await handle(request, dependencies())).status).toBe( + kind === "auth" ? 401 : kind === "accept" ? 406 : 413, + ); + expect(cancel).toHaveBeenCalledTimes(1); +}); +it("reports a noncooperative unread-body cleanup instead of claiming disposal", async () => { + vi.useFakeTimers(); + const blocked = barrier(); + const original = req(); + original.headers.set("content-length", "65537"); + const body = new ReadableStream({ cancel: () => blocked.promise }); + const request = new NextRequest(original.url, { + method: "POST", + headers: original.headers, + body, + duplex: "half", + } as RequestInit); + const response = handle(request, dependencies()); + await vi.advanceTimersByTimeAsync(1001); + expect((await response).status).toBe(503); + blocked.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(vi.getTimerCount()).toBe(0); +}); +it.each(["registration", "connect"])("owns teardown when %s fails", async stage => { + const close = vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "close"); + if (stage === "registration") + vi.spyOn(McpServer.prototype, "registerTool").mockImplementationOnce(() => { + throw new Error("PRIVATE_SENTINEL"); + }); + else + vi.spyOn(WebStandardStreamableHTTPServerTransport.prototype, "start").mockRejectedValueOnce( + new Error("PRIVATE_SENTINEL"), + ); + const d = dependencies(); + const response = await handle(req(), d); + expect(response.status).toBe(503); + expect(await response.text()).not.toContain("PRIVATE_SENTINEL"); + expect(close).toHaveBeenCalledTimes(1); + expect(d.storage.create).not.toHaveBeenCalled(); +}); + +it.each(["closed", "closing", "aborted"])( + "does not acquire or leave a reader locked for an owner already %s", + async state => { + const abort = new AbortController(); + const request = req(abort.signal); + const life = createProposedRegistrationMcpLifetime(request); + const cleanup = barrier(); + let closing: Promise | undefined; + if (state === "closing") { + life.own(() => cleanup.promise); + closing = life.close(); + } else if (state === "closed") await life.close(); + else abort.abort(); + let acquired: ReadableStreamDefaultReader> | undefined; + const actualGetReader = request.body!.getReader.bind(request.body!); + const getReader = vi.spyOn(request.body!, "getReader").mockImplementation(() => { + acquired = actualGetReader(); + return acquired; + }); + try { + expect(request.body!.locked).toBe(false); + const terminal = await life.run(async () => undefined).catch(error => error); + expect(terminal).toBeInstanceOf(Response); + expect(terminal.status).toBe(408); + await expect(readProposedRegistrationMcpBody(request, life)).rejects.toBe(terminal); + expect(request.body!.locked).toBe(false); + expect(getReader).not.toHaveBeenCalled(); + } finally { + // Keep the deliberately failing RED regression from leaving its unowned reader locked. + cleanup.resolve(); + try { + await (closing ?? life.close()); + } finally { + acquired?.releaseLock(); + } + } + }, +); diff --git a/lib/mcp/applications/createProposedRegistrationMcpLifetime.ts b/lib/mcp/applications/createProposedRegistrationMcpLifetime.ts new file mode 100644 index 000000000..e54ed76d4 --- /dev/null +++ b/lib/mcp/applications/createProposedRegistrationMcpLifetime.ts @@ -0,0 +1,75 @@ +/** Request-local ownership for the inactive transport; closing is not storage cancellation. */ +export function createProposedRegistrationMcpLifetime(request: Request) { + let terminal: Response | undefined; + let closing: Promise | undefined; + const cleanups: Array<() => Promise> = []; + let rejectStopped!: (reason: Response) => void; + const stopped = new Promise((_resolve, reject) => { + rejectStopped = reject; + }); + // Observe termination even if it occurs before the first stage starts. + void stopped.catch(() => {}); + const stop = (status: number) => { + if (terminal) return; + terminal = Response.json( + { error: "Request ended; an invoked storage outcome may be unknown" }, + { status }, + ); + rejectStopped(terminal); + }; + const close = (): Promise => { + if (closing) return closing; + stop(408); + clearTimeout(deadline); + request.signal.removeEventListener("abort", abort); + closing = (async () => { + let timer: ReturnType | undefined; + try { + const results = await Promise.race([ + Promise.allSettled(cleanups.map(cleanup => Promise.resolve().then(cleanup))), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error("Transport cleanup unconfirmed")), 1000); + }), + ]); + if (results.some(result => result.status === "rejected")) + throw new Error("Transport cleanup unconfirmed"); + } finally { + clearTimeout(timer); + } + })(); + return closing; + }; + const abort = () => { + stop(408); + }; + const deadline = setTimeout(() => { + stop(504); + }, 30000); + request.signal.addEventListener("abort", abort, { once: true }); + if (request.signal.aborted) abort(); + const assertActive = () => { + if (terminal) throw terminal; + }; + return { + terminated: () => !!terminal || request.signal.aborted, + assertActive, + own(cleanup: () => Promise) { + if (closing) throw new Error("Request owner already closed"); + cleanups.push(cleanup); + }, + async run(work: () => Promise): Promise { + assertActive(); + // Race installs rejection observers on losing work as well as termination. + const result = await Promise.race([ + Promise.resolve().then(() => { + assertActive(); + return work(); + }), + stopped, + ]); + assertActive(); + return result; + }, + close, + }; +} diff --git a/lib/mcp/applications/guardProposedRegistrationStorage.ts b/lib/mcp/applications/guardProposedRegistrationStorage.ts new file mode 100644 index 000000000..c35d253fa --- /dev/null +++ b/lib/mcp/applications/guardProposedRegistrationStorage.ts @@ -0,0 +1,89 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { + ProposedStorageFailure, + type ProposedDependencies, + type ProposedActor, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import { verifyExistingApplicationMcpActor } from "./verifyExistingApplicationMcpActor"; +import type { createProposedRegistrationMcpLifetime } from "./createProposedRegistrationMcpLifetime"; +type Observation = Exclude< + Awaited>, + NextResponse +>; +export type ProposedMcpInvocation = { + request: NextRequest; + admission: Observation; + dependencies: ProposedDependencies; + life: ReturnType; +}; +/** Compare actual observations, then gate the actual domain call without substituting identity. */ +export async function guardProposedRegistrationStorage( + context: ProposedMcpInvocation, + operation: "create" | "read", + signal: AbortSignal, +): Promise { + const { request, admission, dependencies, life } = context; + const deny = (): never => { + throw new ProposedStorageFailure("denied"); + }; + if (life.terminated() || signal.aborted) deny(); + const fresh = await life.run(() => verifyExistingApplicationMcpActor(request)); + if (fresh instanceof NextResponse) deny(); + const observed = fresh as Observation; + const a = admission.verificationEvidence.principal; + const b = observed.verificationEvidence.principal; + if ( + admission.actor !== observed.actor || + admission.workspace !== observed.workspace || + admission.verificationEvidence.effectiveAccountId !== + observed.verificationEvidence.effectiveAccountId || + a.actorAccountId !== b.actorAccountId || + a.mechanism !== b.mechanism + ) + deny(); + if (a.mechanism === "recoup_api_key" && (b.mechanism !== "recoup_api_key" || a.keyId !== b.keyId)) + deny(); + if ( + a.mechanism === "privy" && + (b.mechanism !== "privy" || + a.appId !== b.appId || + a.issuer !== b.issuer || + a.subject !== b.subject) + ) + deny(); + // Primitive snapshots cannot be retargeted while the domain authenticates again. + const expected = Object.freeze({ + actor: admission.actor, + workspace: admission.workspace, + freshActor: observed.actor, + freshWorkspace: observed.workspace, + }); + const check = (method: "create" | "read", call: ProposedActor) => { + if ( + method !== operation || + life.terminated() || + request.signal.aborted || + signal.aborted || + call.actor !== expected.actor || + call.actor !== expected.freshActor || + call.workspace !== expected.workspace || + call.workspace !== expected.freshWorkspace + ) + deny(); + }; + const create = dependencies.storage.create.bind(dependencies.storage); + const read = dependencies.storage.read.bind(dependencies.storage); + return { + policy: dependencies.policy, + storage: { + create(call) { + check("create", call); + return create(call); + }, + read(call) { + check("read", call); + return read(call); + }, + }, + }; +} diff --git a/lib/mcp/applications/handleProposedRegistrationMcpRequest.ts b/lib/mcp/applications/handleProposedRegistrationMcpRequest.ts new file mode 100644 index 000000000..c0c4e30da --- /dev/null +++ b/lib/mcp/applications/handleProposedRegistrationMcpRequest.ts @@ -0,0 +1,71 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; +import type { ProposedDependencies } from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import { setOAuthMcpHeaders } from "@/lib/mcp/oauth/setOAuthMcpHeaders"; +import { verifyExistingApplicationMcpActor } from "./verifyExistingApplicationMcpActor"; +import { createProposedRegistrationMcpLifetime } from "./createProposedRegistrationMcpLifetime"; +import { readProposedRegistrationMcpBody } from "./readProposedRegistrationMcpBody"; +import { registerCreateProposedRegistrationTool } from "./registerCreateProposedRegistrationTool"; +import { registerReadProposedRegistrationTool } from "./registerReadProposedRegistrationTool"; +/** Unregistered, proposed-only HTTP composition. No production dependency factory or route caller. */ +export async function handleProposedRegistrationMcpRequest( + request: NextRequest, + dependencies: ProposedDependencies, +): Promise { + const life = createProposedRegistrationMcpLifetime(request); + // Own unread input too: auth/header/length rejection must not leave a streaming source alive. + life.own(async () => { + if (request.body && !request.body.locked && !request.bodyUsed) await request.body.cancel(); + }); + let response: Response; + try { + response = await life.run(async () => { + if (request.method === "OPTIONS") return new Response(null, { status: 204 }); + const verified = await life.run(() => verifyExistingApplicationMcpActor(request)); + if (verified instanceof NextResponse) return verified; + if (request.method !== "POST") + return Response.json({ error: "Method not allowed" }, { status: 405 }); + const admission = structuredClone(verified); + Object.freeze(admission.verificationEvidence.principal); + Object.freeze(admission.verificationEvidence); + Object.freeze(admission); + const body = await readProposedRegistrationMcpBody(request, life); + life.assertActive(); + const server = new McpServer({ name: "recoup-proposed-registration", version: "0.0.0" }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }); + // Register ownership before any registration/connect stage can fail or hang. + life.own(async () => { + try { + if (server.server.transport) await server.close(); + else await transport.close(); + } catch { + await transport.close(); + throw new Error("Transport cleanup unconfirmed"); + } + }); + const context = { request, admission, dependencies, life }; + registerCreateProposedRegistrationTool(server, context); + registerReadProposedRegistrationTool(server, context); + await life.run(() => server.connect(transport)); + return life.run(() => transport.handleRequest(request, { parsedBody: body })); + }); + } catch (error) { + response = + error instanceof Response + ? error + : Response.json({ error: "Registration transport unavailable" }, { status: 503 }); + } + try { + await life.close(); + } catch { + response = Response.json( + { error: "Transport cleanup unconfirmed; storage outcome may be unknown" }, + { status: 503 }, + ); + } + return setOAuthMcpHeaders(response); +} diff --git a/lib/mcp/applications/readProposedRegistrationMcpBody.ts b/lib/mcp/applications/readProposedRegistrationMcpBody.ts new file mode 100644 index 000000000..b7b36885f --- /dev/null +++ b/lib/mcp/applications/readProposedRegistrationMcpBody.ts @@ -0,0 +1,121 @@ +import type { createProposedRegistrationMcpLifetime } from "./createProposedRegistrationMcpLifetime"; + +// Parse complete entries: quoted parameter text must never establish a media range. +function mediaRanges(value: string | null, interpretQuality = false) { + const token = "[!#$%&'*+.^_`|~0-9A-Za-z-]+"; + const quoted = '"(?:[^"\\\\\\r\\n]|\\\\[^\\r\\n])*"'; + const parameter = `\\s*;\\s*(${token})\\s*=\\s*(${token}|${quoted})`; + const entry = new RegExp(`\\s*(${token}/${token})((?:${parameter})*)\\s*(,|$)`, "gy"); + const ranges: { type: string; quality: number; canonical: string }[] = []; + if (!value) return ranges; + let offset = 0; + while (offset < value.length) { + const match = entry.exec(value); + if (!match || (match[5] === "," && entry.lastIndex === value.length)) return []; + let quality = 1; + let hasQuality = false; + for (const param of match[2].matchAll(new RegExp(parameter, "g"))) { + if (!interpretQuality || param[1].toLowerCase() !== "q") continue; + if (hasQuality || !/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(param[2])) return []; + quality = Number(param[2]); + hasQuality = true; + } + const type = match[1].toLowerCase(); + ranges.push({ type, quality, canonical: type + match[2] }); + offset = entry.lastIndex; + } + return ranges; +} +/** Read once, count wire bytes, and reject non-single or unacknowledged tool execution. */ +export async function readProposedRegistrationMcpBody( + request: Request, + life: ReturnType, +): Promise { + const fail = (status: number, message: string, code = -32600): never => { + throw Response.json({ jsonrpc: "2.0", error: { code, message }, id: null }, { status }); + }; + const accept = mediaRanges(request.headers.get("accept"), true); + const accepts = (type: string) => { + const explicit = accept.filter(range => range.type === type); + return explicit.length > 0 && explicit.every(range => range.quality > 0); + }; + if (!accepts("application/json") || !accepts("text/event-stream")) + fail(406, "Both JSON and event-stream must be accepted", -32000); + const contentType = mediaRanges(request.headers.get("content-type")); + if (contentType.length !== 1 || contentType[0].type !== "application/json") + fail(415, "JSON content type required", -32000); + // SDK 1.26 also checks case-sensitive substrings. Canonicalize only validated + // media tokens on this same request; credentials, parameters and body stay intact. + request.headers.set("accept", accept.map(range => range.canonical).join(", ")); + request.headers.set("content-type", contentType[0].canonical); + if (Number(request.headers.get("content-length")) > 65536) fail(413, "Request body too large"); + if (!request.body) fail(400, "Invalid JSON", -32700); + // No asynchronous gap between checking the owner and registering the acquired reader. + life.assertActive(); + const reader = request.body!.getReader(); + let released = false; + const release = () => { + if (!released) { + released = true; + reader.releaseLock(); + } + }; + life.own(async () => { + if (!released) { + try { + await reader.cancel(); + } finally { + release(); + } + } + }); + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout( + () => + reject( + Response.json( + { jsonrpc: "2.0", error: { code: -32000, message: "Request body timeout" }, id: null }, + { status: 408 }, + ), + ), + 5000, + ); + }); + try { + const bytes: Uint8Array[] = []; + let size = 0; + while (true) { + const chunk = await life.run(() => Promise.race([reader.read(), timeout])); + if (chunk.done) break; + size += chunk.value.byteLength; + if (size > 65536) fail(413, "Request body too large"); + bytes.push(chunk.value); + } + release(); + const joined = new Uint8Array(size); + let offset = 0; + for (const chunk of bytes) { + joined.set(chunk, offset); + offset += chunk.byteLength; + } + let body: unknown; + try { + body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(joined)); + } catch { + fail(400, "Invalid JSON", -32700); + } + if (Array.isArray(body)) fail(400, "Batches are unsupported"); + if ( + body && + typeof body === "object" && + "method" in body && + body.method === "tools/call" && + !("id" in body && (typeof body.id === "string" || typeof body.id === "number")) + ) + fail(400, "Tool calls require an id"); + return body; + } finally { + clearTimeout(timer); + } +} diff --git a/lib/mcp/applications/registerCreateProposedRegistrationTool.ts b/lib/mcp/applications/registerCreateProposedRegistrationTool.ts new file mode 100644 index 000000000..9c2229db4 --- /dev/null +++ b/lib/mcp/applications/registerCreateProposedRegistrationTool.ts @@ -0,0 +1,49 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { createProposedApplicationRegistration } from "@/lib/applications/proposedRegistration/createProposedApplicationRegistration"; +import { + proposedCreateInputSchema, + ProposedStorageFailure, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; +import { getToolResultError } from "@/lib/mcp/getToolResultError"; +import { + guardProposedRegistrationStorage, + type ProposedMcpInvocation, +} from "./guardProposedRegistrationStorage"; +/** Inactive SDK registration; only the server closure supplies request and dependencies. */ +export function registerCreateProposedRegistrationTool( + server: McpServer, + context: ProposedMcpInvocation, +) { + server.registerTool( + "create_application_registration", + { + description: "Create an inactive proposed application registration receipt.", + inputSchema: proposedCreateInputSchema, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }, + async (args, extra) => { + try { + const dependencies = await guardProposedRegistrationStorage( + context, + "create", + extra.signal, + ); + const result = await context.life.run(() => + createProposedApplicationRegistration(context.request, args, dependencies), + ); + return getToolResultSuccess(result); + } catch (error) { + const message = + error instanceof ProposedStorageFailure + ? error.kind === "denied" + ? "Proposed storage denied" + : error.kind === "conflict" + ? "Proposed storage conflict" + : "Storage outcome unknown; retain original operation, key and input" + : "Registration unavailable; retain original operation, key and input if invoked"; + return { ...getToolResultError(message), isError: true }; + } + }, + ); +} diff --git a/lib/mcp/applications/registerReadProposedRegistrationTool.ts b/lib/mcp/applications/registerReadProposedRegistrationTool.ts new file mode 100644 index 000000000..959bc20e1 --- /dev/null +++ b/lib/mcp/applications/registerReadProposedRegistrationTool.ts @@ -0,0 +1,45 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { readProposedApplicationRegistration } from "@/lib/applications/proposedRegistration/readProposedApplicationRegistration"; +import { + proposedReadInputSchema, + ProposedStorageFailure, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; +import { getToolResultError } from "@/lib/mcp/getToolResultError"; +import { + guardProposedRegistrationStorage, + type ProposedMcpInvocation, +} from "./guardProposedRegistrationStorage"; +/** Inactive SDK registration; only the server closure supplies request and dependencies. */ +export function registerReadProposedRegistrationTool( + server: McpServer, + context: ProposedMcpInvocation, +) { + server.registerTool( + "read_application_registration", + { + description: "Read an inactive proposed application registration receipt.", + inputSchema: proposedReadInputSchema, + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + }, + async (args, extra) => { + try { + const dependencies = await guardProposedRegistrationStorage(context, "read", extra.signal); + const result = await context.life.run(() => + readProposedApplicationRegistration(context.request, args, dependencies), + ); + return getToolResultSuccess(result); + } catch (error) { + const message = + error instanceof ProposedStorageFailure + ? error.kind === "denied" + ? "Proposed storage denied" + : error.kind === "conflict" + ? "Proposed storage conflict" + : "Registration read outcome unavailable; retain original read input" + : "Registration read unavailable; retain original read input"; + return { ...getToolResultError(message), isError: true }; + } + }, + ); +} diff --git a/scripts/application-registration-proposal/source-bindings.json b/scripts/application-registration-proposal/source-bindings.json index 2d20beee5..df4f1a58d 100644 --- a/scripts/application-registration-proposal/source-bindings.json +++ b/scripts/application-registration-proposal/source-bindings.json @@ -11,7 +11,7 @@ "tsconfig.json": "b32629dbc2af272f06db2eb3c5e6bd249183a72cec77481e624b0a4086c10d93", "lib/keys/getApiKeyDetails.ts": "68813ca17af04703ded1efc25d8c6864aaa1f7b9c297ddeadb44c6c10220c644", "lib/mcp/__tests__/verifyApiKeyExpiry.test.ts": "1b4b18f8147217734b9b1d89418a57ae23c968e6046109d072469b7735fdd1bc", - "vercel.json": "3321280d5e9e9c4fbba06651418ffb0f5716418acdddc8f889f618ac8eca0fa3" + "vercel.json": "4b3dfd36dbd274213a3ccf2d6bfbfa9be1ba6be26ea71946828f535e1bbfbf8a" }, "databaseInputs": { "proposals/application-registration-2104/protocol-composition.py": "377791d3ef4a26103bd046609d4b8dbf8f63a3d475aa2c72faeba68b553aada5", diff --git a/vercel.json b/vercel.json index 0a1100240..04cdd7fcc 100644 --- a/vercel.json +++ b/vercel.json @@ -27,7 +27,8 @@ "fix/mcp-oauth-behavior-annotations": false, "codex/oauth-annotations-current-main": false, "codex/mcp-api-key-expiry": false, - "codex/mcp-existing-application-actor": false + "codex/mcp-existing-application-actor": false, + "codex/mcp-registration-transport-proposal": false } } }