plugin-cdn-zip-marketplace.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. }
  26. const PLUGIN_CDN_ZIP_FIXTURE_SPECS = [
  27. PLUGIN_CDN_ZIP_MARKETPLACE_SPEC,
  28. PLUGIN_STORE_AUTO_REFRESH_THROTTLED_SPEC,
  29. PLUGIN_STORE_AUTO_REFRESH_ON_ENTER_SPEC,
  30. ];
  31. function matchesSpec(specName: string, specs: string[]): boolean {
  32. return process.argv.concat(specs).some((spec) => spec.includes(specName));
  33. }
  34. export function shouldUsePluginCdnZipMarketplaceFixture(specs: string[] = []): boolean {
  35. return PLUGIN_CDN_ZIP_FIXTURE_SPECS.some((specName) => matchesSpec(specName, specs));
  36. }
  37. /**
  38. * 按 spec 决定 seed 进 known_marketplaces.json 的官方市场 lastUpdated:
  39. * - 节流跳过用例:启动前 1 分钟,进入商店页应命中 10 分钟窗口而不刷新(离线可跑);
  40. * - 进入即刷新用例:远古时间,进入商店页必须真打 CDN 刷新;
  41. * - 其余离线用例:未来时间,阻止任何自动访问公网。
  42. */
  43. export function resolvePluginCdnZipMarketplaceLastUpdated(specs: string[] = []): string {
  44. if (matchesSpec(PLUGIN_STORE_AUTO_REFRESH_THROTTLED_SPEC, specs)) {
  45. return new Date(Date.now() - 60_000).toISOString();
  46. }
  47. if (matchesSpec(PLUGIN_STORE_AUTO_REFRESH_ON_ENTER_SPEC, specs)) {
  48. return PLUGIN_STORE_AUTO_REFRESH_STALE_LAST_UPDATED;
  49. }
  50. return PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED;
  51. }
  52. export async function startPluginCdnZipFixtureServer(): Promise<PluginCdnZipFixtureServer> {
  53. const zipBuffer = createPluginCdnZipArchive();
  54. const sha256 = hashBytes(zipBuffer);
  55. const server = createServer((request, response) => {
  56. const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
  57. if (pathname !== PLUGIN_CDN_ZIP_ARCHIVE_PATH) {
  58. response.writeHead(404);
  59. response.end("not found");
  60. return;
  61. }
  62. response.writeHead(200, {
  63. "content-length": String(zipBuffer.byteLength),
  64. "content-type": "application/zip",
  65. });
  66. response.end(zipBuffer);
  67. });
  68. await new Promise<void>((resolveListen) => {
  69. server.listen(0, "127.0.0.1", resolveListen);
  70. });
  71. const address = server.address();
  72. if (!address || typeof address === "string") {
  73. throw new Error("Plugin CDN zip fixture server did not bind to a TCP port");
  74. }
  75. return {
  76. baseUrl: `http://127.0.0.1:${(address as AddressInfo).port}`,
  77. server,
  78. sha256,
  79. };
  80. }
  81. export async function stopPluginCdnZipFixtureServer(
  82. fixture: PluginCdnZipFixtureServer | undefined,
  83. ): Promise<void> {
  84. if (!fixture?.server.listening) return;
  85. await new Promise<void>((resolveClose, rejectClose) => {
  86. fixture.server.close((error) => {
  87. if (error) rejectClose(error);
  88. else resolveClose();
  89. });
  90. });
  91. }
  92. export function seedPluginCdnZipMarketplaceFixture(input: {
  93. e2eHomeDir: string;
  94. server: PluginCdnZipFixtureServer;
  95. lastUpdated?: string;
  96. }): void {
  97. const pluginStorageRoot = join(input.e2eHomeDir, ".zcode", "cli", "plugins");
  98. const marketplaceSourceRoot = join(
  99. input.e2eHomeDir,
  100. "fixtures",
  101. "plugin-cdn-zip-marketplace-source",
  102. );
  103. const zipUrl = `${input.server.baseUrl}${PLUGIN_CDN_ZIP_ARCHIVE_PATH}`;
  104. const manifest = {
  105. name: PLUGIN_CDN_ZIP_MARKETPLACE_ID,
  106. description: "E2E marketplace seeded before desktop startup for CDN zip install.",
  107. plugins: [
  108. {
  109. name: PLUGIN_CDN_ZIP_NAME,
  110. version: PLUGIN_CDN_ZIP_VERSION,
  111. description: "E2E CDN zip plugin",
  112. commands: ["zip-command"],
  113. skills: ["zip-skill"],
  114. source: {
  115. source: "url",
  116. type: "zip",
  117. url: zipUrl,
  118. sha256: input.server.sha256,
  119. },
  120. },
  121. ],
  122. };
  123. const knownMarketplaces = {
  124. version: 1,
  125. marketplaces: [
  126. {
  127. id: PLUGIN_CDN_ZIP_MARKETPLACE_ID,
  128. source: {
  129. source: "url",
  130. url: "https://cdn-zcode.z.ai/zcode/official-plugin/marketplace.json",
  131. },
  132. name: PLUGIN_CDN_ZIP_MARKETPLACE_NAME,
  133. description: manifest.description,
  134. addedAt: "2026-01-01T00:00:00.000Z",
  135. lastUpdated: input.lastUpdated ?? PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED,
  136. pluginCount: manifest.plugins.length,
  137. },
  138. // 商店页已不再自动拉取 claude-plugins-official;这里仍预置成「已加载」,一是与其它离线
  139. // fixture 惯例一致,二是让 PLM-LC-018 能断言进入商店页后该记录没有任何刷新/失败痕迹。
  140. {
  141. id: "claude-plugins-official",
  142. source: { source: "github", repo: "anthropics/claude-plugins-official" },
  143. name: "claude-plugins-official",
  144. description: "Deterministic offline Claude marketplace marker",
  145. addedAt: "2026-01-01T00:00:00.000Z",
  146. lastUpdated: PLUGIN_CDN_ZIP_OFFLINE_LAST_UPDATED,
  147. pluginCount: 1,
  148. },
  149. ],
  150. };
  151. writeJsonFileSync(join(marketplaceSourceRoot, ".claude-plugin", "marketplace.json"), manifest);
  152. // 官方市场由 bundled/CDN 两个分片重建。把确定性条目写入 CDN 分片,应用启动 seed
  153. // bundled 分片时才不会覆盖本地 fixture;lastUpdated 则阻止 UI 自动访问公网。
  154. writeJsonFileSync(
  155. join(pluginStorageRoot, "marketplaces", PLUGIN_CDN_ZIP_MARKETPLACE_ID, "cdn-marketplace.json"),
  156. manifest,
  157. );
  158. writeJsonFileSync(
  159. join(pluginStorageRoot, "marketplaces", PLUGIN_CDN_ZIP_MARKETPLACE_ID, "marketplace.json"),
  160. manifest,
  161. );
  162. writeJsonFileSync(join(pluginStorageRoot, "known_marketplaces.json"), knownMarketplaces);
  163. }
  164. function createPluginCdnZipArchive(): Buffer {
  165. return createStoredZip([
  166. {
  167. path: `${PLUGIN_CDN_ZIP_NAME}-${PLUGIN_CDN_ZIP_VERSION}/.claude-plugin/plugin.json`,
  168. content: JSON.stringify({
  169. commands: "commands",
  170. description: "E2E CDN zip plugin",
  171. name: PLUGIN_CDN_ZIP_NAME,
  172. skills: "skills",
  173. version: PLUGIN_CDN_ZIP_VERSION,
  174. }),
  175. },
  176. {
  177. path: `${PLUGIN_CDN_ZIP_NAME}-${PLUGIN_CDN_ZIP_VERSION}/skills/zip-skill/SKILL.md`,
  178. content: [
  179. "---",
  180. "description: E2E skill loaded from a CDN zip plugin",
  181. "---",
  182. "",
  183. "# zip-skill",
  184. "",
  185. "Use this skill to prove CDN zip plugin discovery.",
  186. ].join("\n"),
  187. },
  188. {
  189. path: `${PLUGIN_CDN_ZIP_NAME}-${PLUGIN_CDN_ZIP_VERSION}/commands/zip-command.md`,
  190. content: [
  191. "---",
  192. "description: E2E command loaded from a CDN zip plugin",
  193. "allowed-tools: Bash",
  194. "---",
  195. "",
  196. "Run a zip fixture command with $ARGUMENTS.",
  197. ].join("\n"),
  198. },
  199. ]);
  200. }
  201. function createStoredZip(entries: Array<{ content?: string; path: string }>): Buffer {
  202. const localParts: Buffer[] = [];
  203. const centralParts: Buffer[] = [];
  204. let offset = 0;
  205. for (const entry of entries) {
  206. const name = Buffer.from(entry.path);
  207. const data = Buffer.from(entry.content ?? "");
  208. const crc = crc32(data);
  209. const local = Buffer.alloc(30);
  210. local.writeUInt32LE(0x04034b50, 0);
  211. local.writeUInt16LE(20, 4);
  212. local.writeUInt16LE(0, 6);
  213. local.writeUInt16LE(0, 8);
  214. local.writeUInt16LE(0, 10);
  215. local.writeUInt16LE(0, 12);
  216. local.writeUInt32LE(crc, 14);
  217. local.writeUInt32LE(data.byteLength, 18);
  218. local.writeUInt32LE(data.byteLength, 22);
  219. local.writeUInt16LE(name.byteLength, 26);
  220. local.writeUInt16LE(0, 28);
  221. localParts.push(local, name, data);
  222. const central = Buffer.alloc(46);
  223. central.writeUInt32LE(0x02014b50, 0);
  224. central.writeUInt16LE(20, 4);
  225. central.writeUInt16LE(20, 6);
  226. central.writeUInt16LE(0, 8);
  227. central.writeUInt16LE(0, 10);
  228. central.writeUInt16LE(0, 12);
  229. central.writeUInt16LE(0, 14);
  230. central.writeUInt32LE(crc, 16);
  231. central.writeUInt32LE(data.byteLength, 20);
  232. central.writeUInt32LE(data.byteLength, 24);
  233. central.writeUInt16LE(name.byteLength, 28);
  234. central.writeUInt16LE(0, 30);
  235. central.writeUInt16LE(0, 32);
  236. central.writeUInt16LE(0, 34);
  237. central.writeUInt16LE(0, 36);
  238. central.writeUInt32LE(0o100644 * 0x10000, 38);
  239. central.writeUInt32LE(offset, 42);
  240. centralParts.push(central, name);
  241. offset += local.byteLength + name.byteLength + data.byteLength;
  242. }
  243. const centralDirectory = Buffer.concat(centralParts);
  244. const end = Buffer.alloc(22);
  245. end.writeUInt32LE(0x06054b50, 0);
  246. end.writeUInt16LE(0, 4);
  247. end.writeUInt16LE(0, 6);
  248. end.writeUInt16LE(entries.length, 8);
  249. end.writeUInt16LE(entries.length, 10);
  250. end.writeUInt32LE(centralDirectory.byteLength, 12);
  251. end.writeUInt32LE(offset, 16);
  252. end.writeUInt16LE(0, 20);
  253. return Buffer.concat([...localParts, centralDirectory, end]);
  254. }
  255. const CRC32_TABLE = Array.from({ length: 256 }, (_, index) => {
  256. let value = index;
  257. for (let bit = 0; bit < 8; bit += 1) {
  258. value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
  259. }
  260. return value >>> 0;
  261. });
  262. function crc32(buffer: Buffer): number {
  263. let crc = 0xffffffff;
  264. for (const byte of buffer) {
  265. crc = CRC32_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
  266. }
  267. return (crc ^ 0xffffffff) >>> 0;
  268. }
  269. function hashBytes(bytes: Buffer): string {
  270. return createHash("sha256").update(bytes).digest("hex");
  271. }
  272. function writeJsonFileSync(path: string, value: unknown): void {
  273. mkdirSync(dirname(path), { recursive: true });
  274. writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
  275. }