child-source-bundled.test.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /**
  2. * `renderChildEntry` 在 **esbuild 打包 / minify 之后**依然渲染出一份可运行的自包含入口文件。
  3. *
  4. * 为什么必须有这条测试:入口文件里的子进程逻辑是 `childMain.toString()` 拼出来的,而真实发布形态
  5. * 里这个函数先经 esbuild 打包(CLI 是单文件 bundle),desktop-agent 构建还会 minify。一旦
  6. * childMain 引用了模块作用域的任何绑定(常量、辅助函数、import),打包后那个标识符会被改名或
  7. * 提到别处,内嵌出来的文本就成了引用未定义标识符的非法程序——而且**只在发布产物里**坏,
  8. * 源码跑测试全绿。所以这里不测源码形态,专测打包形态,并且不止 `--check` 语法:真 spawn 一次
  9. * 跑到 complete,因为语法合法的坏程序(比如少了 bootstrap)照样能通过语法检查。
  10. *
  11. * esbuild 从 workspace 根解析而来(`apps/zcode-cli/package.json` 的依赖,CLI 的
  12. * `scripts/build.mjs` 用的是同一份)。
  13. */
  14. import { spawnSync } from "node:child_process";
  15. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  16. import { tmpdir } from "node:os";
  17. import { join } from "node:path";
  18. import { pathToFileURL } from "node:url";
  19. import { afterEach, describe, expect, it } from "vitest";
  20. import { build } from "esbuild";
  21. import type { renderChildEntry as renderChildEntryType } from "../src/child-source.js";
  22. const ENTRY = new URL("../src/child-source.ts", import.meta.url);
  23. const roots: string[] = [];
  24. afterEach(async () => {
  25. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  26. });
  27. async function tempRoot(prefix: string): Promise<string> {
  28. const root = await mkdtemp(join(tmpdir(), prefix));
  29. roots.push(root);
  30. return root;
  31. }
  32. /** 打包 child-source.ts 并取出打包产物里的 renderChildEntry(不是源码形态的那一份)。 */
  33. async function bundledRenderChildEntry(minify: boolean): Promise<typeof renderChildEntryType> {
  34. const root = await tempRoot("dwf-child-bundle-");
  35. const outfile = join(root, "child-source.mjs");
  36. await build({
  37. bundle: true,
  38. entryPoints: [new URL(ENTRY).pathname],
  39. format: "esm",
  40. // 与 CLI 发布构建同参:desktop-agent 是 minify + keepNames,普通/SEA 构建不压缩。
  41. keepNames: minify,
  42. minify,
  43. outfile,
  44. platform: "node",
  45. target: "node22",
  46. });
  47. const module = (await import(pathToFileURL(outfile).href)) as {
  48. renderChildEntry: typeof renderChildEntryType;
  49. };
  50. return module.renderChildEntry;
  51. }
  52. /** 按 harness 缺省策略写入口文件、真跑一次子进程,返回它写回的 NDJSON 行。 */
  53. async function runChild(
  54. render: typeof renderChildEntryType,
  55. payload: { lowered: string; args?: Record<string, unknown> },
  56. ): Promise<unknown[]> {
  57. const root = await tempRoot("dwf-child-entry-");
  58. const entryPath = join(root, "run.mjs");
  59. // run 身份是 payload 的必备字段(沙箱据它构造冻结的 `run` 全局)。
  60. await writeFile(
  61. entryPath,
  62. render({ ...payload, run: { id: "run" }, maxOldSpaceSizeMb: 256 }, { runId: "run" }),
  63. "utf8",
  64. );
  65. const result = spawnSync(process.execPath, ["--max-old-space-size=256", entryPath], {
  66. encoding: "utf8",
  67. input: "",
  68. timeout: 30_000,
  69. });
  70. // 子进程的 stderr 是这条测试唯一的归因材料——ReferenceError 之类会在这里现形。
  71. expect(result.stderr).toBe("");
  72. expect(result.status).toBe(0);
  73. return result.stdout
  74. .split("\n")
  75. .filter((line) => line.trim().length > 0)
  76. .map((line) => JSON.parse(line) as unknown);
  77. }
  78. describe.each([
  79. { label: "bundled", minify: false },
  80. { label: "bundled + minified", minify: true },
  81. ])("renderChildEntry ($label)", ({ minify }) => {
  82. it("runs the sandbox to completion", async () => {
  83. const render = await bundledRenderChildEntry(minify);
  84. const lines = await runChild(render, {
  85. lowered: '__host.log("from the sandbox");\nreturn { ok: 42 };',
  86. });
  87. expect(lines).toEqual([
  88. { kind: "event", type: "log", message: "from the sandbox" },
  89. { kind: "complete", ok: true, value: { ok: 42 } },
  90. ]);
  91. });
  92. it("lets no outer-realm function reach the script", async () => {
  93. // 跨 realm 边界(tests/security.test.ts 的 "realm boundary")在发布形态下同样成立:
  94. // 打包 / 压缩若把 null 原型沙箱或传输闭包弄丢,这里会拿到宿主 process。
  95. const render = await bundledRenderChildEntry(minify);
  96. const lines = await runChild(render, {
  97. lowered: [
  98. 'const foreign = (v) => (typeof v === "function" || (typeof v === "object" && v !== null)) && v.constructor !== undefined && v.constructor.constructor !== Function;',
  99. "const hits = [];",
  100. "for (const k of Object.getOwnPropertyNames(globalThis)) { let v; try { v = globalThis[k]; } catch (e) { continue; } if (foreign(v)) hits.push(k); }",
  101. 'let viaGlobal = "blocked";',
  102. 'try { viaGlobal = typeof globalThis.constructor.constructor("return process")(); } catch (e) {}',
  103. "return { hits, viaGlobal, send: typeof globalThis.__send, finish: typeof globalThis.__finish };",
  104. ].join("\n"),
  105. });
  106. expect(lines).toEqual([
  107. {
  108. kind: "complete",
  109. ok: true,
  110. value: { hits: [], viaGlobal: "blocked", send: "undefined", finish: "undefined" },
  111. },
  112. ]);
  113. });
  114. it("keeps the sandbox bans and the curated realm intact", async () => {
  115. const render = await bundledRenderChildEntry(minify);
  116. // bootstrap 若被打包丢掉,脚本会拿到一个没有禁令的裸 context——那时这里会返回 ok:true。
  117. const lines = await runChild(render, {
  118. lowered: [
  119. "let bans = [];",
  120. 'try { Date.now(); } catch (e) { bans.push("Date.now"); }',
  121. 'try { Math.random(); } catch (e) { bans.push("Math.random"); }',
  122. 'return { bans, hasProcess: typeof process !== "undefined", hostKeys: Object.keys(__host).sort() };',
  123. ].join("\n"),
  124. });
  125. expect(lines).toEqual([
  126. {
  127. kind: "complete",
  128. ok: true,
  129. value: {
  130. bans: ["Date.now", "Math.random"],
  131. hasProcess: false,
  132. // Boundary A 的全部成员。产物的两族在这里就分得开:publishArtifact 是效应
  133. // (request/response),declareArtifact 是声明(事件通道)。
  134. hostKeys: [
  135. "args",
  136. "ask",
  137. "channel",
  138. "createActor",
  139. "declareArtifact",
  140. "enterPhase",
  141. "future",
  142. "hole",
  143. "log",
  144. "publishArtifact",
  145. "report",
  146. // run 身份(facade 的 `run`):与 args 一样是值,不是可调用物。
  147. "run",
  148. "worldRead",
  149. ],
  150. },
  151. },
  152. ]);
  153. });
  154. });