plugin-secrets.adapter.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Plugin Secrets Adapter - 敏感选项与全部项目选项的私有文件(plugin-compat.md「Sensitive Option Storage」)。
  2. //
  3. // 启动与动态 MCP 共用读取、分层合并规则;保存时哪些键属于敏感值由 bootstrap 决定。
  4. // 任何错误信息与返回的诊断原因都不带值。
  5. import { readFile } from "node:fs/promises";
  6. import { dirname, join, resolve, win32 } from "node:path";
  7. import { z } from "zod";
  8. import { atomicWritePrivateTextFile, backupCorruptFile, withFileLock } from "@zcode/shared/node";
  9. import type { PluginOptionLayer } from "./config-factory.js";
  10. export const PLUGIN_SECRETS_FILE_NAME = "plugin-secrets.json";
  11. const PLUGIN_SECRETS_FILE_VERSION = 1;
  12. const JSON_INDENT = 2;
  13. const WINDOWS_PLATFORM = "win32";
  14. const pluginOptionValueSchema = z.union([z.string(), z.number(), z.boolean()]);
  15. const pluginSecretValuesSchema = z.record(
  16. z.string(),
  17. z.record(z.string(), pluginOptionValueSchema),
  18. );
  19. const pluginSecretsFileSchema = z
  20. .object({
  21. version: z.literal(PLUGIN_SECRETS_FILE_VERSION),
  22. user: pluginSecretValuesSchema,
  23. workspaces: z.record(z.string(), pluginSecretValuesSchema),
  24. })
  25. .strict();
  26. export type PluginSecretValue = z.infer<typeof pluginOptionValueSchema>;
  27. /** pluginId → key → value。 */
  28. export type PluginSecretValues = z.infer<typeof pluginSecretValuesSchema>;
  29. export type PluginSecretsFile = z.infer<typeof pluginSecretsFileSchema>;
  30. export type PluginSecretsScope = { kind: "user" } | { kind: "workspace"; root: string };
  31. /** 读取结果:读不出时一律按空文件处理,原因只区分「损坏」与「I/O 失败」。 */
  32. export type PluginSecretsReadResult =
  33. | { status: "ok"; file: PluginSecretsFile }
  34. | { status: "unreadable"; reason: "corrupt" | "io"; file: PluginSecretsFile };
  35. export function createEmptyPluginSecretsFile(): PluginSecretsFile {
  36. return { version: PLUGIN_SECRETS_FILE_VERSION, user: {}, workspaces: {} };
  37. }
  38. /**
  39. * 插件配置路径与 workspace root 的比较键:Windows 不区分大小写、分隔符统一为 `/`。
  40. * workspace 配置路径匹配与私有文件的 workspace 键共用这一条规则。
  41. */
  42. export function normalizePluginConfigPathForComparison(
  43. path: string,
  44. platform: NodeJS.Platform = process.platform,
  45. ): string {
  46. if (platform !== WINDOWS_PLATFORM) return resolve(path);
  47. return win32.resolve(path).replaceAll("\\", "/").toLowerCase();
  48. }
  49. /**
  50. * 读取路径(无锁):写入是原子 rename,读者只会看到旧文件或新文件。
  51. * 损坏时先备份再按空处理;备份失败不影响读取(原文件仍在,下次写入前会再备份)。
  52. */
  53. export async function readPluginSecretsFile(path: string): Promise<PluginSecretsReadResult> {
  54. let raw: string;
  55. try {
  56. raw = await readFile(path, "utf8");
  57. } catch (error) {
  58. if (getErrorCode(error) === "ENOENT") {
  59. return { status: "ok", file: createEmptyPluginSecretsFile() };
  60. }
  61. return { status: "unreadable", reason: "io", file: createEmptyPluginSecretsFile() };
  62. }
  63. const parsed = parsePluginSecretsFile(raw);
  64. if (parsed) return { status: "ok", file: parsed };
  65. await backupCorruptFile(path).catch(() => undefined);
  66. return { status: "unreadable", reason: "corrupt", file: createEmptyPluginSecretsFile() };
  67. }
  68. /**
  69. * 在文件锁内读改写。损坏的文件先备份(失败则抛错,不覆盖读不出的证据)再按空处理;
  70. * 损坏以外的读取错误向上抛。内容不变且原文件有效时不写盘,避免为空操作创建文件。
  71. */
  72. export async function updatePluginSecretsFile(
  73. path: string,
  74. mutate: (file: PluginSecretsFile) => PluginSecretsFile,
  75. ): Promise<void> {
  76. await withFileLock(path, async () => {
  77. const current = await readPluginSecretsFileForWrite(path);
  78. const next = prunePluginSecretsFile(mutate(current.file));
  79. if (!current.corrupt && JSON.stringify(next) === JSON.stringify(current.file)) return;
  80. await atomicWritePrivateTextFile(path, `${JSON.stringify(next, null, JSON_INDENT)}\n`);
  81. });
  82. }
  83. /** 某个 scope 下全部插件的私有值;workspace 按规范化后的 root 匹配。 */
  84. export function getPluginSecretsForScope(
  85. file: PluginSecretsFile,
  86. scope: PluginSecretsScope,
  87. ): PluginSecretValues {
  88. if (scope.kind === "user") return file.user;
  89. const target = normalizePluginConfigPathForComparison(scope.root);
  90. const merged: PluginSecretValues = {};
  91. // 键按规范化比较,兼容手工编辑留下的大小写或分隔符差异。
  92. for (const [root, values] of Object.entries(file.workspaces)) {
  93. if (normalizePluginConfigPathForComparison(root) !== target) continue;
  94. for (const [pluginId, pluginValues] of Object.entries(values)) {
  95. merged[pluginId] = { ...merged[pluginId], ...pluginValues };
  96. }
  97. }
  98. return merged;
  99. }
  100. /** 写入一个插件在某个 scope 的私有值:先删 clearKeys,再写 values(与 config.json 的合并语义一致)。 */
  101. export function setPluginSecrets(
  102. file: PluginSecretsFile,
  103. scope: PluginSecretsScope,
  104. pluginId: string,
  105. values: Record<string, PluginSecretValue>,
  106. clearKeys: readonly string[],
  107. ): PluginSecretsFile {
  108. const clear = new Set(clearKeys);
  109. const current = getPluginSecretsForScope(file, scope)[pluginId] ?? {};
  110. const nextPluginValues = {
  111. ...Object.fromEntries(Object.entries(current).filter(([key]) => !clear.has(key))),
  112. ...values,
  113. };
  114. if (scope.kind === "user") {
  115. return { ...file, user: { ...file.user, [pluginId]: nextPluginValues } };
  116. }
  117. const target = normalizePluginConfigPathForComparison(scope.root);
  118. const scopeValues = { ...getPluginSecretsForScope(file, scope), [pluginId]: nextPluginValues };
  119. return {
  120. ...file,
  121. workspaces: {
  122. ...withoutWorkspaceRoot(file.workspaces, target),
  123. [target]: scopeValues,
  124. },
  125. };
  126. }
  127. /** 删除一个插件的私有值:指定 scope,或 `"all"`(user 与全部 workspaces,用于卸载)。 */
  128. export function removePluginSecrets(
  129. file: PluginSecretsFile,
  130. pluginId: string,
  131. scope: PluginSecretsScope | "all",
  132. ): PluginSecretsFile {
  133. const removeFrom = (values: PluginSecretValues): PluginSecretValues =>
  134. Object.fromEntries(Object.entries(values).filter(([id]) => id !== pluginId));
  135. if (scope === "all") {
  136. return {
  137. ...file,
  138. user: removeFrom(file.user),
  139. workspaces: Object.fromEntries(
  140. Object.entries(file.workspaces).map(([root, values]) => [root, removeFrom(values)]),
  141. ),
  142. };
  143. }
  144. if (scope.kind === "user") return { ...file, user: removeFrom(file.user) };
  145. const target = normalizePluginConfigPathForComparison(scope.root);
  146. return {
  147. ...file,
  148. workspaces: Object.fromEntries(
  149. Object.entries(file.workspaces).map(([root, values]) => [
  150. root,
  151. normalizePluginConfigPathForComparison(root) === target ? removeFrom(values) : values,
  152. ]),
  153. ),
  154. };
  155. }
  156. function withoutWorkspaceRoot(
  157. workspaces: PluginSecretsFile["workspaces"],
  158. normalizedRoot: string,
  159. ): PluginSecretsFile["workspaces"] {
  160. return Object.fromEntries(
  161. Object.entries(workspaces).filter(
  162. ([root]) => normalizePluginConfigPathForComparison(root) !== normalizedRoot,
  163. ),
  164. );
  165. }
  166. /** 去掉空的插件条目与空的 workspace 条目,卸载或清除后不留空壳。 */
  167. function prunePluginSecretsFile(file: PluginSecretsFile): PluginSecretsFile {
  168. const pruneValues = (values: PluginSecretValues): PluginSecretValues =>
  169. Object.fromEntries(
  170. Object.entries(values).filter(([, pluginValues]) => Object.keys(pluginValues).length > 0),
  171. );
  172. return {
  173. version: PLUGIN_SECRETS_FILE_VERSION,
  174. user: pruneValues(file.user),
  175. workspaces: Object.fromEntries(
  176. Object.entries(file.workspaces)
  177. .map(([root, values]) => [root, pruneValues(values)] as const)
  178. .filter(([, values]) => Object.keys(values).length > 0),
  179. ),
  180. };
  181. }
  182. async function readPluginSecretsFileForWrite(
  183. path: string,
  184. ): Promise<{ file: PluginSecretsFile; corrupt: boolean }> {
  185. let raw: string;
  186. try {
  187. raw = await readFile(path, "utf8");
  188. } catch (error) {
  189. if (getErrorCode(error) === "ENOENT") {
  190. return { file: createEmptyPluginSecretsFile(), corrupt: false };
  191. }
  192. throw error;
  193. }
  194. const parsed = parsePluginSecretsFile(raw);
  195. if (parsed) return { file: parsed, corrupt: false };
  196. await backupCorruptFile(path);
  197. return { file: createEmptyPluginSecretsFile(), corrupt: true };
  198. }
  199. function parsePluginSecretsFile(raw: string): PluginSecretsFile | undefined {
  200. let value: unknown;
  201. try {
  202. value = JSON.parse(raw);
  203. } catch {
  204. return undefined;
  205. }
  206. const parsed = pluginSecretsFileSchema.safeParse(value);
  207. return parsed.success ? parsed.data : undefined;
  208. }
  209. function getErrorCode(error: unknown): string | undefined {
  210. if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
  211. const code = (error as { code?: unknown }).code;
  212. return typeof code === "string" ? code : undefined;
  213. }
  214. /**
  215. * 私有文件与插件存储目录 `plugins/` 同级。默认就是 `<cli storage root>/plugin-secrets.json`;
  216. * 调用方覆盖插件存储目录(测试、嵌入)时文件跟着走,不会写进真实的用户目录。
  217. */
  218. export function resolvePluginSecretsPath(pluginStorageRoot: string): string {
  219. return join(dirname(pluginStorageRoot), PLUGIN_SECRETS_FILE_NAME);
  220. }
  221. /** 启动与动态重载共用同一套来源优先级;仓库文件不能成为运行参数的来源。 */
  222. export function resolvePluginSecretOverrides(
  223. layers: readonly PluginOptionLayer[],
  224. file: PluginSecretsFile,
  225. ) {
  226. const layerSecrets = layers.map((layer) => getPluginSecretsForScope(file, toSecretsScope(layer)));
  227. const overrides: Array<{
  228. pluginId: string;
  229. key: string;
  230. scope: PluginOptionLayer["scope"];
  231. value: PluginSecretValue;
  232. }> = [];
  233. for (const [pluginId, keys] of collectSecretKeys(layerSecrets)) {
  234. for (const key of keys) {
  235. const winner = resolveLayeredValue(layers, layerSecrets, pluginId, key);
  236. if (winner) overrides.push({ pluginId, key, ...winner });
  237. }
  238. }
  239. return overrides;
  240. }
  241. function toSecretsScope(layer: PluginOptionLayer): PluginSecretsScope {
  242. return layer.scope === "workspace" && layer.workspaceRoot
  243. ? { kind: "workspace", root: layer.workspaceRoot }
  244. : { kind: "user" };
  245. }
  246. function collectSecretKeys(layerSecrets: readonly PluginSecretValues[]): Map<string, Set<string>> {
  247. const touched = new Map<string, Set<string>>();
  248. for (const secrets of layerSecrets) {
  249. for (const [pluginId, values] of Object.entries(secrets)) {
  250. const keys = touched.get(pluginId) ?? new Set<string>();
  251. for (const key of Object.keys(values)) keys.add(key);
  252. touched.set(pluginId, keys);
  253. }
  254. }
  255. return touched;
  256. }
  257. function resolveLayeredValue(
  258. layers: readonly PluginOptionLayer[],
  259. layerSecrets: readonly PluginSecretValues[],
  260. pluginId: string,
  261. key: string,
  262. ): { scope: PluginOptionLayer["scope"]; value: PluginSecretValue } | undefined {
  263. for (let index = layers.length - 1; index >= 0; index -= 1) {
  264. const layer = layers[index];
  265. if (!layer) continue;
  266. const secret = layerSecrets[index]?.[pluginId]?.[key];
  267. if (secret !== undefined) return { scope: layer.scope, value: secret };
  268. // 项目文件不提供任何运行时选项,即使调用方传入的是旧的配置快照,也不能覆盖用户私有值。
  269. const plain = layer.scope === "user" ? layer.options[pluginId]?.[key] : undefined;
  270. if (plain !== undefined) return { scope: layer.scope, value: plain };
  271. }
  272. return undefined;
  273. }