source-archive.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { spawnSync } from "node:child_process";
  2. import path from "node:path";
  3. import { t as list, x as extract } from "tar";
  4. // Validate the entire archive before either extractor writes anything. Native
  5. // tar avoids thousands of Node filesystem operations on Windows runners.
  6. export async function extractSourceArchive(
  7. file,
  8. cwd,
  9. extractor = process.platform === "win32" ? "native" : "node",
  10. ) {
  11. if (!["native", "node"].includes(extractor))
  12. throw new Error("Unknown source extractor");
  13. let unsafe = false;
  14. let entries = 0;
  15. const seen = new Set();
  16. await list({
  17. file,
  18. strict: true,
  19. onReadEntry(entry) {
  20. const name = entry.path.replace(/\/$/u, "");
  21. const parts = name.split("/");
  22. const key = process.platform === "win32" ? name.toLowerCase() : name;
  23. if (
  24. parts[0] !== "minimax-code" ||
  25. parts.some((p) => !p || p === "." || p === ".." || p === ".git") ||
  26. /[\\:\x00]/u.test(name) ||
  27. !["File", "Directory"].includes(entry.type) ||
  28. seen.has(key)
  29. )
  30. unsafe = true;
  31. seen.add(key);
  32. entries++;
  33. },
  34. });
  35. if (unsafe || entries === 0)
  36. throw new Error("Archive contains an unreviewed path or file type");
  37. if (extractor === "native") {
  38. // Git Bash prepends its GNU tar to PATH. Unlike Windows' bundled bsdtar,
  39. // it can interpret a drive-letter archive path as a remote host. Select
  40. // the Windows executable explicitly so both shells extract identically.
  41. const nativeTar = process.platform === "win32"
  42. ? path.join(process.env.SystemRoot || "C:\\Windows", "System32", "tar.exe")
  43. : "tar";
  44. const result = spawnSync(nativeTar, ["-xzf", file, "-C", cwd], {
  45. encoding: "utf8",
  46. });
  47. if (result.error?.code !== "ENOENT") {
  48. if (result.error || result.status !== 0)
  49. throw new Error(`Native source extraction failed: ${result.error?.message || result.stderr?.trim() || `exit ${result.status}`}`);
  50. return "native";
  51. }
  52. // Source export remains usable on machines without an external tar binary.
  53. }
  54. await extract({ file, cwd, strict: true });
  55. return "node";
  56. }