plugin-extension-settings.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // PLM-EXT-P2D:插件设置与扩展的 settings 能力(docs/plugins/extension-host.md §16.7;存储见 CLI spec
  2. // apps/zcode-cli/docs/design/v2/plugin-compat.md「Sensitive Option Storage」)。
  3. // 隔离 HOME:两个纯 JS fixture 扩展(test/e2e/fixtures/fs/plugins/plugin-extension-settings/)经 plugins.dirs 加载:
  4. // - e2e-ext-settings:userConfig 有敏感键 token 与普通键 region(默认 eu)。env.onDidChange 时调 settings.get,
  5. // 另订阅 settings.onDidChange。日志只有 hasToken、token 长度、region 与键名。
  6. // 视图 account 的工具 login / logout 调 settings.update(P4 H1,§18.1),用例经沙箱页面调这两个工具。
  7. // - e2e-ext-settings-other:只有自己的 mode(默认 lite),验证 settings.get 拿不到别的插件的值,
  8. // settings.update 写不了不属于它的键(第一次 env 时试写,都应报 invalid-input)。
  9. // 设置经真实的设置页(插件管理详情 → 高级)保存与清除。不需要模型。
  10. // 运行时证据:Main 日志([extensions] / fixture 的 E2E_SETTINGS_*)、隔离 HOME 的 config.json 与
  11. // plugin-secrets.json、设置页 DOM;扫描隔离 HOME 与 App 数据目录,token 原文只能出现在 plugin-secrets.json。
  12. import { randomUUID } from "node:crypto";
  13. import { cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
  14. import { join, resolve } from "node:path";
  15. import {
  16. TID_NAV_PRIMARY_ITEM,
  17. TID_SETTINGS_BACK_BUTTON,
  18. TID_SIDE_PANE_EXTENSION_VIEW_ITEM,
  19. } from "@zcode/shared/test-ids";
  20. import {
  21. DEFAULT_WORKSPACE,
  22. clearAppData,
  23. clickTestIdByDom,
  24. getE2EAppDataPaths,
  25. } from "#e2e/helpers/desktop-app";
  26. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  27. import {
  28. createExtensionLog,
  29. evaluateInViewPage,
  30. openLauncher,
  31. openLauncherView,
  32. waitForViewPane,
  33. writePluginDirsConfig,
  34. } from "#e2e/helpers/extension-host-views";
  35. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  36. import {
  37. capturePluginManualReview,
  38. clickPluginControl,
  39. openInstalledPluginSettingsAdvanced,
  40. openPluginManagementSettings,
  41. requirePluginManualReview,
  42. setPluginPresentation,
  43. waitForPluginControl,
  44. } from "#e2e/helpers/plugin-management-lifecycle";
  45. const CASE_ID = "PLM-EXT-P2D";
  46. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  47. const FIXTURE_ROOT = resolve(
  48. process.cwd(),
  49. "test/e2e/fixtures/fs/plugins/plugin-extension-settings",
  50. );
  51. const PLUGINS = ["e2e-ext-settings", "e2e-ext-settings-other"];
  52. const PLUGIN_ID = "e2e-ext-settings@inline";
  53. // 每次运行一个新值:扫描泄露时不会被历史文件误判。
  54. const TOKEN = `E2E-SECRET-${randomUUID()}`;
  55. // settings.update 写入的第二个值(P4 H1):与设置页保存的值不同,扫描时能分开判断。
  56. const UPDATE_TOKEN = `E2E-UPDATE-${randomUUID()}`;
  57. const REGION = "us-east";
  58. const UPDATED_REGION = "ap-south";
  59. const ACCOUNT_VIEW = `${PLUGIN_ID}/account`;
  60. const evidence: Record<string, unknown> = {};
  61. const log = createExtensionLog();
  62. function cliPath(...segments: string[]): string {
  63. return join(getE2EAppDataPaths().homeDir, ".zcode", "cli", ...segments);
  64. }
  65. async function seedFixtures(): Promise<void> {
  66. const target = join(getE2EAppDataPaths().homeDir, "fixtures", "extension-settings");
  67. await mkdir(target, { recursive: true });
  68. for (const name of PLUGINS) {
  69. await cp(join(FIXTURE_ROOT, name), join(target, name), { recursive: true, force: true });
  70. }
  71. await writePluginDirsConfig(
  72. PLUGINS.map((name) => join(target, name)),
  73. PLUGINS.map((name) => `${name}@inline`),
  74. );
  75. }
  76. async function readJson(path: string): Promise<Record<string, unknown>> {
  77. return JSON.parse(await readFile(path, "utf8").catch(() => "{}")) as Record<string, unknown>;
  78. }
  79. /** `~/.zcode/cli/config.json` 里本插件 user 层的选项。 */
  80. async function readConfigOptions(): Promise<Record<string, unknown>> {
  81. const config = await readJson(cliPath("config.json"));
  82. const plugins = (config.plugins ?? {}) as { options?: Record<string, Record<string, unknown>> };
  83. return plugins.options?.[PLUGIN_ID] ?? {};
  84. }
  85. /** `~/.zcode/cli/plugin-secrets.json` 里本插件 user 层的敏感值。 */
  86. async function readSecretOptions(): Promise<Record<string, unknown>> {
  87. const secrets = (await readJson(cliPath("plugin-secrets.json"))) as {
  88. user?: Record<string, Record<string, unknown>>;
  89. };
  90. return secrets.user?.[PLUGIN_ID] ?? {};
  91. }
  92. async function setConfigInput(configKey: string, value: string): Promise<void> {
  93. await waitForPluginControl("plugin-store-config-input", { configKey });
  94. const done = await browser.execute(
  95. (key, next) => {
  96. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  97. (candidate) =>
  98. candidate.dataset.testid === "plugin-store-config-input" &&
  99. candidate.dataset.configKey === key,
  100. );
  101. if (!(element instanceof HTMLInputElement)) return false;
  102. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
  103. element,
  104. next,
  105. );
  106. element.dispatchEvent(new InputEvent("input", { bubbles: true, data: next }));
  107. element.dispatchEvent(new Event("change", { bubbles: true }));
  108. return true;
  109. },
  110. configKey,
  111. value,
  112. );
  113. if (!done) throw new Error(`could not set the plugin config input ${configKey}`);
  114. }
  115. interface ConfigUi {
  116. tokenInputType: string | null;
  117. tokenValueLength: number;
  118. region: string | null;
  119. clearKeys: string[];
  120. scopes: Record<string, string>;
  121. }
  122. /** 设置页里本插件的配置区:敏感输入框类型、清除按钮、scope 标记(不读 token 值本身)。 */
  123. async function readConfigUi(): Promise<ConfigUi> {
  124. return browser.execute((pluginId) => {
  125. const section = document.querySelector<HTMLElement>(
  126. `[data-testid="plugin-store-config"][data-plugin-id="${pluginId}"]`,
  127. );
  128. const input = (key: string) =>
  129. section?.querySelector<HTMLInputElement>(
  130. `[data-testid="plugin-store-config-input"][data-config-key="${key}"]`,
  131. ) ?? null;
  132. const scopes: Record<string, string> = {};
  133. for (const label of Array.from(section?.querySelectorAll<HTMLElement>("label") ?? [])) {
  134. const key = label.querySelector<HTMLElement>("[data-config-key]")?.dataset.configKey;
  135. const scope =
  136. label.querySelector<HTMLElement>("[data-settings-scope]")?.dataset.settingsScope;
  137. if (key && scope) scopes[key] = scope;
  138. }
  139. return {
  140. tokenInputType: input("token")?.type ?? null,
  141. tokenValueLength: input("token")?.value.length ?? 0,
  142. region: input("region")?.value ?? null,
  143. clearKeys: Array.from(
  144. section?.querySelectorAll<HTMLElement>('[data-testid="plugin-store-config-clear"]') ?? [],
  145. ).map((element) => element.dataset.configKey ?? ""),
  146. scopes,
  147. };
  148. }, PLUGIN_ID);
  149. }
  150. async function waitForConfigUi(
  151. predicate: (ui: ConfigUi) => boolean,
  152. message: string,
  153. ): Promise<ConfigUi> {
  154. let latest: ConfigUi | null = null;
  155. await browser.waitUntil(
  156. async () => {
  157. latest = await readConfigUi();
  158. return predicate(latest);
  159. },
  160. { timeout: 30000, interval: 300, timeoutMsg: `${message}: ${JSON.stringify(latest)}` },
  161. );
  162. return latest!;
  163. }
  164. /** 等 from 行之后出现满足条件的日志行(启动时的语言可能已经是 en-US,旧的探测行不能算)。 */
  165. async function waitForLogAfter(
  166. from: number,
  167. predicate: (line: string) => boolean,
  168. message: string,
  169. ): Promise<string> {
  170. let found = "";
  171. await browser.waitUntil(
  172. async () => {
  173. found = (await log.lines()).slice(from).find(predicate) ?? "";
  174. return Boolean(found);
  175. },
  176. { timeout: 30000, interval: 500, timeoutMsg: message },
  177. );
  178. return found;
  179. }
  180. /** 递归找含 needle 的文件(只读 ≤ 20MB 的文件)。 */
  181. async function findFilesContaining(root: string, needle: string): Promise<string[]> {
  182. const hits: string[] = [];
  183. const bytes = Buffer.from(needle);
  184. const walk = async (dir: string): Promise<void> => {
  185. for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
  186. const path = join(dir, entry.name);
  187. if (entry.isDirectory()) {
  188. if (entry.name !== "node_modules") await walk(path);
  189. } else if (entry.isFile()) {
  190. const info = await stat(path).catch(() => null);
  191. if (!info || info.size > 20 * 1024 * 1024) continue;
  192. const content = await readFile(path).catch(() => null);
  193. if (content?.includes(bytes)) hits.push(path);
  194. }
  195. }
  196. };
  197. await walk(root);
  198. return hits;
  199. }
  200. /** 隔离 HOME、App 数据目录与运行时日志目录里含 needle 的文件。 */
  201. async function scanLeaks(needle: string): Promise<{ roots: string[]; hits: string[] }> {
  202. const { homeDir, appDataDir } = getE2EAppDataPaths();
  203. const roots = [
  204. ...new Set([homeDir, appDataDir, process.env.ZCODE_E2E_RUNTIME_LOG_DIR ?? ""]),
  205. ].filter(Boolean);
  206. const hits = (await Promise.all(roots.map((root) => findFilesContaining(root, needle)))).flat();
  207. return { roots, hits: [...new Set(hits)] };
  208. }
  209. /** `~/.zcode/cli/config.json` 里另一个插件 user 层的选项。 */
  210. async function readOtherConfigOptions(): Promise<Record<string, unknown>> {
  211. const config = await readJson(cliPath("config.json"));
  212. const plugins = (config.plugins ?? {}) as { options?: Record<string, Record<string, unknown>> };
  213. return plugins.options?.["e2e-ext-settings-other@inline"] ?? {};
  214. }
  215. /** 某个元素里第一个 svg 的 class(Lucide 图标带 `lucide-<名字>`)。 */
  216. async function readIconClass(selector: string): Promise<string | null> {
  217. return browser.execute(
  218. (target) => document.querySelector(target)?.querySelector("svg")?.getAttribute("class") ?? null,
  219. selector,
  220. );
  221. }
  222. /** 在 account 视图的沙箱页面里调视图工具(与 GitLab 面板页面调 login 同一条路径),返回 CallToolResult。 */
  223. async function callAccountTool(name: string, args: Record<string, unknown>): Promise<unknown> {
  224. const pane = await waitForViewPane(
  225. ACCOUNT_VIEW,
  226. (item) => item.phase === "running" && item.displayed,
  227. "the account view should be running",
  228. );
  229. const raw = await evaluateInViewPage<string>(
  230. pane.sandbox!,
  231. `window.zcode.ready()
  232. .then(() => window.zcode.callTool(${JSON.stringify(name)}, ${JSON.stringify(args)}))
  233. .then((result) => JSON.stringify(result))`,
  234. );
  235. if (!raw) throw new Error(`the account view did not answer the ${name} tool call`);
  236. return JSON.parse(raw) as unknown;
  237. }
  238. describe("PLM-EXT-P2D 插件设置与扩展的 settings 能力", () => {
  239. after(async () => {
  240. await writeFile(
  241. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-p2d-evidence.json"),
  242. JSON.stringify(evidence, null, 2),
  243. ).catch(() => undefined);
  244. await clearAppData();
  245. });
  246. it("敏感值存私有文件,settings.get 只给本插件,onDidChange 在保存与清除后触发", async function () {
  247. this.timeout(600000);
  248. requirePluginManualReview();
  249. await seedFixtures();
  250. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  251. afterElectronProcessExit: () => log.mark(),
  252. });
  253. await prepareV4ConversationE2E();
  254. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  255. // (a) 保存前:settings.get 只有默认值。
  256. evidence.initialProbe = await log.waitFor(
  257. (line) =>
  258. line.includes("E2E_SETTINGS_PROBE plugin=e2e-ext-settings ") &&
  259. line.includes("locale=zh-CN"),
  260. "the settings extension should read its defaults",
  261. 60000,
  262. );
  263. expect(String(evidence.initialProbe)).toContain("hasToken=false tokenLength=0 region=eu");
  264. evidence.initialOtherProbe = await log.waitFor(
  265. (line) =>
  266. line.includes("E2E_SETTINGS_PROBE plugin=e2e-ext-settings-other") &&
  267. line.includes("locale=zh-CN"),
  268. "the other extension should read its own defaults",
  269. 60000,
  270. );
  271. expect(String(evidence.initialOtherProbe)).toContain("hasToken=false mode=lite keys=mode");
  272. // (b) 设置页保存两个键:普通值进 config.json,敏感值只进 plugin-secrets.json。
  273. await openPluginManagementSettings();
  274. await openInstalledPluginSettingsAdvanced(PLUGIN_ID);
  275. const before = await waitForConfigUi(
  276. (ui) => ui.tokenInputType !== null,
  277. "the plugin settings should show the config fields",
  278. );
  279. evidence.configUiBefore = before;
  280. expect(before.tokenInputType).toBe("password");
  281. expect(before.scopes).toMatchObject({ token: "default", region: "default" });
  282. await capturePluginManualReview(CASE_ID, "settings-before-zh-CN-zai-light");
  283. const linesBeforeSave = (await log.lines()).length;
  284. await setConfigInput("token", TOKEN);
  285. await setConfigInput("region", REGION);
  286. await clickPluginControl("plugin-store-config-save", { pluginId: PLUGIN_ID });
  287. await browser.waitUntil(async () => (await readConfigOptions()).region === REGION, {
  288. timeout: 30000,
  289. timeoutMsg: "region should be saved in config.json",
  290. });
  291. const configOptions = await readConfigOptions();
  292. const secretOptions = await readSecretOptions();
  293. evidence.configOptions = configOptions;
  294. evidence.secretKeys = Object.keys(secretOptions);
  295. expect(configOptions).toEqual({ region: REGION });
  296. expect(secretOptions.token).toBe(TOKEN);
  297. expect(JSON.stringify(await readJson(cliPath("config.json")))).not.toContain(TOKEN);
  298. // (c) onDidChange:保存成功后本插件收到新值。
  299. evidence.changedLog = await log.waitFor(
  300. (line) => line.includes("E2E_SETTINGS_CHANGED plugin=e2e-ext-settings hasToken=true"),
  301. "settings.onDidChange should fire after saving",
  302. );
  303. expect(String(evidence.changedLog)).toContain(
  304. `tokenLength=${TOKEN.length} region=${REGION} keys=region,token`,
  305. );
  306. evidence.windowHostSettingsLog = (await log.lines()).filter((line) =>
  307. line.includes("[extensions] settings"),
  308. );
  309. // (e) 设置页:敏感值掩码、user scope 有清除按钮、scope 标记跟着来源变。
  310. const after = await waitForConfigUi(
  311. (ui) => ui.scopes.token === "user" && ui.scopes.region === "user",
  312. "the scope markers should show the user scope after saving",
  313. );
  314. evidence.configUiAfter = after;
  315. expect(after.tokenInputType).toBe("password");
  316. expect(after.clearKeys).toContain("token");
  317. for (const [locale, theme] of [
  318. ["zh-CN", "zai-light"],
  319. ["zh-CN", "zai-dark"],
  320. ["en-US", "zai-light"],
  321. ["en-US", "zai-dark"],
  322. ] as const) {
  323. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  324. await capturePluginManualReview(CASE_ID, `settings-saved-${locale}-${theme}`);
  325. }
  326. // (d) settings.get:换语言让两个扩展再读。第一个拿到 token(只看长度)与 region;第二个只有自己的值。
  327. evidence.probeAfterSave = await waitForLogAfter(
  328. linesBeforeSave,
  329. (line) =>
  330. line.includes("E2E_SETTINGS_PROBE plugin=e2e-ext-settings ") &&
  331. line.includes("locale=en-US"),
  332. "the settings extension should read the saved values",
  333. );
  334. expect(String(evidence.probeAfterSave)).toContain(
  335. `hasToken=true tokenLength=${TOKEN.length} region=${REGION} keys=region,token`,
  336. );
  337. evidence.otherProbeAfterSave = await waitForLogAfter(
  338. linesBeforeSave,
  339. (line) =>
  340. line.includes("E2E_SETTINGS_PROBE plugin=e2e-ext-settings-other") &&
  341. line.includes("locale=en-US"),
  342. "the other extension should read only its own values",
  343. );
  344. expect(String(evidence.otherProbeAfterSave)).toContain("hasToken=false mode=lite keys=mode");
  345. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  346. // (g) 清除敏感值:两处都删,onDidChange 再触发一次,hasToken=false。
  347. const changedBefore = (await log.lines()).filter((line) =>
  348. line.includes("E2E_SETTINGS_CHANGED"),
  349. ).length;
  350. await clickPluginControl("plugin-store-config-clear", {
  351. pluginId: PLUGIN_ID,
  352. configKey: "token",
  353. });
  354. await clickPluginControl("plugin-store-config-save", { pluginId: PLUGIN_ID });
  355. await browser.waitUntil(async () => !("token" in (await readSecretOptions())), {
  356. timeout: 30000,
  357. timeoutMsg: "the cleared token should leave plugin-secrets.json",
  358. });
  359. evidence.clearedLog = await log.waitFor(
  360. (line) =>
  361. line.includes("E2E_SETTINGS_CHANGED plugin=e2e-ext-settings hasToken=false") &&
  362. line.includes(`region=${REGION}`),
  363. "settings.onDidChange should fire after clearing the token",
  364. );
  365. expect(
  366. (await log.lines()).filter((line) => line.includes("E2E_SETTINGS_CHANGED")).length,
  367. ).toBeGreaterThan(changedBefore);
  368. expect(await readConfigOptions()).toEqual({ region: REGION });
  369. const cleared = await waitForConfigUi(
  370. (ui) => ui.scopes.token === "default",
  371. "the token scope marker should fall back to default after clearing",
  372. );
  373. evidence.configUiCleared = cleared;
  374. await capturePluginManualReview(CASE_ID, "settings-cleared-zh-CN-zai-light");
  375. // (h) settings.update(P4 H1,§18.1):视图工具 login 写敏感键。只进 plugin-secrets.json,onDidChange 触发。
  376. // 视图在对话主视图的侧栏里:先关掉设置页。
  377. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  378. timeout: 15000,
  379. timeoutMsg: "the settings back button should be visible",
  380. });
  381. const linesBeforeLogin = (await log.lines()).length;
  382. // H4(§18.1):启动页条目、导航条目与视图标签用 GitLab 示例的图标(log-in、git-merge、git-pull-request),
  383. // 不退回通用插件图标。读 Lucide 渲染的 svg class。
  384. await openLauncher();
  385. evidence.icons = {
  386. launcher: await readIconClass(
  387. `[data-testid="${TID_SIDE_PANE_EXTENSION_VIEW_ITEM}"][data-side-pane-open-tab-item="extension-view:${ACCOUNT_VIEW}"]`,
  388. ),
  389. nav: await readIconClass(
  390. `[data-testid="${TID_NAV_PRIMARY_ITEM}"][data-extension-item="${PLUGIN_ID}/nav"]`,
  391. ),
  392. };
  393. await openLauncherView(ACCOUNT_VIEW);
  394. const loginResult = await callAccountTool("login", { token: UPDATE_TOKEN });
  395. (evidence.icons as Record<string, string | null>).tab = await readIconClass(
  396. `[data-side-pane-tab-id="extension-view:${ACCOUNT_VIEW}"]`,
  397. );
  398. expect(evidence.icons).toMatchObject({
  399. launcher: expect.stringContaining("lucide-log-in"),
  400. nav: expect.stringContaining("lucide-git-merge"),
  401. tab: expect.stringContaining("lucide-git-pull-request"),
  402. });
  403. evidence.loginResult = loginResult;
  404. expect(JSON.stringify(loginResult)).toContain('"ok":true');
  405. expect(JSON.stringify(loginResult)).not.toContain(UPDATE_TOKEN);
  406. await browser.waitUntil(async () => (await readSecretOptions()).token === UPDATE_TOKEN, {
  407. timeout: 30000,
  408. timeoutMsg: "settings.update should store the token in plugin-secrets.json",
  409. });
  410. expect(await readConfigOptions()).toEqual({ region: REGION });
  411. expect(JSON.stringify(await readJson(cliPath("config.json")))).not.toContain(UPDATE_TOKEN);
  412. evidence.updateChangedLog = await waitForLogAfter(
  413. linesBeforeLogin,
  414. (line) =>
  415. line.includes("E2E_SETTINGS_CHANGED plugin=e2e-ext-settings hasToken=true") &&
  416. line.includes(`tokenLength=${UPDATE_TOKEN.length} region=${REGION}`),
  417. "settings.onDidChange should fire after settings.update",
  418. );
  419. evidence.updateServiceLog = (await log.lines())
  420. .slice(linesBeforeLogin)
  421. .filter(
  422. (line) => line.includes("[extensions] settings") || line.includes("E2E_SETTINGS_UPDATE"),
  423. );
  424. expect(JSON.stringify(evidence.updateServiceLog)).toContain(
  425. `settings update plugin=${PLUGIN_ID} keys=1 cleared=0`,
  426. );
  427. await capturePluginManualReview(CASE_ID, "settings-update-account-view-zh-CN-zai-light");
  428. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  429. await capturePluginManualReview(CASE_ID, "settings-update-account-view-en-US-zai-dark");
  430. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  431. // (i) 只写自己的插件:第二个扩展写不属于它的 token、写类型不符的 mode,都报 invalid-input,什么都没写。
  432. evidence.foreignTokenLog = await log.waitFor(
  433. (line) => line.includes("E2E_SETTINGS_FOREIGN token "),
  434. "the other extension should try to write a foreign key",
  435. );
  436. expect(String(evidence.foreignTokenLog)).toContain("code=invalid-input");
  437. evidence.foreignTypeLog = await log.waitFor(
  438. (line) => line.includes("E2E_SETTINGS_FOREIGN mode-type "),
  439. "the other extension should try to write a wrong value type",
  440. );
  441. expect(String(evidence.foreignTypeLog)).toContain("code=invalid-input");
  442. expect(await readOtherConfigOptions()).toEqual({});
  443. expect((await readSecretOptions()).token).toBe(UPDATE_TOKEN);
  444. // (j) 写入后不泄露:新 token 原文只在 plugin-secrets.json 里。
  445. const updateScan = await scanLeaks(UPDATE_TOKEN);
  446. evidence.updateTokenHits = updateScan.hits;
  447. expect(updateScan.hits).toEqual([cliPath("plugin-secrets.json")]);
  448. // (k) settings.update 清除:logout 两处都删,onDidChange 再触发一次 hasToken=false。
  449. const linesBeforeLogout = (await log.lines()).length;
  450. const logoutResult = await callAccountTool("logout", {});
  451. evidence.logoutResult = logoutResult;
  452. expect(JSON.stringify(logoutResult)).toContain('"ok":true');
  453. await browser.waitUntil(async () => !("token" in (await readSecretOptions())), {
  454. timeout: 30000,
  455. timeoutMsg: "settings.update clear should remove the token from plugin-secrets.json",
  456. });
  457. expect(await readConfigOptions()).toEqual({ region: REGION });
  458. evidence.logoutChangedLog = await waitForLogAfter(
  459. linesBeforeLogout,
  460. (line) =>
  461. line.includes("E2E_SETTINGS_CHANGED plugin=e2e-ext-settings hasToken=false") &&
  462. line.includes(`region=${REGION}`),
  463. "settings.onDidChange should fire after clearing through settings.update",
  464. );
  465. // (m) settings.update 写普通键:只进 config.json 的 plugins.options,不进 plugin-secrets.json;onDidChange 触发。
  466. // 宿主行为,以前只由示例插件用例 PLM-JARVIS-2 断言(Jarvis 的设置面板保存模型等普通设置)。
  467. const linesBeforeRegion = (await log.lines()).length;
  468. const regionResult = await callAccountTool("setRegion", { region: UPDATED_REGION });
  469. evidence.regionResult = regionResult;
  470. expect(JSON.stringify(regionResult)).toContain('"ok":true');
  471. await browser.waitUntil(async () => (await readConfigOptions()).region === UPDATED_REGION, {
  472. timeout: 30000,
  473. timeoutMsg: "settings.update should store the normal key in config.json",
  474. });
  475. expect(await readConfigOptions()).toEqual({ region: UPDATED_REGION });
  476. expect(Object.keys(await readSecretOptions())).not.toContain("region");
  477. evidence.regionChangedLog = await waitForLogAfter(
  478. linesBeforeRegion,
  479. (line) =>
  480. line.includes("E2E_SETTINGS_CHANGED plugin=e2e-ext-settings hasToken=false") &&
  481. line.includes(`region=${UPDATED_REGION}`),
  482. "settings.onDidChange should fire after settings.update wrote the normal key",
  483. );
  484. // (f) 日志与其他文件不泄露:两个 token 原文都不在 App / CLI 日志与数据目录里(plugin-secrets.json 已清空)。
  485. const scan = await scanLeaks(TOKEN);
  486. const updateScanAfterClear = await scanLeaks(UPDATE_TOKEN);
  487. evidence.tokenScanRoots = scan.roots;
  488. evidence.tokenLeaks = scan.hits;
  489. evidence.updateTokenLeaksAfterClear = updateScanAfterClear.hits;
  490. expect(scan.hits).toEqual([]);
  491. expect(updateScanAfterClear.hits).toEqual([]);
  492. });
  493. });