cloud / internal-packages / installer / test / mcp-relay-proof.mjsmain at aacbc74
// A PROOF OF THE MCP RELAY against a real deployment, with no browser: this script is the MCP
// app. It registers at the relay, names a deployment, signs in and consents there with a
// member's session, gets the relay's tokens, and calls the deployment's MCP server through
// the relay. Then it refreshes, and checks what the relay keeps.
//
// node test/mcp-relay-proof.mjs <relay origin> <domain> <session.json>
//
// `session.json` is a member's session at https://iterate.<domain>, made with a passkey:
// `{ "header": "<the session cookie, as a Cookie header's value>" }`.
// Prints no token and no cookie.
import { createHash, randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
const [relay, domain, sessionFile] = process.argv.slice(2);
if (!relay || !domain || !sessionFile)
throw new Error("usage: mcp-relay-proof.mjs <relay origin> <domain> <session.json>");
const member = JSON.parse(readFileSync(sessionFile, "utf8")).header;
const issuer = `https://iterate.${domain}`;
const redirectUri = "http://127.0.0.1:9/callback"; // nothing listens: the code is read off the redirect
let failed = 0;
const check = (name, pass, detail = "") => {
if (!pass) failed += 1;
console.log(`${pass ? "ok " : "FAIL"} ${name}${detail ? `: ${detail}` : ""}`);
};
const cookiesOf = (response) =>
(response.headers.getSetCookie?.() ?? [])
.map((c) => c.split(";")[0])
.filter((c) => !c.endsWith("="));
const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
const form = (fields) => ({
method: "POST",
redirect: "manual",
body: new URLSearchParams(fields),
});
// 1. the app finds the relay as any MCP client does
const challenge = await fetch(`${relay}/mcp`, { method: "POST" });
const metadataUrl = /resource_metadata="([^"]+)"/.exec(
challenge.headers.get("www-authenticate") || "",
)?.[1];
check(
"the relay answers 401 and names its metadata",
challenge.status === 401 && Boolean(metadataUrl),
);
const resource = await (await fetch(metadataUrl)).json();
const server = await (
await fetch(`${resource.authorization_servers[0]}/.well-known/oauth-authorization-server`)
).json();
check("its issuer is its own origin", server.issuer === relay, server.issuer);
// 2. the app registers (an app with a client metadata document skips this)
const client = await (
await fetch(server.registration_endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
client_name: "MCP relay proof",
redirect_uris: [redirectUri],
token_endpoint_auth_method: "none",
}),
})
).json();
check("the app registers", typeof client.client_id === "string");
// 3. the relay's page: which deployment
const verifier = b64url(randomBytes(32));
const state = b64url(randomBytes(12));
const authorize = new URL(server.authorization_endpoint);
authorize.search = new URLSearchParams({
response_type: "code",
client_id: client.client_id,
redirect_uri: redirectUri,
scope: "iterate",
resource: resource.resource,
state,
code_challenge: b64url(createHash("sha256").update(verifier).digest()),
code_challenge_method: "S256",
});
const asked = await fetch(authorize, { redirect: "manual" });
const askedPage = await asked.text();
const relayCookies = cookiesOf(asked);
const relayHandle = /name="handle" value="([^"]+)"/.exec(askedPage)?.[1];
check(
"the relay asks for the deployment's domain",
asked.status === 200 && Boolean(relayHandle) && askedPage.includes('name="domain"'),
);
const wrong = await fetch(authorize, {
...form({ handle: relayHandle, decision: "approve", domain: "no-deployment-here.example.com" }),
headers: { cookie: relayCookies.join("; ") },
});
check("a domain with no deployment is refused, and the form stays good", wrong.status === 400);
const named = await fetch(authorize, {
...form({ handle: relayHandle, decision: "approve", domain }),
headers: { cookie: relayCookies.join("; ") },
});
relayCookies.push(...cookiesOf(named));
const there = new URL(named.headers.get("location") || "http://none");
check(
"it sends the person to the deployment's own identity provider, as the Cloud's client",
named.status === 302 &&
there.origin === issuer &&
there.searchParams.get("client_id") === `${relay}/oauth2/client.json` &&
there.searchParams.get("resource") === `${issuer}/mcp`,
there.origin,
);
// 4. on the deployment: a person who is not signed in signs in there; the member is signed in,
// sees the consent page, and allows
const signedOut = await fetch(there, { redirect: "manual" });
check(
"a person who is not signed in is sent to the deployment's own sign-in page",
signedOut.status === 302 &&
// `/sign-in?…`, or `/sign-in/<a method>?…` on a deployment that offers one method
(signedOut.headers.get("location") || "").startsWith(`${issuer}/sign-in`),
`${signedOut.status}`,
);
const consent = await fetch(there, { redirect: "manual", headers: { cookie: member } });
const consentPage = await consent.text();
const consentCookies = cookiesOf(consent);
const consentHandle = /name="handle" value="([^"]+)"/.exec(consentPage)?.[1];
check(
"the deployment shows its own consent page for the Cloud's client",
consent.status === 200 && Boolean(consentHandle) && consentPage.includes("iterate Cloud"),
consent.status === 200 ? "" : `${consent.status} ${consent.headers.get("location") || ""}`,
);
const allowed = await fetch(`${issuer}${there.pathname}`, {
...form({ handle: consentHandle, decision: "allow" }),
headers: { origin: issuer, cookie: [member, ...consentCookies].join("; ") },
});
const back = new URL(allowed.headers.get("location") || "http://none");
check(
"the deployment sends its code back to the relay",
allowed.status === 302 && back.href.startsWith(`${relay}/oauth2/callback?`),
`${allowed.status}`,
);
// 5. back at the relay, then at the app
const finished = await fetch(back, {
redirect: "manual",
headers: { cookie: relayCookies.join("; ") },
});
const home = new URL(finished.headers.get("location") || "http://none");
check(
"the relay sends its own code to the app",
finished.status === 302 &&
home.href.startsWith(redirectUri) &&
home.searchParams.get("state") === state &&
home.searchParams.get("iss") === relay,
home.searchParams.get("error_description") || "",
);
const stolen = await fetch(back, { redirect: "manual" });
check(
"the deployment's code is refused in another browser",
stolen.status === 400,
`${stolen.status}`,
);
const token = (fields) =>
fetch(
server.token_endpoint,
form({ ...fields, client_id: client.client_id, resource: resource.resource }),
).then(async (answer) => ({ status: answer.status, ...(await answer.json()) }));
const first = await token({
grant_type: "authorization_code",
code: home.searchParams.get("code"),
redirect_uri: redirectUri,
code_verifier: verifier,
});
check(
"the app gets the relay's tokens",
Boolean(first.access_token && first.refresh_token),
`expires in ${first.expires_in} s`,
);
// 6. the deployment's MCP server, through the relay
let id = 0;
async function mcp(accessToken, method, params, sessionId) {
const headers = new Headers({
authorization: `Bearer ${accessToken}`,
"content-type": "application/json",
accept: "application/json, text/event-stream",
"mcp-protocol-version": "2025-06-18",
});
if (sessionId) headers.set("mcp-session-id", sessionId);
const answer = await fetch(`${relay}/mcp`, {
method: "POST",
headers,
body: JSON.stringify({
jsonrpc: "2.0",
...(method.startsWith("notifications/") ? {} : { id: (id += 1) }),
method,
params,
}),
});
const text = await answer.text();
const data = answer.headers.get("content-type")?.includes("event-stream")
? text
.split("\n")
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5))
.at(-1)
: text;
let message = null;
try {
message = JSON.parse(data || "null");
} catch {}
return { status: answer.status, sessionId: answer.headers.get("mcp-session-id"), message, text };
}
const started = await mcp(first.access_token, "initialize", {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "mcp-relay-proof", version: "0" },
});
check(
"initialize reaches the deployment's MCP server",
started.status === 200 && Boolean(started.message?.result?.serverInfo),
JSON.stringify(started.message?.result?.serverInfo ?? started.text.slice(0, 200)),
);
const session = started.sessionId;
await mcp(first.access_token, "notifications/initialized", undefined, session);
const tools = await mcp(first.access_token, "tools/list", {}, session);
const names = tools.message?.result?.tools?.map((tool) => tool.name) ?? [];
check(
"tools/list answers with the deployment's tools",
names.length > 0,
(tools.message?.result?.tools ?? [])
.map((tool) => `${tool.name} ${JSON.stringify({ title: tool.title, ...tool.annotations })}`)
.join(", "),
);
const ran = await mcp(
first.access_token,
"tools/call",
{ name: "run", arguments: { script: "async (itx) => itx.whoami()" } },
session,
);
const said = JSON.stringify(ran.message?.result ?? ran.text.slice(0, 300));
check(
"a script runs in the deployment",
ran.message?.result?.isError === false && said.includes(domain.split(".")[0]),
said.slice(0, 240),
);
const direct = await fetch(`${issuer}/mcp`, {
method: "POST",
headers: { authorization: `Bearer ${first.access_token}`, "content-type": "application/json" },
body: "{}",
});
check(
"the relay's token is worth nothing at the deployment itself",
direct.status === 401,
`${direct.status}`,
);
// 7. a refresh at the relay refreshes at the deployment
const second = await token({ grant_type: "refresh_token", refresh_token: first.refresh_token });
check(
"the app refreshes",
Boolean(second.access_token) && second.access_token !== first.access_token,
`${second.status} ${second.error_description || ""}`,
);
const again = await mcp(second.access_token, "tools/list", {}, session);
check(
"the new token reaches the deployment",
again.status === 200 && Boolean(again.message?.result?.tools),
`${again.status}`,
);
console.log(failed ? `\n${failed} failed` : "\nall passed");
process.exit(failed ? 1 : 0);