plugin-cdn-zip-marketplace.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { createHash } from "node:crypto";
  2. import { mkdirSync, writeFileSync } from "node:fs";
  3. import { createServer, type Server } from "node:http";
  4. import type { AddressInfo } from "node:net";
  5. import { dirname, join } from "node:path";
  6. export const PLUGIN_CDN_ZIP_MARKETPLACE_SPEC = "plugin-cdn-zip-marketplace-install.test.ts";
  7. export const PLUGIN_STORE_AUTO_REFRESH_THROTTLED_SPEC =
  8. "plugin-store-auto-refresh-throttled.test.ts";
  9. export const PLUGIN_STORE_AUTO_REFRESH_ON_ENTER_SPEC = "plugin-store-auto-refresh-on-enter.test.ts";
  10. // 固定未来时间阻止正式离线用例启动时自动刷新真实官方 CDN。
  11. export const PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED = "2099-01-01T00:00:00.000Z";
  12. // 远古时间让「进入商店页即刷新官方市场」用例必然落在节流窗口之外(且 pluginCount>0,
  13. // 确保走的是节流路径而不是「从未加载过」路径)。
  14. export const PLUGIN_STORE_AUTO_REFRESH_STALE_LAST_UPDATED = "2000-01-01T00:00:00.000Z";
  15. export const PLUGIN_CDN_ZIP_MARKETPLACE_ID = "zcode-plugins-official";
  16. export const PLUGIN_CDN_ZIP_MARKETPLACE_NAME = "ZCode Official Plugins";
  17. export const PLUGIN_CDN_ZIP_NAME = "e2e-cdn-zip-plugin";
  18. export const PLUGIN_CDN_ZIP_ID = `${PLUGIN_CDN_ZIP_NAME}@${PLUGIN_CDN_ZIP_MARKETPLACE_ID}`;
  19. export const PLUGIN_CDN_ZIP_VERSION = "7.8.9";
  20. export const PLUGIN_CDN_ZIP_ARCHIVE_PATH = "/e2e-cdn-zip-plugin.zip";
  21. export interface PluginCdnZipFixtureServer {
  22. baseUrl: string;
  23. server: Server;
  24. sha256: string;
  25. oversizedLocales: boolean;
  26. }
  27. const PLUGIN_CDN_ZIP_FIXTURE_SPECS = [
  28. PLUGIN_CDN_ZIP_MARKETPLACE_SPEC,
  29. "agent-plugin-discovery.test.ts",
  30. PLUGIN_STORE_AUTO_REFRESH_THROTTLED_SPEC,
  31. PLUGIN_STORE_AUTO_REFRESH_ON_ENTER_SPEC,
  32. ];
  33. function matchesSpec(specName: string, specs: string[]): boolean {
  34. return process.argv.concat(specs).some((spec) => spec.includes(specName));
  35. }
  36. export function shouldUsePluginCdnZipMarketplaceFixture(specs: string[] = []): boolean {
  37. return PLUGIN_CDN_ZIP_FIXTURE_SPECS.some((specName) => matchesSpec(specName, specs));
  38. }
  39. /**
  40. * 按 spec 决定 seed 进 known_marketplaces.json 的官方市场 lastUpdated:
  41. * - 节流跳过用例:启动前 1 分钟,进入商店页应命中 10 分钟窗口而不刷新(离线可跑);
  42. * - 进入即刷新用例:远古时间,进入商店页必须真打 CDN 刷新;
  43. * - 其余离线用例:未来时间,阻止任何自动访问公网。
  44. */
  45. export function resolvePluginCdnZipMarketplaceLastUpdated(specs: string[] = []): string {
  46. if (matchesSpec(PLUGIN_STORE_AUTO_REFRESH_THROTTLED_SPEC, specs)) {
  47. return new Date(Date.now() - 60_000).toISOString();
  48. }
  49. if (matchesSpec(PLUGIN_STORE_AUTO_REFRESH_ON_ENTER_SPEC, specs)) {
  50. return PLUGIN_STORE_AUTO_REFRESH_STALE_LAST_UPDATED;
  51. }
  52. return PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED;
  53. }
  54. export async function startPluginCdnZipFixtureServer(
  55. specs: string[] = [],
  56. ): Promise<PluginCdnZipFixtureServer> {
  57. const oversizedLocales = matchesSpec("agent-plugin-discovery.test.ts", specs);
  58. const zipBuffer = createPluginCdnZipArchive();
  59. const sha256 = hashBytes(zipBuffer);
  60. const server = createServer((request, response) => {
  61. const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
  62. if (pathname === "/marketplace.json") {
  63. const address = server.address() as AddressInfo;
  64. response.writeHead(200, { "content-type": "application/json" });
  65. response.end(
  66. JSON.stringify(
  67. createPluginCdnZipManifest(`http://127.0.0.1:${address.port}`, sha256, oversizedLocales),
  68. ),
  69. );
  70. return;
  71. }
  72. if (pathname !== PLUGIN_CDN_ZIP_ARCHIVE_PATH) {
  73. response.writeHead(404);
  74. response.end("not found");
  75. return;
  76. }
  77. response.writeHead(200, {
  78. "content-length": String(zipBuffer.byteLength),
  79. "content-type": "application/zip",
  80. });
  81. response.end(zipBuffer);
  82. });
  83. await new Promise<void>((resolveListen) => {
  84. server.listen(0, "127.0.0.1", resolveListen);
  85. });
  86. const address = server.address();
  87. if (!address || typeof address === "string") {
  88. throw new Error("Plugin CDN zip fixture server did not bind to a TCP port");
  89. }
  90. return {
  91. baseUrl: `http://127.0.0.1:${(address as AddressInfo).port}`,
  92. server,
  93. sha256,
  94. oversizedLocales,
  95. };
  96. }
  97. export async function stopPluginCdnZipFixtureServer(
  98. fixture: PluginCdnZipFixtureServer | undefined,
  99. ): Promise<void> {
  100. if (!fixture?.server.listening) return;
  101. await new Promise<void>((resolveClose, rejectClose) => {
  102. fixture.server.close((error) => {
  103. if (error) rejectClose(error);
  104. else resolveClose();
  105. });
  106. });
  107. }
  108. export function seedPluginCdnZipMarketplaceFixture(input: {
  109. e2eHomeDir: string;
  110. server: PluginCdnZipFixtureServer;
  111. lastUpdated?: string;
  112. localCatalog?: boolean;
  113. }): void {
  114. const pluginStorageRoot = join(input.e2eHomeDir, ".zcode", "cli", "plugins");
  115. const marketplaceSourceRoot = join(
  116. input.e2eHomeDir,
  117. "fixtures",
  118. "plugin-cdn-zip-marketplace-source",
  119. );
  120. const manifest = createPluginCdnZipManifest(
  121. input.server.baseUrl,
  122. input.server.sha256,
  123. input.server.oversizedLocales,
  124. );
  125. const knownMarketplaces = {
  126. version: 1,
  127. marketplaces: [
  128. {
  129. id: PLUGIN_CDN_ZIP_MARKETPLACE_ID,
  130. source: {
  131. source: "url",
  132. url: input.localCatalog
  133. ? `${input.server.baseUrl}/marketplace.json`
  134. : "https://cdn-zcode.z.ai/zcode/official-plugin/marketplace.json",
  135. },
  136. name: PLUGIN_CDN_ZIP_MARKETPLACE_NAME,
  137. description: manifest.description,
  138. addedAt: "2026-01-01T00:00:00.000Z",
  139. lastUpdated: input.lastUpdated ?? PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED,
  140. pluginCount: manifest.plugins.length,
  141. },
  142. // 商店页已不再自动拉取 claude-plugins-official;这里仍预置成「已加载」,一是与其它离线
  143. // fixture 惯例一致,二是让 PLM-LC-018 能断言进入商店页后该记录没有任何刷新/失败痕迹。
  144. {
  145. id: "claude-plugins-official",
  146. source: { source: "github", repo: "anthropics/claude-plugins-official" },
  147. name: "claude-plugins-official",
  148. description: "Deterministic offline Claude marketplace marker",
  149. addedAt: "2026-01-01T00:00:00.000Z",
  150. lastUpdated: PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED,
  151. pluginCount: 1,
  152. },
  153. ],
  154. };
  155. writeJsonFileSync(join(marketplaceSourceRoot, ".claude-plugin", "marketplace.json"), manifest);
  156. // 官方市场由 bundled/CDN 两个分片重建。把确定性条目写入 CDN 分片,应用启动 seed
  157. // bundled 分片时才不会覆盖本地 fixture;lastUpdated 则阻止 UI 自动访问公网。
  158. writeJsonFileSync(
  159. join(pluginStorageRoot, "marketplaces", PLUGIN_CDN_ZIP_MARKETPLACE_ID, "cdn-marketplace.json"),
  160. manifest,
  161. );
  162. writeJsonFileSync(
  163. join(pluginStorageRoot, "marketplaces", PLUGIN_CDN_ZIP_MARKETPLACE_ID, "marketplace.json"),
  164. manifest,
  165. );
  166. writeJsonFileSync(join(pluginStorageRoot, "known_marketplaces.json"), knownMarketplaces);
  167. }
  168. function createPluginCdnZipArchive(): Buffer {
  169. return createStoredZip([
  170. {
  171. path: `${PLUGIN_CDN_ZIP_NAME}-${PLUGIN_CDN_ZIP_VERSION}/.claude-plugin/plugin.json`,
  172. content: JSON.stringify({
  173. commands: "commands",
  174. description: "E2E CDN zip plugin",
  175. name: PLUGIN_CDN_ZIP_NAME,
  176. skills: "skills",
  177. version: PLUGIN_CDN_ZIP_VERSION,
  178. }),
  179. },
  180. {
  181. path: `${PLUGIN_CDN_ZIP_NAME}-${PLUGIN_CDN_ZIP_VERSION}/skills/zip-skill/SKILL.md`,
  182. content: [
  183. "---",
  184. "name: zip-skill",
  185. "description: E2E skill loaded from a CDN zip plugin",
  186. "---",
  187. "",
  188. "# zip-skill",
  189. "",
  190. "Use this skill to prove CDN zip plugin discovery.",
  191. ].join("\n"),
  192. },
  193. {
  194. path: `${PLUGIN_CDN_ZIP_NAME}-${PLUGIN_CDN_ZIP_VERSION}/commands/zip-command.md`,
  195. content: [
  196. "---",
  197. "description: E2E command loaded from a CDN zip plugin",
  198. "allowed-tools: Bash",
  199. "---",
  200. "",
  201. "Run a zip fixture command with $ARGUMENTS.",
  202. ].join("\n"),
  203. },
  204. ]);
  205. }
  206. function createStoredZip(entries: Array<{ content?: string; path: string }>): Buffer {
  207. const localParts: Buffer[] = [];
  208. const centralParts: Buffer[] = [];
  209. let offset = 0;
  210. for (const entry of entries) {
  211. const name = Buffer.from(entry.path);
  212. const data = Buffer.from(entry.content ?? "");
  213. const crc = crc32(data);
  214. const local = Buffer.alloc(30);
  215. local.writeUInt32LE(0x04034b50, 0);
  216. local.writeUInt16LE(20, 4);
  217. local.writeUInt16LE(0, 6);
  218. local.writeUInt16LE(0, 8);
  219. local.writeUInt16LE(0, 10);
  220. local.writeUInt16LE(0, 12);
  221. local.writeUInt32LE(crc, 14);
  222. local.writeUInt32LE(data.byteLength, 18);
  223. local.writeUInt32LE(data.byteLength, 22);
  224. local.writeUInt16LE(name.byteLength, 26);
  225. local.writeUInt16LE(0, 28);
  226. localParts.push(local, name, data);
  227. const central = Buffer.alloc(46);
  228. central.writeUInt32LE(0x02014b50, 0);
  229. central.writeUInt16LE(20, 4);
  230. central.writeUInt16LE(20, 6);
  231. central.writeUInt16LE(0, 8);
  232. central.writeUInt16LE(0, 10);
  233. central.writeUInt16LE(0, 12);
  234. central.writeUInt16LE(0, 14);
  235. central.writeUInt32LE(crc, 16);
  236. central.writeUInt32LE(data.byteLength, 20);
  237. central.writeUInt32LE(data.byteLength, 24);
  238. central.writeUInt16LE(name.byteLength, 28);
  239. central.writeUInt16LE(0, 30);
  240. central.writeUInt16LE(0, 32);
  241. central.writeUInt16LE(0, 34);
  242. central.writeUInt16LE(0, 36);
  243. central.writeUInt32LE(0o100644 * 0x10000, 38);
  244. central.writeUInt32LE(offset, 42);
  245. centralParts.push(central, name);
  246. offset += local.byteLength + name.byteLength + data.byteLength;
  247. }
  248. const centralDirectory = Buffer.concat(centralParts);
  249. const end = Buffer.alloc(22);
  250. end.writeUInt32LE(0x06054b50, 0);
  251. end.writeUInt16LE(0, 4);
  252. end.writeUInt16LE(0, 6);
  253. end.writeUInt16LE(entries.length, 8);
  254. end.writeUInt16LE(entries.length, 10);
  255. end.writeUInt32LE(centralDirectory.byteLength, 12);
  256. end.writeUInt32LE(offset, 16);
  257. end.writeUInt16LE(0, 20);
  258. return Buffer.concat([...localParts, centralDirectory, end]);
  259. }
  260. const CRC32_TABLE = Array.from({ length: 256 }, (_, index) => {
  261. let value = index;
  262. for (let bit = 0; bit < 8; bit += 1) {
  263. value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
  264. }
  265. return value >>> 0;
  266. });
  267. function crc32(buffer: Buffer): number {
  268. let crc = 0xffffffff;
  269. for (const byte of buffer) {
  270. crc = CRC32_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
  271. }
  272. return (crc ^ 0xffffffff) >>> 0;
  273. }
  274. function hashBytes(bytes: Buffer): string {
  275. return createHash("sha256").update(bytes).digest("hex");
  276. }
  277. function writeJsonFileSync(path: string, value: unknown): void {
  278. mkdirSync(dirname(path), { recursive: true });
  279. writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
  280. }
  281. function createPluginCdnZipManifest(baseUrl: string, sha256: string, oversizedLocales: boolean) {
  282. // 仅发现用例注入超大目录;界面语言放末尾,避免单纯截取前 N 项也能通过。
  283. const extraLocales = oversizedLocales
  284. ? Object.fromEntries(
  285. Array.from({ length: 5_000 }, (_, index) => [
  286. `x-${index}`,
  287. index === 0 ? '"\n🚀'.repeat(2_000) : "Unused fixture translation",
  288. ]),
  289. )
  290. : {};
  291. const localizedListing = oversizedLocales
  292. ? {
  293. displayName_i18n: {
  294. ...extraLocales,
  295. "zh-CN": "ZIP 归档助手",
  296. "en-US": "ZIP Archive Helper",
  297. "ja-JP": "ZIP ヘルパー",
  298. "ru-RU": "ZIP помощник",
  299. "ko-KR": "ZIP 도우미",
  300. },
  301. description_i18n: {
  302. ...extraLocales,
  303. "zh-CN": "用于验证大翻译表的本地插件",
  304. "en-US": "Local plugin with a large translation catalog",
  305. "ja-JP": "ローカルプラグイン",
  306. "ru-RU": "Локальный плагин",
  307. "ko-KR": "로컬 플러그인",
  308. },
  309. }
  310. : {};
  311. return {
  312. name: PLUGIN_CDN_ZIP_MARKETPLACE_ID,
  313. description: "E2E marketplace seeded before desktop startup for CDN zip install.",
  314. plugins: [
  315. {
  316. name: PLUGIN_CDN_ZIP_NAME,
  317. version: PLUGIN_CDN_ZIP_VERSION,
  318. description: "E2E CDN zip plugin",
  319. ...localizedListing,
  320. commands: ["zip-command"],
  321. skills: ["zip-skill"],
  322. source: {
  323. source: "url",
  324. type: "zip",
  325. url: `${baseUrl}${PLUGIN_CDN_ZIP_ARCHIVE_PATH}`,
  326. sha256,
  327. },
  328. },
  329. ],
  330. };
  331. }