validate-plugin.mjs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { readFile, readdir, realpath, stat } from "node:fs/promises";
  2. import { isAbsolute, join, relative, resolve, sep } from "node:path";
  3. import { spawn } from "node:child_process";
  4. import { pathToFileURL } from "node:url";
  5. import { parseArgs } from "node:util";
  6. const ROOT_TOKEN = "${CLAUDE_PLUGIN_ROOT}/";
  7. const PLACEHOLDER = /\bTODO\b|\bFIXME\b|<your[-_ ][^>]+>|YOUR_API_KEY/u;
  8. function outside(root, path) {
  9. const value = relative(root, path);
  10. return value === ".." || value.startsWith(`..${sep}`) || isAbsolute(value);
  11. }
  12. /** 附加完整性检查,不复制 ZCode 的 manifest schema。 */
  13. export async function preflightPlugin(path) {
  14. const root = await realpath(path);
  15. const errors = [];
  16. const manifestPath = await realpath(join(root, ".zcode-plugin", "plugin.json"));
  17. if (outside(root, manifestPath)) return ["Manifest symlink escapes outside plugin"];
  18. const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
  19. const resources = [];
  20. function inspect(value) {
  21. if (typeof value === "string") {
  22. if (PLACEHOLDER.test(value)) errors.push("Unresolved TODO/placeholder");
  23. const offset = value.indexOf(ROOT_TOKEN);
  24. if (offset >= 0) resources.push(value.slice(offset + ROOT_TOKEN.length).split(/["'\s]/u)[0]);
  25. } else if (Array.isArray(value)) value.forEach(inspect);
  26. else if (value && typeof value === "object") Object.values(value).forEach(inspect);
  27. }
  28. inspect(manifest);
  29. for (const field of ["skills", "commands", "hooks", "mcpServers"]) {
  30. const value = manifest[field];
  31. for (const entry of Array.isArray(value) ? value : [value])
  32. if (typeof entry === "string") resources.push(entry);
  33. }
  34. const visited = new Set();
  35. const visitedActual = new Set();
  36. while (resources.length) {
  37. const resource = resources.shift();
  38. if (visited.has(resource)) continue;
  39. visited.add(resource);
  40. const candidate = resolve(root, resource);
  41. if (outside(root, candidate)) {
  42. errors.push(`Resource escapes outside plugin: ${resource}`);
  43. continue;
  44. }
  45. try {
  46. const actual = await realpath(candidate);
  47. if (outside(root, actual)) {
  48. errors.push(`Resource symlink escapes outside plugin: ${resource}`);
  49. continue;
  50. }
  51. if (visitedActual.has(actual)) continue;
  52. visitedActual.add(actual);
  53. const info = await stat(actual);
  54. if (info.isDirectory()) {
  55. for (const entry of await readdir(actual)) {
  56. if (entry !== "node_modules" && entry !== ".git") resources.push(join(resource, entry));
  57. }
  58. } else if (info.isFile() && /\.(?:json|md|mjs|cjs|js|ts|txt|yaml|yml|toml)$/u.test(actual)) {
  59. const text = await readFile(actual, "utf8");
  60. if (actual.endsWith(".json")) inspect(JSON.parse(text));
  61. else if (PLACEHOLDER.test(text)) errors.push(`Unresolved placeholder: ${resource}`);
  62. }
  63. } catch (error) {
  64. errors.push(`Resource unavailable: ${resource}: ${error.message}`);
  65. }
  66. }
  67. return errors;
  68. }
  69. export async function validatePlugin(path, cli = "zcode") {
  70. const errors = await preflightPlugin(path);
  71. if (errors.length) throw new Error(errors.join("\n"));
  72. const nodeEntry = /\.[cm]?js$/u.test(cli);
  73. if (process.platform === "win32" && /\.cmd$/iu.test(cli))
  74. throw new Error("Use --cli with zcode.exe or the CLI JavaScript entrypoint on Windows");
  75. const args = [...(nodeEntry ? [cli] : []), "plugins", "validate", resolve(path)];
  76. const code = await new Promise((accept, reject) => {
  77. const child = spawn(nodeEntry ? process.execPath : cli, args, {
  78. stdio: "inherit",
  79. shell: false,
  80. });
  81. child.once("error", reject);
  82. child.once("close", (exitCode) => accept(exitCode ?? 1));
  83. });
  84. if (code !== 0) throw new Error(`ZCode plugin validation failed (${code})`);
  85. }
  86. async function main() {
  87. const { values, positionals } = parseArgs({
  88. allowPositionals: true,
  89. options: { cli: { type: "string" } },
  90. });
  91. if (positionals.length !== 1)
  92. throw new Error(
  93. "Usage: node validate-plugin.mjs <plugin-path> [--cli zcode-executable-or-js-entry]",
  94. );
  95. await validatePlugin(positionals[0], values.cli);
  96. }
  97. if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href)
  98. main().catch((error) => {
  99. console.error(error.message);
  100. process.exitCode = 1;
  101. });