plugin-runtime-env-agent.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { createHash } from "node:crypto";
  2. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  3. import { dirname, join } from "node:path";
  4. import { DEFAULT_PLUGIN_MARKETPLACES } from "@zcode/shared";
  5. import { getE2EAppDataPaths } from "./desktop-app.js";
  6. export const PLUGIN_RUNTIME_ENV_MARKETPLACE_ID =
  7. "e2e-plugin-runtime-env-market";
  8. export const PLUGIN_RUNTIME_ENV_NAME = "e2e-plugin-secret-agent";
  9. export const PLUGIN_RUNTIME_ENV_ID = `${PLUGIN_RUNTIME_ENV_NAME}@${PLUGIN_RUNTIME_ENV_MARKETPLACE_ID}`;
  10. export const PLUGIN_RUNTIME_ENV_VARIABLE = "E2E_PLUGIN_RUNTIME_SECRET";
  11. export const PLUGIN_RUNTIME_ENV_RESOLVED_MARKER =
  12. "E2E_PLUGIN_RUNTIME_SECRET_RESOLVED";
  13. export const PLUGIN_RUNTIME_ENV_TOOL_NAME =
  14. "mcp__plugin_e2e-plugin-secret-agent_secret-verifier__verify_secret_env";
  15. export const PLUGIN_RUNTIME_ENV_AGENT_NAME = `${PLUGIN_RUNTIME_ENV_NAME}:secret-auditor`;
  16. export const PLUGIN_RUNTIME_ENV_AGENT_BARE_NAME = "secret-auditor";
  17. export interface PluginRuntimeEnvFixture {
  18. marketplaceRoot: string;
  19. }
  20. export async function createPluginRuntimeEnvFixture(
  21. expectedSecret: string,
  22. ): Promise<PluginRuntimeEnvFixture> {
  23. const { homeDir } = getE2EAppDataPaths();
  24. await primeDefaultPluginMarketplacesForE2E(homeDir);
  25. const marketplaceRoot = join(
  26. homeDir,
  27. "fixtures",
  28. PLUGIN_RUNTIME_ENV_MARKETPLACE_ID,
  29. );
  30. const pluginRoot = join(marketplaceRoot, "plugins", PLUGIN_RUNTIME_ENV_NAME);
  31. await rm(marketplaceRoot, { force: true, recursive: true });
  32. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  33. name: PLUGIN_RUNTIME_ENV_NAME,
  34. version: "1.0.0",
  35. description: "E2E plugin MCP secret env and agent projection fixture",
  36. agents: "agents",
  37. mcpServers: {
  38. "secret-verifier": {
  39. type: "stdio",
  40. command: "node",
  41. args: ["${ZCODE_PLUGIN_ROOT}/server.mjs"],
  42. env: {
  43. [PLUGIN_RUNTIME_ENV_VARIABLE]: `\${${PLUGIN_RUNTIME_ENV_VARIABLE}}`,
  44. },
  45. },
  46. },
  47. });
  48. await writeText(
  49. join(pluginRoot, "agents", `${PLUGIN_RUNTIME_ENV_AGENT_BARE_NAME}.md`),
  50. [
  51. "---",
  52. `name: ${PLUGIN_RUNTIME_ENV_AGENT_BARE_NAME}`,
  53. "description: Verifies plugin agent resource identity",
  54. "tools:",
  55. " - Read",
  56. "---",
  57. "Report the plugin agent identity.",
  58. ].join("\n"),
  59. );
  60. await writeText(
  61. join(pluginRoot, "server.mjs"),
  62. buildSecretVerifierServer(
  63. createHash("sha256").update(expectedSecret).digest("hex"),
  64. ),
  65. );
  66. await writeJson(join(marketplaceRoot, ".claude-plugin", "marketplace.json"), {
  67. name: PLUGIN_RUNTIME_ENV_MARKETPLACE_ID,
  68. description: "E2E Plugin Runtime Env Market",
  69. plugins: [
  70. {
  71. name: PLUGIN_RUNTIME_ENV_NAME,
  72. version: "1.0.0",
  73. description: "Plugin MCP secret env and agent projection fixture",
  74. source: `./plugins/${PLUGIN_RUNTIME_ENV_NAME}`,
  75. },
  76. ],
  77. });
  78. return { marketplaceRoot };
  79. }
  80. async function primeDefaultPluginMarketplacesForE2E(homeDir: string): Promise<void> {
  81. const path = join(
  82. homeDir,
  83. ".zcode",
  84. "cli",
  85. "plugins",
  86. "known_marketplaces.json",
  87. );
  88. const existing = await readKnownMarketplaceRecords(path);
  89. const now = new Date().toISOString();
  90. const byId = new Map(existing.map((record) => [record.id, record]));
  91. for (const marketplace of DEFAULT_PLUGIN_MARKETPLACES) {
  92. const current = byId.get(marketplace.id);
  93. byId.set(marketplace.id, {
  94. ...(current ?? {
  95. addedAt: now,
  96. id: marketplace.id,
  97. name: marketplace.name,
  98. source: marketplace.source.includes(":")
  99. ? { source: "url", url: marketplace.source }
  100. : { repo: marketplace.source, source: "github" },
  101. }),
  102. // 修复原因:该 case 只验证本地插件,若默认市场未标记为已加载,设置页会并发 clone
  103. // GitHub 官方市场并占住插件协议请求,导致本地市场已落盘但添加弹窗无法收尾。
  104. lastUpdated: current?.lastUpdated ?? now,
  105. pluginCount: Math.max(1, current?.pluginCount ?? marketplace.pluginCount),
  106. });
  107. }
  108. await writeJson(path, {
  109. version: 1,
  110. marketplaces: [...byId.values()],
  111. });
  112. }
  113. async function readKnownMarketplaceRecords(
  114. path: string,
  115. ): Promise<Array<Record<string, unknown> & { id: string; pluginCount?: number }>> {
  116. try {
  117. const parsed = JSON.parse(await readFile(path, "utf-8")) as {
  118. marketplaces?: unknown;
  119. };
  120. if (!Array.isArray(parsed.marketplaces)) return [];
  121. return parsed.marketplaces.filter(
  122. (
  123. record,
  124. ): record is Record<string, unknown> & {
  125. id: string;
  126. pluginCount?: number;
  127. } =>
  128. typeof record === "object" &&
  129. record !== null &&
  130. typeof (record as { id?: unknown }).id === "string",
  131. );
  132. } catch {
  133. return [];
  134. }
  135. }
  136. function buildSecretVerifierServer(expectedSecretHash: string): string {
  137. return `#!/usr/bin/env node
  138. import { createHash } from "node:crypto";
  139. import readline from "node:readline";
  140. const actual = process.env.${PLUGIN_RUNTIME_ENV_VARIABLE} || "";
  141. const resolved = createHash("sha256").update(actual).digest("hex") === ${JSON.stringify(expectedSecretHash)};
  142. const input = readline.createInterface({ input: process.stdin });
  143. function send(message) { process.stdout.write(JSON.stringify(message) + "\\n"); }
  144. input.on("line", (line) => {
  145. let request;
  146. try { request = JSON.parse(line); } catch { return; }
  147. if (request.method === "initialize") {
  148. send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "e2e-plugin-secret-agent", version: "1.0.0" } } });
  149. return;
  150. }
  151. if (request.method === "tools/list") {
  152. send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "verify_secret_env", description: "Return only whether the plugin secret environment was resolved", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } }] } });
  153. return;
  154. }
  155. if (request.method === "tools/call") {
  156. send({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: resolved ? ${JSON.stringify(PLUGIN_RUNTIME_ENV_RESOLVED_MARKER)} : "E2E_PLUGIN_RUNTIME_SECRET_UNRESOLVED" }] } });
  157. return;
  158. }
  159. if (request.id !== undefined) send({ jsonrpc: "2.0", id: request.id, result: {} });
  160. });
  161. `;
  162. }
  163. async function writeJson(path: string, value: unknown): Promise<void> {
  164. await writeText(path, `${JSON.stringify(value, null, 2)}\n`);
  165. }
  166. async function writeText(path: string, value: string): Promise<void> {
  167. await mkdir(dirname(path), { recursive: true });
  168. await writeFile(path, value, "utf-8");
  169. }