deterministic-tar-archive.mjs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import { lstatSync, readFileSync, readdirSync, readlinkSync, writeFileSync } from "node:fs";
  2. import { createHash } from "node:crypto";
  3. import { basename, join } from "node:path";
  4. import { constants as zlibConstants, gzipSync } from "node:zlib";
  5. function collectDeterministicTarEntries(sourcePath) {
  6. const sourceStat = lstatSync(sourcePath);
  7. const entries = [];
  8. function visit(currentPath, relativePath) {
  9. const currentStat = lstatSync(currentPath);
  10. if (currentStat.isDirectory()) {
  11. if (relativePath) {
  12. entries.push({
  13. type: "directory",
  14. relativePath: `${relativePath.replace(/\/+$/u, "")}/`,
  15. });
  16. }
  17. const children = readdirSync(currentPath)
  18. .slice()
  19. .sort((left, right) => left.localeCompare(right, "en"));
  20. for (const child of children) {
  21. visit(join(currentPath, child), relativePath ? `${relativePath}/${child}` : child);
  22. }
  23. return;
  24. }
  25. if (currentStat.isSymbolicLink()) {
  26. entries.push({
  27. type: "symlink",
  28. relativePath,
  29. linkName: readlinkSync(currentPath).replace(/\\/gu, "/"),
  30. });
  31. return;
  32. }
  33. if (!currentStat.isFile()) {
  34. throw new Error(`Unsupported component archive entry: ${currentPath}`);
  35. }
  36. entries.push({
  37. type: "file",
  38. relativePath,
  39. mode: currentStat.mode & 0o111 ? 0o755 : 0o644,
  40. data: readFileSync(currentPath),
  41. });
  42. }
  43. if (sourceStat.isDirectory()) {
  44. visit(sourcePath, "");
  45. return entries;
  46. }
  47. visit(sourcePath, basename(sourcePath));
  48. return entries;
  49. }
  50. function writeTarOctal(buffer, offset, length, value) {
  51. const text = Math.trunc(value)
  52. .toString(8)
  53. .padStart(length - 1, "0");
  54. buffer.write(text.slice(-(length - 1)), offset, length - 1, "ascii");
  55. buffer[offset + length - 1] = 0;
  56. }
  57. function splitTarPath(relativePath) {
  58. const normalizedPath = relativePath.replace(/\\/gu, "/");
  59. if (Buffer.byteLength(normalizedPath) <= 100) {
  60. return { name: normalizedPath, prefix: "" };
  61. }
  62. const parts = normalizedPath.split("/");
  63. for (let index = 1; index < parts.length; index += 1) {
  64. const prefix = parts.slice(0, index).join("/");
  65. const name = parts.slice(index).join("/");
  66. if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) {
  67. return { name, prefix };
  68. }
  69. }
  70. throw new Error(`Component archive path is too long for ustar: ${relativePath}`);
  71. }
  72. function buildTarHeader(entry) {
  73. const header = Buffer.alloc(512, 0);
  74. const { name, prefix } = splitTarPath(entry.relativePath);
  75. const mode = entry.type === "file" ? entry.mode : entry.type === "directory" ? 0o755 : 0o777;
  76. const size = entry.type === "file" ? entry.data.length : 0;
  77. const typeFlag = entry.type === "directory" ? "5" : entry.type === "symlink" ? "2" : "0";
  78. header.write(name, 0, 100, "utf8");
  79. writeTarOctal(header, 100, 8, mode);
  80. writeTarOctal(header, 108, 8, 0);
  81. writeTarOctal(header, 116, 8, 0);
  82. writeTarOctal(header, 124, 12, size);
  83. writeTarOctal(header, 136, 12, 0);
  84. header.fill(0x20, 148, 156);
  85. header.write(typeFlag, 156, 1, "ascii");
  86. if (entry.type === "symlink") {
  87. header.write(entry.linkName, 157, 100, "utf8");
  88. }
  89. header.write("ustar", 257, 5, "ascii");
  90. header[262] = 0;
  91. header.write("00", 263, 2, "ascii");
  92. header.write("root", 265, 32, "ascii");
  93. header.write("root", 297, 32, "ascii");
  94. header.write(prefix, 345, 155, "utf8");
  95. let checksum = 0;
  96. for (const byte of header) checksum += byte;
  97. const checksumText = checksum.toString(8).padStart(6, "0");
  98. header.write(checksumText.slice(-6), 148, 6, "ascii");
  99. header[154] = 0;
  100. header[155] = 0x20;
  101. return header;
  102. }
  103. export function packSourceAsDeterministicTarGzip(sourcePath, artifactPath) {
  104. const chunks = [];
  105. for (const entry of collectDeterministicTarEntries(sourcePath)) {
  106. chunks.push(buildTarHeader(entry));
  107. if (entry.type !== "file") continue;
  108. chunks.push(entry.data);
  109. const padding = (512 - (entry.data.length % 512)) % 512;
  110. if (padding > 0) chunks.push(Buffer.alloc(padding, 0));
  111. }
  112. chunks.push(Buffer.alloc(1024, 0));
  113. // 归档路径会作为静态 deps 资源长期复用;固定 tar 元数据与 gzip mtime,避免同一二进制
  114. // 因 producer 的用户、目录或时间不同而生成不同归档。
  115. const archive = gzipSync(Buffer.concat(chunks), {
  116. filename: "",
  117. level: zlibConstants.Z_BEST_COMPRESSION,
  118. mtime: 0,
  119. });
  120. archive[9] = 255;
  121. writeFileSync(artifactPath, archive);
  122. }
  123. export function computeDeterministicSourceSha256(sourcePath) {
  124. const hash = createHash("sha256");
  125. for (const entry of collectDeterministicTarEntries(sourcePath)) {
  126. hash.update(
  127. `${JSON.stringify({
  128. type: entry.type,
  129. relativePath: entry.relativePath,
  130. mode: entry.mode,
  131. linkName: entry.linkName,
  132. size: entry.type === "file" ? entry.data.length : 0,
  133. })}\n`,
  134. "utf8",
  135. );
  136. if (entry.type === "file") {
  137. hash.update(entry.data);
  138. hash.update("\n", "utf8");
  139. }
  140. }
  141. return hash.digest("hex");
  142. }