verify-proxy-stdio-docker.mjs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. #!/usr/bin/env node
  2. /**
  3. * R3 Docker Transport 验证:在真实 Linux 容器内安装 staged Source Server,启动 Core,
  4. * 再通过正式 `zcode server proxy-stdio` 的 stdin/stdout 访问受鉴权的 ingress。
  5. */
  6. import { spawn } from "node:child_process";
  7. import { randomBytes } from "node:crypto";
  8. import { dirname, join, resolve } from "node:path";
  9. import { fileURLToPath } from "node:url";
  10. import { resolveVerificationTarget } from "./verify-remote-ssh-target.mjs";
  11. const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  12. const argv = process.argv.slice(2);
  13. const readArg = (flag) => {
  14. const index = argv.indexOf(flag);
  15. return index >= 0 ? argv[index + 1] : undefined;
  16. };
  17. const target = resolveVerificationTarget(readArg("--target"));
  18. const archive = join(packageRoot, "dist-release", `zcode-server-${target}.tar.gz`);
  19. const containerName = `zcode-proxy-stdio-${process.pid}`;
  20. const image = process.env.ZCODE_PROXY_STDIO_IMAGE ?? "node:24-bookworm-slim";
  21. function run(command, args, options = {}) {
  22. return new Promise((resolvePromise, rejectPromise) => {
  23. const child = spawn(command, args, {
  24. stdio: [options.input ? "pipe" : "ignore", "pipe", "pipe"],
  25. });
  26. const stdout = [];
  27. const stderr = [];
  28. child.stdout.on("data", (chunk) => stdout.push(chunk));
  29. child.stderr.on("data", (chunk) => stderr.push(chunk));
  30. if (options.input) child.stdin.end(options.input);
  31. child.once("error", rejectPromise);
  32. child.once("exit", (code) => {
  33. const result = {
  34. code: code ?? 1,
  35. stdout: Buffer.concat(stdout),
  36. stderr: Buffer.concat(stderr),
  37. };
  38. if (result.code === 0 || options.allowFailure) resolvePromise(result);
  39. else
  40. rejectPromise(
  41. new Error(`${command} ${args.join(" ")} failed: ${result.stderr.toString("utf8")}`),
  42. );
  43. });
  44. });
  45. }
  46. function assert(condition, message) {
  47. if (!condition) throw new Error(`Assertion failed: ${message}`);
  48. }
  49. let exitCode = 0;
  50. try {
  51. await run("docker", ["version"]);
  52. await run("docker", ["run", "--detach", "--name", containerName, image, "sleep", "infinity"]);
  53. await run("docker", ["cp", archive, `${containerName}:/tmp/zcode-server.tar.gz`]);
  54. await run("docker", [
  55. "exec",
  56. containerName,
  57. "sh",
  58. "-lc",
  59. [
  60. "mkdir -p /tmp/zcode-bootstrap",
  61. "tar -xzf /tmp/zcode-server.tar.gz -C /tmp/zcode-bootstrap --strip-components=1",
  62. "/tmp/zcode-bootstrap/bin/zcode update --from-archive /tmp/zcode-server.tar.gz --server-root /root/.zcode/server --json",
  63. "ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1 /root/.zcode/server/bin/zcode serve --daemon --server-root /root/.zcode/server --json",
  64. ].join(" && "),
  65. ]);
  66. const statusResult = await run("docker", [
  67. "exec",
  68. containerName,
  69. "/root/.zcode/server/bin/zcode",
  70. "status",
  71. "--server-root",
  72. "/root/.zcode/server",
  73. "--json",
  74. ]);
  75. const status = JSON.parse(statusResult.stdout.toString("utf8").trim().split("\n").pop());
  76. assert(status.state === "ready", `Source Server ready, got ${status.state}`);
  77. const tokenResult = await run("docker", [
  78. "exec",
  79. containerName,
  80. "cat",
  81. "/root/.zcode/server/run/ingress-token",
  82. ]);
  83. const token = tokenResult.stdout.toString("utf8").trim();
  84. assert(token.length >= 32, "ingress token exists");
  85. // Docker exec -i 是正式 proxy-stdio 的底层字节桥;HTTP 200 只能证明文本请求成功,
  86. // 不能替代 NUL/高位字节/大 chunk 的无损守护。保留独立 64 KiB round-trip 断言。
  87. const binaryPayload = Buffer.concat([
  88. Buffer.from([0, 1, 2, 13, 10, 127, 128, 254, 255]),
  89. randomBytes(64 * 1024),
  90. ]);
  91. const binaryRoundTrip = await run("docker", ["exec", "-i", containerName, "sh", "-lc", "cat"], {
  92. input: binaryPayload,
  93. });
  94. assert(binaryRoundTrip.stdout.equals(binaryPayload), "docker exec preserves 64 KiB binary data");
  95. assert(binaryRoundTrip.stderr.length === 0, "docker exec binary bridge keeps stderr empty");
  96. const request = Buffer.from(
  97. `GET /api/server-info HTTP/1.1\r\nHost: source-server\r\nAuthorization: Bearer ${token}\r\nConnection: close\r\n\r\n`,
  98. "utf8",
  99. );
  100. const response = await run(
  101. "docker",
  102. [
  103. "exec",
  104. "-i",
  105. containerName,
  106. "/root/.zcode/server/bin/zcode",
  107. "server",
  108. "proxy-stdio",
  109. "--server-root",
  110. "/root/.zcode/server",
  111. ],
  112. { input: request },
  113. );
  114. const rawResponse = response.stdout.toString("utf8");
  115. assert(
  116. rawResponse.startsWith("HTTP/1.1 200"),
  117. `proxy response is HTTP 200: ${rawResponse.slice(0, 80)}`,
  118. );
  119. assert(rawResponse.includes('"serverId"'), "proxy response contains server-info JSON");
  120. console.log(
  121. `[verify-proxy-stdio-docker] PASS target=${target} httpBytes=${response.stdout.length} binaryBytes=${binaryPayload.length}`,
  122. );
  123. } catch (error) {
  124. exitCode = 1;
  125. console.error(
  126. "[verify-proxy-stdio-docker] FAILED:",
  127. error instanceof Error ? error.message : error,
  128. );
  129. } finally {
  130. await run("docker", ["rm", "-f", containerName], { allowFailure: true }).catch(() => undefined);
  131. }
  132. process.exit(exitCode);