preinstalled-tools-rewrite-fixture.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { createServer, type ServerResponse } from "node:http";
  4. import { cp, mkdir, mkdtemp, readFile, readdir, stat, writeFile } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { create as createTar } from "tar";
  8. const exec = promisify(execFile);
  9. const PREFIX = `/build/${"relocatable-prefix-".repeat(32)}`;
  10. const SCENARIOS = [
  11. "plain",
  12. "success",
  13. "dir-prefix",
  14. "dir-prefix-too-long",
  15. "dir-prefix-invalid",
  16. "dir-prefix-binary",
  17. "too-long",
  18. "missing",
  19. "signing-failure",
  20. "cancel",
  21. ] as const;
  22. const CANCEL_FILES = 4096;
  23. /** 真实 Mach-O 与文本归档;只通过 catalog、HTTP、公开命令和文件系统控制验收。 */
  24. export async function startPreinstalledToolsRewriteFixture(artifactDirectory: string) {
  25. if (process.platform !== "darwin") throw new Error("路径改写候选需要 macOS 原生签名工具");
  26. await mkdir(artifactDirectory, { recursive: true });
  27. // 同一报告目录可启动多轮候选,清单与归档必须各自拥有目录,不能覆盖上一轮。
  28. const directory = await mkdtemp(join(artifactDirectory, "session-"));
  29. const source = join(directory, "probe.c");
  30. const original = join(directory, "probe");
  31. await writeFile(
  32. source,
  33. `#include <stdio.h>\nstatic const char target[] = "${PREFIX}/data/value.txt";\nint main(void) { char value[4096]; FILE *file = fopen(target, "r"); if (!file) { perror(target); return 2; } if (!fgets(value, sizeof(value), file)) return 3; fclose(file); printf("rewrite-ok:%s\\n", value); return 0; }\n`,
  34. );
  35. await exec("clang", ["-O0", source, "-o", original]);
  36. await exec("/usr/bin/codesign", [
  37. "--force",
  38. "--sign",
  39. "-",
  40. "--identifier",
  41. "example.preinstalled.rewrite",
  42. original,
  43. ]);
  44. const originalBinary = await readFile(original);
  45. const directorySource = join(directory, "directory-probe.cpp");
  46. const directoryProbe = join(directory, "directory-probe");
  47. await writeFile(
  48. directorySource,
  49. `#include <stdio.h>\n#include <string>\nstatic const char root[] = "${PREFIX}";\nint main() { std::string path(root, sizeof(root)-1); path += "/data/value.txt"; FILE *file=fopen(path.c_str(),"r"); if(!file) { perror(path.c_str()); return 2; } char value[4096]; if(!fgets(value,sizeof(value),file)) return 3; fclose(file); printf("rewrite-ok:%s\\n",value); }\n`,
  50. );
  51. await exec("clang++", ["-O2", directorySource, "-o", directoryProbe]);
  52. await exec("/usr/bin/codesign", ["--force", "--sign", "-", directoryProbe]);
  53. const directoryData = Buffer.from(`${PREFIX}/one\0${PREFIX}/two\0${PREFIX}`);
  54. const binaryData = Buffer.from(`${PREFIX}/one:${PREFIX}/二\0tail/${PREFIX}/tail`);
  55. const resources = new Map<string, Buffer>();
  56. const manifests = new Map<string, unknown>();
  57. const catalogPath = join(directory, "catalog.json");
  58. const requests: string[] = [];
  59. const pending = new Map<string, Set<ServerResponse>>();
  60. const released = new Set<string>();
  61. const server = createServer((request, response) => {
  62. void (async () => {
  63. const [kind, name] = (request.url ?? "").split("/").filter(Boolean);
  64. if (kind === "archive" && name && resources.has(name)) {
  65. requests.push(name);
  66. const bytes = resources.get(name)!;
  67. response.writeHead(200, { "content-length": bytes.length });
  68. if (["cancel", "signing-failure"].includes(name) && !released.has(name)) {
  69. const waiting = pending.get(name) ?? new Set<ServerResponse>();
  70. pending.set(name, waiting);
  71. waiting.add(response);
  72. response.write(bytes.subarray(0, Math.floor(bytes.length / 2)));
  73. response.once("close", () => waiting.delete(response));
  74. } else response.end(bytes);
  75. } else if (kind === "release" && name && resources.has(name)) {
  76. released.add(name);
  77. const bytes = resources.get(name)!;
  78. for (const waiting of pending.get(name) ?? [])
  79. waiting.end(bytes.subarray(Math.floor(bytes.length / 2)));
  80. pending.delete(name);
  81. response.end("released");
  82. } else if (kind === "scenario" && name && manifests.has(name)) {
  83. await writeFile(
  84. catalogPath,
  85. JSON.stringify([
  86. { toolId: "qpdf", displayName: "qpdf", resources: [manifests.get(name)] },
  87. ]),
  88. );
  89. response.end("selected");
  90. } else if (kind === "status") {
  91. response.setHeader("content-type", "application/json");
  92. response.end(
  93. JSON.stringify({
  94. requests,
  95. pending: [...pending].filter(([, waiting]) => waiting.size > 0).map(([name]) => name),
  96. binarySize: binaryData.length,
  97. directoryPrefixSize: directoryData.length,
  98. originalBinarySha256: createHash("sha256").update(originalBinary).digest("hex"),
  99. }),
  100. );
  101. } else response.writeHead(404).end();
  102. })().catch((error: unknown) => response.writeHead(500).end(String(error)));
  103. });
  104. await new Promise<void>((resolve, reject) => {
  105. server.once("error", reject);
  106. server.listen(0, "127.0.0.1", resolve);
  107. });
  108. const address = server.address();
  109. if (!address || typeof address === "string") throw new Error("rewrite fixture address missing");
  110. const url = `http://127.0.0.1:${address.port}`;
  111. for (const scenario of SCENARIOS) {
  112. const payload = join(directory, scenario);
  113. await mkdir(join(payload, "bin"), { recursive: true });
  114. await mkdir(join(payload, "data"), { recursive: true });
  115. await cp(original, join(payload, "bin", "probe"));
  116. await cp(original, join(payload, "bin", "unchanged"));
  117. await writeFile(join(payload, "bin", "plain"), "#!/bin/sh\nprintf 'plain-ok\\n'\n", {
  118. mode: 0o755,
  119. });
  120. await writeFile(join(payload, "data", "value.txt"), PREFIX);
  121. await writeFile(join(payload, "data", "binary.bin"), binaryData);
  122. await writeFile(join(payload, "data", "directory.bin"), directoryData);
  123. await cp(directoryProbe, join(payload, "bin", "directory-probe"));
  124. const rewrite = [{ path: "data/value.txt", placeholder: PREFIX, mode: "text" }];
  125. if (scenario === "cancel" || scenario === "signing-failure") {
  126. await mkdir(join(payload, "wait"));
  127. // 多个真实文件形成可观察的改写区间;取消由首个文件内容变化触发,不靠延时猜时序。
  128. for (let index = 0; index < CANCEL_FILES; index += 1) {
  129. const path = `wait/${index}.txt`;
  130. await writeFile(join(payload, path), PREFIX);
  131. rewrite.push({ path, placeholder: PREFIX, mode: "text" });
  132. }
  133. }
  134. rewrite.push({ path: "data/binary.bin", placeholder: PREFIX, mode: "binary" });
  135. if (scenario.startsWith("dir-prefix")) {
  136. rewrite.push({ path: "data/directory.bin", placeholder: PREFIX, mode: "binary-dir-prefix" });
  137. rewrite.push({
  138. path: "bin/directory-probe",
  139. placeholder: PREFIX,
  140. mode: scenario === "dir-prefix-binary" ? "binary" : "binary-dir-prefix",
  141. });
  142. }
  143. if (scenario === "dir-prefix-too-long") {
  144. await writeFile(join(payload, "data", "short-directory.bin"), "/短/suffix\0");
  145. rewrite.push({
  146. path: "data/short-directory.bin",
  147. placeholder: "/短",
  148. mode: "binary-dir-prefix",
  149. });
  150. }
  151. if (scenario === "dir-prefix-invalid") {
  152. await writeFile(join(payload, "data", "directory.bin"), `${PREFIX}/valid\0${PREFIX}Suffix`);
  153. }
  154. if (scenario === "too-long") {
  155. await writeFile(join(payload, "data", "short.bin"), "/short/suffix\0");
  156. rewrite.push({ path: "data/short.bin", placeholder: "/short", mode: "binary" });
  157. }
  158. if (scenario === "missing")
  159. rewrite.push({ path: "data/missing.txt", placeholder: PREFIX, mode: "text" });
  160. if (scenario === "signing-failure") {
  161. await cp(original, join(payload, "bin", "signing-probe"));
  162. rewrite.push({ path: "bin/signing-probe", placeholder: PREFIX, mode: "binary" });
  163. }
  164. rewrite.push({ path: "bin/probe", placeholder: PREFIX, mode: "binary" });
  165. rewrite.push({ path: "bin/unchanged", placeholder: `${PREFIX}-not-present`, mode: "binary" });
  166. const archivePath = join(directory, `${scenario}.tar.gz`);
  167. const roots = await readdir(payload);
  168. await createTar({ gzip: true, portable: true, cwd: payload, file: archivePath }, roots);
  169. const bytes = await readFile(archivePath);
  170. resources.set(scenario, bytes);
  171. let installedSizeBytes = 0;
  172. for (const path of await readdir(payload, { recursive: true })) {
  173. const file = await stat(join(payload, path));
  174. if (file.isFile()) installedSizeBytes += file.size;
  175. }
  176. const target =
  177. scenario === "plain"
  178. ? "bin/plain"
  179. : scenario.startsWith("dir-prefix")
  180. ? "bin/directory-probe"
  181. : "bin/probe";
  182. manifests.set(scenario, {
  183. toolId: "qpdf",
  184. resourceId: `rewrite-${scenario}-${process.arch}`,
  185. version: "1.0",
  186. platforms: [{ platform: process.platform, arch: process.arch }],
  187. binaryArch: process.arch,
  188. archive: {
  189. format: "tar.gz",
  190. sizeBytes: bytes.length,
  191. sha256: createHash("sha256").update(bytes).digest("hex"),
  192. path: `archive/${scenario}`,
  193. },
  194. installedSizeBytes,
  195. requiredFiles: [target, "bin/unchanged", "data/value.txt", "data/binary.bin"],
  196. entries: [{ name: "qpdf", target, args: [], env: [] }],
  197. runtimeChecks: [
  198. {
  199. entry: "qpdf",
  200. args: [],
  201. expectedOutput: scenario === "plain" ? "plain-ok" : "rewrite-ok:",
  202. timeoutMs: 30000,
  203. },
  204. ],
  205. ...(scenario === "plain" ? {} : { rewrite }),
  206. });
  207. }
  208. await writeFile(
  209. catalogPath,
  210. JSON.stringify([{ toolId: "qpdf", displayName: "qpdf", resources: [manifests.get("plain")] }]),
  211. );
  212. return {
  213. url,
  214. cdnBaseUrl: url,
  215. catalogPath,
  216. stop: async () => {
  217. await writeFile(join(directory, "requests.json"), JSON.stringify(requests));
  218. server.closeAllConnections();
  219. await new Promise<void>((resolve, reject) =>
  220. server.close((error) => (error ? reject(error) : resolve())),
  221. );
  222. },
  223. };
  224. }