pluginSyncArchive.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import { chmod, lstat, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  2. import { dirname, join, posix, resolve } from "node:path";
  3. import { promisify } from "node:util";
  4. import { gunzip, gzip } from "node:zlib";
  5. import {
  6. normalizePluginSyncRelativePath,
  7. resolvePluginSyncPathWithin,
  8. } from "./pluginSyncPath.js";
  9. const gzipAsync = promisify(gzip);
  10. const gunzipAsync = promisify(gunzip);
  11. const TAR_BLOCK_SIZE = 512;
  12. const TAR_END_BLOCK_BYTES = TAR_BLOCK_SIZE * 2;
  13. export const PLUGIN_SYNC_METADATA_ARCHIVE_PATH = ".zcode-plugin-sync.json";
  14. export type PluginSyncArchiveEntry =
  15. | {
  16. sourcePath: string;
  17. archivePath: string;
  18. }
  19. | {
  20. content: string | Uint8Array;
  21. archivePath: string;
  22. mode?: number;
  23. mtimeMs?: number;
  24. };
  25. export interface PluginSyncArchiveMetadata {
  26. plugins: Array<{
  27. name: string;
  28. pluginId: string;
  29. directoryName: string;
  30. enabled?: boolean;
  31. }>;
  32. marketplaceSources?: Array<{
  33. marketplaceId: string;
  34. directoryName: string;
  35. }>;
  36. }
  37. export interface PluginSyncArchiveExtractOptions {
  38. maxExtractedBytes?: number;
  39. }
  40. export async function createPluginSyncArchive(params: {
  41. entries: readonly PluginSyncArchiveEntry[];
  42. metadata: PluginSyncArchiveMetadata;
  43. }): Promise<Uint8Array> {
  44. const parts: Buffer[] = [];
  45. for (const entry of params.entries) {
  46. if ("sourcePath" in entry) {
  47. await appendTarEntry(parts, entry.sourcePath, normalizeArchivePath(entry.archivePath));
  48. } else {
  49. appendTarFile(
  50. parts,
  51. normalizeArchivePath(entry.archivePath),
  52. typeof entry.content === "string"
  53. ? Buffer.from(entry.content, "utf-8")
  54. : Buffer.from(entry.content),
  55. entry.mode,
  56. entry.mtimeMs,
  57. );
  58. }
  59. }
  60. appendTarFile(
  61. parts,
  62. PLUGIN_SYNC_METADATA_ARCHIVE_PATH,
  63. Buffer.from(`${JSON.stringify(params.metadata, null, 2)}\n`, "utf-8"),
  64. );
  65. parts.push(Buffer.alloc(TAR_END_BLOCK_BYTES));
  66. return await gzipAsync(Buffer.concat(parts));
  67. }
  68. export async function extractPluginSyncArchive(
  69. archive: Uint8Array,
  70. targetDir: string,
  71. options: PluginSyncArchiveExtractOptions = {},
  72. ): Promise<void> {
  73. const targetRoot = resolve(targetDir);
  74. await mkdir(targetRoot, { recursive: true });
  75. const maxExtractedBytes = options.maxExtractedBytes;
  76. const buffer = await gunzipWithLimit(archive, maxExtractedBytes);
  77. let offset = 0;
  78. let extractedBytes = 0;
  79. while (offset + TAR_BLOCK_SIZE <= buffer.length) {
  80. const header = buffer.subarray(offset, offset + TAR_BLOCK_SIZE);
  81. offset += TAR_BLOCK_SIZE;
  82. if (header.every((byte) => byte === 0)) {
  83. break;
  84. }
  85. const size = readTarOctal(header, 124, 12);
  86. const dataStart = offset;
  87. const dataEnd = dataStart + size;
  88. if (dataEnd > buffer.length) {
  89. throw new Error("truncated plugin sync archive entry");
  90. }
  91. const data = buffer.subarray(dataStart, dataEnd);
  92. offset = dataStart + Math.ceil(size / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE;
  93. const typeFlag = readTarString(header, 156, 1) || "0";
  94. const archivePath = normalizeArchivePath(readTarEntryPath(header));
  95. const targetPath = resolveWithin(targetRoot, archivePath);
  96. if (typeFlag === "5") {
  97. await mkdir(targetPath, { recursive: true });
  98. } else if (typeFlag === "0" || typeFlag === "\0") {
  99. extractedBytes += size;
  100. if (maxExtractedBytes !== undefined && extractedBytes > maxExtractedBytes) {
  101. throw new Error(
  102. `plugin sync archive exceeds limit: ${extractedBytes}/${maxExtractedBytes}`,
  103. );
  104. }
  105. const fileMode = readTarMode(header);
  106. await mkdir(dirname(targetPath), { recursive: true });
  107. await writeFile(targetPath, data, { mode: fileMode });
  108. if (process.platform !== "win32") {
  109. // writeFile 新建文件会受远端 umask 影响;plugin 脚本的可执行位必须按归档 header 恢复。
  110. await chmod(targetPath, fileMode);
  111. }
  112. } else {
  113. throw new Error(`unsupported plugin archive entry type: ${typeFlag}`);
  114. }
  115. }
  116. }
  117. async function gunzipWithLimit(
  118. archive: Uint8Array,
  119. maxExtractedBytes: number | undefined,
  120. ): Promise<Buffer> {
  121. if (maxExtractedBytes === undefined) {
  122. return await gunzipAsync(Buffer.from(archive));
  123. }
  124. const maxTarBytes = maxExtractedBytes + TAR_END_BLOCK_BYTES + TAR_BLOCK_SIZE * 512;
  125. try {
  126. return await gunzipAsync(Buffer.from(archive), {
  127. maxOutputLength: maxTarBytes,
  128. });
  129. } catch (error) {
  130. throw new Error(
  131. `plugin sync archive exceeds limit: ${
  132. error instanceof Error ? error.message : String(error)
  133. }`,
  134. );
  135. }
  136. }
  137. async function appendTarEntry(
  138. parts: Buffer[],
  139. sourcePath: string,
  140. archivePath: string,
  141. ): Promise<void> {
  142. const sourceStat = await lstat(sourcePath);
  143. if (sourceStat.isDirectory()) {
  144. const directoryEntryPath = ensureTrailingSlash(archivePath);
  145. parts.push(
  146. createTarHeader({
  147. entryPath: directoryEntryPath,
  148. mode: sourceStat.mode,
  149. mtimeSeconds: Math.floor(sourceStat.mtimeMs / 1000),
  150. size: 0,
  151. typeFlag: "5",
  152. }),
  153. );
  154. const children = (await readdir(sourcePath, { withFileTypes: true })).sort((left, right) =>
  155. left.name.localeCompare(right.name),
  156. );
  157. for (const child of children) {
  158. await appendTarEntry(
  159. parts,
  160. join(sourcePath, child.name),
  161. normalizeArchivePath(posix.join(archivePath, child.name)),
  162. );
  163. }
  164. return;
  165. }
  166. if (!sourceStat.isFile()) {
  167. throw new Error(`unsupported plugin archive source: ${sourcePath}`);
  168. }
  169. appendTarFile(parts, archivePath, await readFile(sourcePath), sourceStat.mode, sourceStat.mtimeMs);
  170. }
  171. function appendTarFile(
  172. parts: Buffer[],
  173. archivePath: string,
  174. content: Buffer,
  175. mode = 0o644,
  176. mtimeMs = Date.now(),
  177. ): void {
  178. parts.push(
  179. createTarHeader({
  180. entryPath: normalizeArchivePath(archivePath),
  181. mode,
  182. mtimeSeconds: Math.floor(mtimeMs / 1000),
  183. size: content.length,
  184. typeFlag: "0",
  185. }),
  186. content,
  187. Buffer.alloc(Math.ceil(content.length / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE - content.length),
  188. );
  189. }
  190. function createTarHeader(options: {
  191. entryPath: string;
  192. mode: number;
  193. mtimeSeconds: number;
  194. size: number;
  195. typeFlag: "0" | "5";
  196. }): Buffer {
  197. const header = Buffer.alloc(TAR_BLOCK_SIZE);
  198. const { name, prefix } = splitTarEntryPath(options.entryPath);
  199. writeTarString(header, name, 0, 100);
  200. writeTarOctal(header, options.mode & 0o777, 100, 8);
  201. writeTarOctal(header, 0, 108, 8);
  202. writeTarOctal(header, 0, 116, 8);
  203. writeTarOctal(header, options.size, 124, 12);
  204. writeTarOctal(header, options.mtimeSeconds, 136, 12);
  205. header.fill(0x20, 148, 156);
  206. writeTarString(header, options.typeFlag, 156, 1);
  207. writeTarString(header, "ustar", 257, 6);
  208. writeTarString(header, "00", 263, 2);
  209. writeTarString(header, "zcode", 265, 32);
  210. writeTarString(header, "zcode", 297, 32);
  211. writeTarString(header, prefix, 345, 155);
  212. writeTarChecksum(header, header.reduce((sum, byte) => sum + byte, 0));
  213. return header;
  214. }
  215. function splitTarEntryPath(entryPath: string): { name: string; prefix: string } {
  216. if (Buffer.byteLength(entryPath) <= 100) {
  217. return { name: entryPath, prefix: "" };
  218. }
  219. const segments = entryPath.split("/");
  220. for (let index = segments.length - 1; index > 0; index -= 1) {
  221. const prefix = segments.slice(0, index).join("/");
  222. const name = segments.slice(index).join("/");
  223. if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) {
  224. return { name, prefix };
  225. }
  226. }
  227. throw new Error(`plugin archive path is too long: ${entryPath}`);
  228. }
  229. function readTarEntryPath(header: Buffer): string {
  230. const name = readTarString(header, 0, 100);
  231. const prefix = readTarString(header, 345, 155);
  232. return prefix ? `${prefix}/${name}` : name;
  233. }
  234. function readTarString(buffer: Buffer, offset: number, length: number): string {
  235. const slice = buffer.subarray(offset, offset + length);
  236. const end = slice.indexOf(0);
  237. return slice.subarray(0, end === -1 ? slice.length : end).toString("utf8");
  238. }
  239. function readTarOctal(buffer: Buffer, offset: number, length: number): number {
  240. const raw = readTarString(buffer, offset, length).trim();
  241. return raw ? Number.parseInt(raw, 8) : 0;
  242. }
  243. function readTarMode(header: Buffer): number {
  244. const mode = readTarOctal(header, 100, 8);
  245. if (!Number.isFinite(mode) || mode <= 0) {
  246. return 0o644;
  247. }
  248. return mode & 0o777;
  249. }
  250. function writeTarString(
  251. buffer: Buffer,
  252. value: string,
  253. offset: number,
  254. length: number,
  255. ): void {
  256. const source = Buffer.from(value, "utf8");
  257. if (source.length > length) {
  258. throw new Error(`plugin archive header value is too long: ${value}`);
  259. }
  260. source.copy(buffer, offset);
  261. }
  262. function writeTarOctal(
  263. buffer: Buffer,
  264. value: number,
  265. offset: number,
  266. length: number,
  267. ): void {
  268. const encoded = value.toString(8).padStart(length - 1, "0");
  269. writeTarString(buffer, encoded, offset, length - 1);
  270. buffer[offset + length - 1] = 0;
  271. }
  272. function writeTarChecksum(buffer: Buffer, checksum: number): void {
  273. const encoded = checksum.toString(8).padStart(6, "0");
  274. writeTarString(buffer, encoded, 148, 6);
  275. buffer[154] = 0;
  276. buffer[155] = 0x20;
  277. }
  278. function ensureTrailingSlash(path: string): string {
  279. return path.endsWith("/") ? path : `${path}/`;
  280. }
  281. function normalizeArchivePath(path: string): string {
  282. return normalizePluginSyncRelativePath(path, {
  283. unsafePathLabel: "unsafe plugin archive path",
  284. });
  285. }
  286. function resolveWithin(targetRoot: string, archivePath: string): string {
  287. return resolvePluginSyncPathWithin(targetRoot, archivePath, {
  288. unsafePathLabel: "unsafe plugin archive path",
  289. });
  290. }