mcp-official-auth-routing-fixture.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { once } from "node:events";
  2. import { mkdir, readFile, writeFile } from "node:fs/promises";
  3. import { createServer } from "node:http";
  4. import { dirname, join } from "node:path";
  5. import { prepareWebRemoteControlSessionEventsFixture } from "#e2e/helpers/web-remote-control-session-events-fixture";
  6. export const OFFICIAL_AUTH_ROUTING_PLUGIN = "e2e-official-auth";
  7. export const OFFICIAL_AUTH_ROUTING_SERVER = `plugin:${OFFICIAL_AUTH_ROUTING_PLUGIN}:identity`;
  8. /** 外部账号、relay 与 MCP 使用隔离夹具,Host/CLI/反向授权仍走真实产品链路。 */
  9. export async function prepareOfficialMcpAuthRoutingFixture(options: {
  10. specs: string[];
  11. credentialsFile: string;
  12. settingsFile: string;
  13. workspacePath: string;
  14. }): Promise<(() => Promise<void>) | null> {
  15. if (!options.specs.some((spec) => spec.endsWith("mcp-official-auth-routing.test.ts")))
  16. return null;
  17. const stopRemote = await prepareWebRemoteControlSessionEventsFixture({
  18. ...options,
  19. webUrl: "http://127.0.0.1:0/remote/v4",
  20. });
  21. const requests: Array<{ method: string; authenticated: boolean }> = [];
  22. const server = createServer(async (request, response) => {
  23. response.setHeader("content-type", "application/json");
  24. if (request.url === "/__e2e/status") {
  25. response.end(JSON.stringify({ requests }));
  26. return;
  27. }
  28. if (request.method === "GET") {
  29. response.writeHead(405);
  30. response.end();
  31. return;
  32. }
  33. const chunks: Buffer[] = [];
  34. for await (const chunk of request) chunks.push(Buffer.from(chunk));
  35. const message = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
  36. id?: string | number;
  37. method: string;
  38. params?: { protocolVersion?: string };
  39. };
  40. const authenticated = request.headers.authorization === "Bearer mock-token";
  41. requests.push({ method: message.method, authenticated });
  42. if (message.id === undefined) {
  43. response.writeHead(202);
  44. response.end();
  45. return;
  46. }
  47. const result = !authenticated
  48. ? { error: { code: 1006, message: "not authenticated" } }
  49. : {
  50. result:
  51. message.method === "initialize"
  52. ? {
  53. protocolVersion: message.params?.protocolVersion ?? "2025-11-25",
  54. capabilities: { tools: {} },
  55. serverInfo: { name: "official-auth-routing-fixture", version: "1.0.0" },
  56. }
  57. : message.method === "tools/list"
  58. ? {
  59. tools: [
  60. {
  61. name: "identity",
  62. description: "E2E authenticated control-plane fixture",
  63. inputSchema: { type: "object", properties: {} },
  64. },
  65. ],
  66. }
  67. : {},
  68. };
  69. response.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, ...result }));
  70. });
  71. let previous: Record<string, string | undefined> = {};
  72. const cleanup = async () => {
  73. if (server.listening) {
  74. server.closeAllConnections();
  75. await new Promise<void>((resolve, reject) =>
  76. server.close((error) => (error ? reject(error) : resolve())),
  77. );
  78. }
  79. for (const [key, value] of Object.entries(previous)) {
  80. if (value === undefined) delete process.env[key];
  81. else process.env[key] = value;
  82. }
  83. await stopRemote();
  84. };
  85. try {
  86. server.listen(0, "127.0.0.1");
  87. await once(server, "listening");
  88. const address = server.address();
  89. if (!address || typeof address === "string") throw new Error("Missing MCP fixture address");
  90. const baseUrl = `http://127.0.0.1:${address.port}`;
  91. const envPatch = {
  92. ZCODE_E2E_OFFICIAL_AUTH_ROUTING_URL: baseUrl,
  93. ZCODE_OFFICIAL_MCP_DEV_TRUSTED_ORIGINS: baseUrl,
  94. };
  95. previous = Object.fromEntries(Object.keys(envPatch).map((key) => [key, process.env[key]]));
  96. Object.assign(process.env, envPatch);
  97. const storageRoot = dirname(dirname(options.credentialsFile));
  98. const pluginId = `${OFFICIAL_AUTH_ROUTING_PLUGIN}@e2e-fixture`;
  99. const pluginRoot = join(storageRoot, "cli", "e2e-fixtures", OFFICIAL_AUTH_ROUTING_PLUGIN);
  100. await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  101. await writeFile(
  102. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  103. JSON.stringify({
  104. name: OFFICIAL_AUTH_ROUTING_PLUGIN,
  105. version: "0.0.0",
  106. mcpServers: {
  107. identity: {
  108. type: "http",
  109. url: `${baseUrl}/mcp`,
  110. protocolVersion: "legacy",
  111. auth: { type: "zcode_official", provider: "jwt_token" },
  112. },
  113. },
  114. }),
  115. );
  116. const installedPath = join(storageRoot, "cli", "plugins", "installed_plugins.json");
  117. await mkdir(dirname(installedPath), { recursive: true });
  118. await writeFile(
  119. installedPath,
  120. JSON.stringify({
  121. version: 1,
  122. plugins: [
  123. {
  124. id: pluginId,
  125. name: OFFICIAL_AUTH_ROUTING_PLUGIN,
  126. installPath: pluginRoot,
  127. marketplace: "e2e-fixture",
  128. scope: "user",
  129. version: "0.0.0",
  130. installedAt: "2026-10-30T00:00:00.000Z",
  131. updatedAt: "2026-10-30T00:00:00.000Z",
  132. },
  133. ],
  134. }),
  135. );
  136. const configPath = join(storageRoot, "cli", "config.json");
  137. const config = JSON.parse(
  138. await readFile(configPath, "utf8").catch((error: NodeJS.ErrnoException) => {
  139. if (error.code !== "ENOENT") throw error;
  140. return "{}";
  141. }),
  142. );
  143. config.plugins = {
  144. ...config.plugins,
  145. enabledPlugins: { ...config.plugins?.enabledPlugins, [pluginId]: true },
  146. };
  147. await writeFile(configPath, JSON.stringify(config));
  148. return cleanup;
  149. } catch (error) {
  150. await cleanup();
  151. throw error;
  152. }
  153. }