zip-source.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import { createHash } from "node:crypto";
  2. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
  5. import { setTimeout as delay } from "node:timers/promises";
  6. import { isHttpClientPortError } from "@zcode/contracts";
  7. import * as yauzl from "yauzl";
  8. import { createNodeWebFetchHttpClientAdapter } from "../http/index.js";
  9. import {
  10. appendPluginSourceCleanupError,
  11. cleanupPluginSourceBestEffort,
  12. directoryExists,
  13. fileExists,
  14. } from "./helpers.js";
  15. const ZIP_DOWNLOAD_MAX_BYTES = 200 * 1024 * 1024;
  16. const ZIP_EXTRACT_MAX_BYTES = 500 * 1024 * 1024;
  17. const ZIP_MAX_ENTRIES = 20_000;
  18. const ZIP_MAX_SINGLE_FILE_BYTES = 50 * 1024 * 1024;
  19. const ZIP_MAX_REDIRECTS = 5;
  20. const ZIP_DOWNLOAD_TIMEOUT_MS = 180_000;
  21. const ZIP_TEMP_PREFIX = "zcode-plugin-zip-";
  22. const ZIP_DENIED_HEADERS = new Set([
  23. "authorization",
  24. "cookie",
  25. "proxy-authorization",
  26. "set-cookie",
  27. ]);
  28. const ZIP_REQUIRED_SHA256_PATTERN = /^[a-f0-9]{64}$/u;
  29. export interface ResolvedZipPluginSourceRoot {
  30. cleanup: () => Promise<void>;
  31. path: string;
  32. }
  33. export interface ResolveZipPluginSourceInput {
  34. headers?: Record<string, string>;
  35. path?: string;
  36. sha256: string;
  37. signal?: AbortSignal;
  38. stripRoot?: boolean;
  39. url: string;
  40. }
  41. export interface ResolveHttpZipSourceInput {
  42. headers?: Record<string, string>;
  43. path?: string;
  44. requireSingleRoot?: boolean;
  45. sha256?: string;
  46. signal?: AbortSignal;
  47. stripRoot?: boolean;
  48. url: string;
  49. }
  50. export class PluginZipDownloadError extends Error {
  51. readonly status?: number;
  52. readonly url: string;
  53. constructor(message: string, url: string, status?: number) {
  54. super(message);
  55. this.name = "PluginZipDownloadError";
  56. this.url = url;
  57. if (status !== undefined) this.status = status;
  58. }
  59. }
  60. interface ZipExtractResult {
  61. topLevelSegments: Set<string>;
  62. }
  63. type ZipEntryKind = "directory" | "file";
  64. export async function resolveZipPluginSource(
  65. input: ResolveZipPluginSourceInput,
  66. ): Promise<ResolvedZipPluginSourceRoot> {
  67. validateZipSourceInput(input);
  68. const resolved = await resolveHttpZipSource({
  69. headers: input.headers,
  70. path: input.path,
  71. sha256: input.sha256,
  72. signal: input.signal,
  73. stripRoot: input.stripRoot,
  74. url: input.url,
  75. });
  76. return resolved;
  77. }
  78. export async function resolveHttpZipSource(
  79. input: ResolveHttpZipSourceInput,
  80. ): Promise<ResolvedZipPluginSourceRoot> {
  81. validateZipDownloadUrl(input.url);
  82. validateZipHeaders(input.headers);
  83. if (input.path !== undefined) normalizeZipRelativePath(input.path);
  84. if (input.sha256 !== undefined && !ZIP_REQUIRED_SHA256_PATTERN.test(input.sha256.toLowerCase())) {
  85. throw new Error("Plugin zip source sha256 must be a 64 character hex string");
  86. }
  87. const tempRoot = await mkdtemp(join(tmpdir(), ZIP_TEMP_PREFIX));
  88. const archivePath = join(tempRoot, "source.zip");
  89. const extractRoot = join(tempRoot, "extract");
  90. const cleanup = async (): Promise<void> => {
  91. await rm(tempRoot, { force: true, recursive: true });
  92. };
  93. try {
  94. throwIfAborted(input.signal);
  95. const zipBytes = await downloadZipArchive({
  96. headers: input.headers,
  97. signal: input.signal,
  98. url: input.url,
  99. });
  100. const actualSha256 = createHash("sha256").update(zipBytes).digest("hex");
  101. if (input.sha256 !== undefined && actualSha256 !== input.sha256.toLowerCase()) {
  102. throw new Error(
  103. `Plugin zip sha256 mismatch: expected=${input.sha256.toLowerCase()}, actual=${actualSha256}`,
  104. );
  105. }
  106. await writeFile(archivePath, zipBytes);
  107. const extracted = await extractZipArchive({
  108. archivePath,
  109. signal: input.signal,
  110. targetRoot: extractRoot,
  111. });
  112. const pluginRoot = resolveZipRoot({
  113. extractRoot,
  114. path: input.path,
  115. requireSingleRoot: input.requireSingleRoot,
  116. stripRoot: input.stripRoot,
  117. topLevelSegments: extracted.topLevelSegments,
  118. });
  119. return { cleanup, path: pluginRoot };
  120. } catch (error) {
  121. const cleanupError = await cleanupPluginSourceBestEffort(cleanup);
  122. throw appendPluginSourceCleanupError(error, cleanupError);
  123. }
  124. }
  125. export function readZipPluginSourceSha256(source: unknown): string | undefined {
  126. if (!isZipPluginUrlSource(source)) return undefined;
  127. return source.sha256;
  128. }
  129. export function isZipPluginUrlSource(
  130. source: unknown,
  131. ): source is { source: "url"; type: "zip"; sha256: string; url: string } {
  132. return (
  133. typeof source === "object" &&
  134. source !== null &&
  135. !Array.isArray(source) &&
  136. "source" in source &&
  137. (source as { source?: unknown }).source === "url" &&
  138. (source as { type?: unknown }).type === "zip" &&
  139. typeof (source as { url?: unknown }).url === "string" &&
  140. typeof (source as { sha256?: unknown }).sha256 === "string"
  141. );
  142. }
  143. function validateZipSourceInput(input: ResolveZipPluginSourceInput): void {
  144. validateZipDownloadUrl(input.url);
  145. if (!ZIP_REQUIRED_SHA256_PATTERN.test(input.sha256.toLowerCase())) {
  146. throw new Error("Plugin zip source sha256 must be a 64 character hex string");
  147. }
  148. validateZipHeaders(input.headers);
  149. if (input.path !== undefined) {
  150. normalizeZipRelativePath(input.path);
  151. }
  152. }
  153. async function downloadZipArchive(input: {
  154. headers?: Record<string, string>;
  155. signal?: AbortSignal;
  156. url: string;
  157. }): Promise<Uint8Array> {
  158. // agent 会封存用户 shell 代理,ZIP 下载必须和其他应用层 fetch 一样读取 captured proxy fallback。
  159. const client = createNodeWebFetchHttpClientAdapter({
  160. env: process.env,
  161. maxResponseBytes: ZIP_DOWNLOAD_MAX_BYTES,
  162. timeoutMs: ZIP_DOWNLOAD_TIMEOUT_MS,
  163. });
  164. let currentUrl = input.url;
  165. let currentHeaders = input.headers;
  166. for (let redirectCount = 0; redirectCount <= ZIP_MAX_REDIRECTS; redirectCount += 1) {
  167. throwIfAborted(input.signal);
  168. validateZipDownloadUrl(currentUrl);
  169. const request = () =>
  170. client.request(
  171. {
  172. headers: currentHeaders,
  173. maxResponseBytes: ZIP_DOWNLOAD_MAX_BYTES,
  174. method: "GET",
  175. redirect: "manual",
  176. url: currentUrl,
  177. },
  178. { signal: input.signal },
  179. );
  180. const response = await request().catch(async (error: unknown) => {
  181. if (
  182. !isHttpClientPortError(error) ||
  183. (error.code !== "network_error" && error.code !== "proxy_error")
  184. )
  185. throw error;
  186. // 代理 TLS 握手或正文传输可能偶发断开;GET 尚未激活缓存,可安全重试一次。
  187. // 原生 fetch 比代理请求多包一层 cause;仅识别连接重置,不重试证书错误或取消。
  188. const cause =
  189. error.cause instanceof Error && error.cause.cause instanceof Error
  190. ? error.cause.cause
  191. : error.cause;
  192. if (
  193. !(cause instanceof Error) ||
  194. !("code" in cause) ||
  195. (cause.code !== "ECONNRESET" && cause.code !== "UND_ERR_SOCKET")
  196. )
  197. throw error;
  198. await delay(250, undefined, { signal: input.signal });
  199. return request();
  200. });
  201. if (isRedirectStatus(response.status)) {
  202. const location = response.headers.location;
  203. if (!location) {
  204. throw new Error(`Plugin zip download redirect is missing Location header: ${currentUrl}`);
  205. }
  206. const redirectUrl = new URL(location, currentUrl);
  207. // 跨 CDN origin 继续发送 marketplace 自定义 header 会把内部元数据泄露给跳转目标。
  208. if (redirectUrl.origin !== new URL(currentUrl).origin) {
  209. currentHeaders = undefined;
  210. }
  211. currentUrl = redirectUrl.toString();
  212. continue;
  213. }
  214. if (response.status < 200 || response.status >= 300) {
  215. throw new PluginZipDownloadError(
  216. `Failed to download plugin zip: ${response.status} ${response.statusText}`,
  217. currentUrl,
  218. response.status,
  219. );
  220. }
  221. return response.body;
  222. }
  223. throw new Error(`Plugin zip download exceeded redirect limit: ${input.url}`);
  224. }
  225. async function extractZipArchive(input: {
  226. archivePath: string;
  227. signal?: AbortSignal;
  228. targetRoot: string;
  229. }): Promise<ZipExtractResult> {
  230. const targetRoot = resolve(input.targetRoot);
  231. await mkdir(targetRoot, { recursive: true });
  232. const zipFile = await openZipFile(input.archivePath);
  233. const topLevelSegments = new Set<string>();
  234. let entryCount = 0;
  235. let extractedBytes = 0;
  236. try {
  237. await new Promise<void>((resolvePromise, rejectPromise) => {
  238. const rejectOnce = (error: unknown): void => {
  239. zipFile.close();
  240. rejectPromise(error);
  241. };
  242. zipFile.once("error", rejectOnce);
  243. zipFile.once("end", () => {
  244. zipFile.removeListener("error", rejectOnce);
  245. resolvePromise();
  246. });
  247. zipFile.on("entry", (entry) => {
  248. void (async () => {
  249. try {
  250. throwIfAborted(input.signal);
  251. entryCount += 1;
  252. if (entryCount > ZIP_MAX_ENTRIES) {
  253. throw new Error(`Plugin zip has too many entries: ${entryCount}/${ZIP_MAX_ENTRIES}`);
  254. }
  255. const normalizedPath = normalizeZipRelativePath(entry.fileName);
  256. topLevelSegments.add(normalizedPath.split("/")[0] ?? normalizedPath);
  257. const targetPath = resolveZipPathWithin(targetRoot, normalizedPath);
  258. const kind = classifyZipEntry(entry);
  259. if (kind === "directory") {
  260. await mkdir(targetPath, { recursive: true });
  261. zipFile.readEntry();
  262. return;
  263. }
  264. if (entry.uncompressedSize > ZIP_MAX_SINGLE_FILE_BYTES) {
  265. throw new Error(`Plugin zip entry exceeds single file limit: ${entry.fileName}`);
  266. }
  267. const bytes = await readZipEntryBuffer(zipFile, entry, input.signal);
  268. extractedBytes += bytes.byteLength;
  269. if (extractedBytes > ZIP_EXTRACT_MAX_BYTES) {
  270. throw new Error(
  271. `Plugin zip extracted content exceeds limit: ${extractedBytes}/${ZIP_EXTRACT_MAX_BYTES}`,
  272. );
  273. }
  274. await mkdir(dirname(targetPath), { recursive: true });
  275. await writeFile(targetPath, bytes);
  276. zipFile.readEntry();
  277. } catch (error) {
  278. rejectOnce(error);
  279. }
  280. })();
  281. });
  282. zipFile.readEntry();
  283. });
  284. } finally {
  285. zipFile.close();
  286. }
  287. return { topLevelSegments };
  288. }
  289. function resolveZipRoot(input: {
  290. extractRoot: string;
  291. path?: string;
  292. requireSingleRoot?: boolean;
  293. stripRoot?: boolean;
  294. topLevelSegments: Set<string>;
  295. }): string {
  296. const extractRoot = resolve(input.extractRoot);
  297. if (input.requireSingleRoot && input.topLevelSegments.size !== 1) {
  298. throw new Error(
  299. `Plugin zip must contain exactly one top-level directory: ${input.topLevelSegments.size}`,
  300. );
  301. }
  302. if (input.path !== undefined) {
  303. const requested = resolveZipPathWithin(extractRoot, normalizeZipRelativePath(input.path));
  304. if (!directoryExists(requested)) {
  305. throw new Error(`Plugin zip source subdirectory does not exist: ${input.path}`);
  306. }
  307. return requested;
  308. }
  309. if (hasPluginManifest(extractRoot)) {
  310. return extractRoot;
  311. }
  312. if (input.stripRoot !== false && input.topLevelSegments.size === 1) {
  313. const [segment] = [...input.topLevelSegments];
  314. if (segment) {
  315. const candidate = resolveZipPathWithin(extractRoot, segment);
  316. if (directoryExists(candidate)) return candidate;
  317. }
  318. }
  319. if (!directoryExists(extractRoot)) {
  320. throw new Error("Plugin zip did not extract a plugin root directory");
  321. }
  322. return extractRoot;
  323. }
  324. function hasPluginManifest(rootPath: string): boolean {
  325. return (
  326. fileExists(join(rootPath, ".zcode-plugin", "plugin.json")) ||
  327. fileExists(join(rootPath, ".claude-plugin", "plugin.json")) ||
  328. fileExists(join(rootPath, ".codex-plugin", "plugin.json"))
  329. );
  330. }
  331. function openZipFile(path: string): Promise<yauzl.ZipFile> {
  332. return new Promise((resolvePromise, rejectPromise) => {
  333. yauzl.open(path, { lazyEntries: true, validateEntrySizes: true }, (error, zipFile) => {
  334. if (error) {
  335. rejectPromise(error);
  336. return;
  337. }
  338. if (!zipFile) {
  339. rejectPromise(new Error("Failed to open plugin zip archive"));
  340. return;
  341. }
  342. resolvePromise(zipFile);
  343. });
  344. });
  345. }
  346. function readZipEntryBuffer(
  347. zipFile: yauzl.ZipFile,
  348. entry: yauzl.Entry,
  349. signal?: AbortSignal,
  350. ): Promise<Buffer> {
  351. return new Promise((resolvePromise, rejectPromise) => {
  352. zipFile.openReadStream(entry, (error, stream) => {
  353. if (error) {
  354. rejectPromise(error);
  355. return;
  356. }
  357. if (!stream) {
  358. rejectPromise(new Error(`Failed to read plugin zip entry: ${entry.fileName}`));
  359. return;
  360. }
  361. const chunks: Buffer[] = [];
  362. let bytesRead = 0;
  363. const cleanup = (): void => {
  364. signal?.removeEventListener("abort", onAbort);
  365. };
  366. const onAbort = (): void => {
  367. stream.destroy(new Error("Plugin operation cancelled"));
  368. };
  369. signal?.addEventListener("abort", onAbort, { once: true });
  370. stream.on("data", (chunk: Buffer | string) => {
  371. const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
  372. bytesRead += buffer.byteLength;
  373. if (bytesRead > ZIP_MAX_SINGLE_FILE_BYTES) {
  374. stream.destroy(
  375. new Error(`Plugin zip entry exceeds single file limit: ${entry.fileName}`),
  376. );
  377. return;
  378. }
  379. chunks.push(buffer);
  380. });
  381. stream.once("error", (streamError) => {
  382. cleanup();
  383. rejectPromise(streamError);
  384. });
  385. stream.once("end", () => {
  386. cleanup();
  387. resolvePromise(Buffer.concat(chunks));
  388. });
  389. });
  390. });
  391. }
  392. function classifyZipEntry(entry: yauzl.Entry): ZipEntryKind {
  393. const isDirectoryByName = entry.fileName.endsWith("/");
  394. if ((entry.generalPurposeBitFlag & 0x1) !== 0) {
  395. throw new Error(`Encrypted plugin zip entries are not supported: ${entry.fileName}`);
  396. }
  397. const unixMode = (entry.externalFileAttributes >>> 16) & 0xffff;
  398. const fileType = unixMode & 0o170000;
  399. if (fileType === 0o120000) {
  400. throw new Error(`Plugin zip entry symlinks are not supported: ${entry.fileName}`);
  401. }
  402. if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000) {
  403. throw new Error(`Unsupported plugin zip entry type: ${entry.fileName}`);
  404. }
  405. if (fileType === 0o040000 || isDirectoryByName) return "directory";
  406. return "file";
  407. }
  408. function normalizeZipRelativePath(path: string): string {
  409. if (path.includes("\0")) {
  410. throw new Error(`Unsafe plugin zip path: ${path}`);
  411. }
  412. const withoutTrailingSlash = path.replace(/\/+$/u, "");
  413. if (
  414. !withoutTrailingSlash ||
  415. path.includes("\\") ||
  416. isAbsolute(path) ||
  417. posix.isAbsolute(path) ||
  418. /^[a-zA-Z]:/u.test(path)
  419. ) {
  420. throw new Error(`Unsafe plugin zip path: ${path}`);
  421. }
  422. const parts = withoutTrailingSlash.split("/");
  423. if (parts.some((part) => !part || part === "." || part === "..")) {
  424. throw new Error(`Unsafe plugin zip path: ${path}`);
  425. }
  426. return withoutTrailingSlash;
  427. }
  428. function resolveZipPathWithin(rootPath: string, relativePath: string): string {
  429. const root = resolve(rootPath);
  430. const target = resolve(root, ...relativePath.split("/"));
  431. const rel = relative(root, target);
  432. if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
  433. throw new Error(`Unsafe plugin zip path: ${relativePath}`);
  434. }
  435. return target;
  436. }
  437. function validateZipHeaders(headers: Record<string, string> | undefined): void {
  438. if (!headers) return;
  439. for (const [key, value] of Object.entries(headers)) {
  440. if (ZIP_DENIED_HEADERS.has(key.toLowerCase())) {
  441. throw new Error(`Plugin zip source header is not allowed: ${key}`);
  442. }
  443. if (typeof value !== "string") {
  444. throw new Error(`Plugin zip source header must be a string: ${key}`);
  445. }
  446. }
  447. }
  448. function validateZipDownloadUrl(value: string): void {
  449. let url: URL;
  450. try {
  451. url = new URL(value);
  452. } catch {
  453. throw new Error(`Plugin zip source URL is invalid: ${value}`);
  454. }
  455. if (url.protocol === "https:") return;
  456. if (url.protocol === "http:" && isLoopbackHost(url.hostname)) return;
  457. throw new Error(`Plugin zip source URL must be HTTPS: ${value}`);
  458. }
  459. function isLoopbackHost(hostname: string): boolean {
  460. const normalized = hostname.toLowerCase();
  461. return (
  462. normalized === "localhost" ||
  463. normalized === "::1" ||
  464. normalized === "[::1]" ||
  465. isIpv4LoopbackHost(normalized)
  466. );
  467. }
  468. function isIpv4LoopbackHost(hostname: string): boolean {
  469. const match = /^127(?:\.(\d{1,3})){3}$/u.exec(hostname);
  470. if (!match) return false;
  471. return hostname
  472. .split(".")
  473. .every((part) => Number.parseInt(part, 10) >= 0 && Number.parseInt(part, 10) <= 255);
  474. }
  475. function isRedirectStatus(status: number): boolean {
  476. return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
  477. }
  478. function throwIfAborted(signal: AbortSignal | undefined): void {
  479. if (signal?.aborted) {
  480. const error = new Error("Plugin operation cancelled");
  481. error.name = "AbortError";
  482. throw error;
  483. }
  484. }