verify-proxy-stdio-wsl.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. #!/usr/bin/env node
  2. /**
  3. * R3 WSL Transport smoke:在真实 WSL 中从 archive 安装 Source Server,启动 daemon,
  4. * 并通过正式 proxy-stdio 验证鉴权 HTTP 与 64 KiB WSL stdio 字节桥。
  5. */
  6. import { spawn } from "node:child_process";
  7. import { randomBytes } from "node:crypto";
  8. import { readFile } from "node:fs/promises";
  9. import { dirname, join, resolve } from "node:path";
  10. import { fileURLToPath } from "node:url";
  11. import { resolveVerificationTarget } from "./verify-remote-ssh-target.mjs";
  12. const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  13. const argv = process.argv.slice(2);
  14. const readArg = (flag) => {
  15. const index = argv.indexOf(flag);
  16. return index >= 0 ? argv[index + 1] : undefined;
  17. };
  18. const target = resolveVerificationTarget(readArg("--target"));
  19. const distro = readArg("--distro");
  20. const archive = join(packageRoot, "dist-release", `zcode-server-${target}.tar.gz`);
  21. const operationId = `zcode-wsl-verify-${process.pid}`;
  22. const archivePath = `/tmp/${operationId}.tar.gz`;
  23. const bootstrapDir = `/tmp/${operationId}-bootstrap`;
  24. const serverRoot = `/tmp/${operationId}-server`;
  25. const wslBaseArgs = [...(distro ? ["--distribution", distro] : []), "--"];
  26. function run(command, args, options = {}) {
  27. return new Promise((resolvePromise, rejectPromise) => {
  28. const child = spawn(command, args, {
  29. stdio: [options.input ? "pipe" : "ignore", "pipe", "pipe"],
  30. });
  31. const stdout = [];
  32. const stderr = [];
  33. child.stdout.on("data", (chunk) => stdout.push(chunk));
  34. child.stderr.on("data", (chunk) => stderr.push(chunk));
  35. if (options.input) child.stdin.end(options.input);
  36. child.once("error", rejectPromise);
  37. child.once("exit", (code) => {
  38. const result = {
  39. code: code ?? 1,
  40. stdout: Buffer.concat(stdout),
  41. stderr: Buffer.concat(stderr),
  42. };
  43. if (result.code === 0 || options.allowFailure) resolvePromise(result);
  44. else
  45. rejectPromise(
  46. new Error(`${command} ${args.join(" ")} failed: ${result.stderr.toString("utf8")}`),
  47. );
  48. });
  49. });
  50. }
  51. const wsl = (args, options) => run("wsl.exe", [...wslBaseArgs, ...args], options);
  52. const shell = (script, options) => wsl(["sh", "-lc", script], options);
  53. function assert(condition, message) {
  54. if (!condition) throw new Error(`Assertion failed: ${message}`);
  55. }
  56. let exitCode = 0;
  57. try {
  58. await wsl(["true"]);
  59. await shell(
  60. `rm -rf '${bootstrapDir}' '${serverRoot}' '${archivePath}' && cat > '${archivePath}'`,
  61. {
  62. input: await readFile(archive),
  63. },
  64. );
  65. await shell(
  66. [
  67. `mkdir -p '${bootstrapDir}'`,
  68. `tar -xzf '${archivePath}' -C '${bootstrapDir}' --strip-components=1`,
  69. `'${bootstrapDir}/bin/zcode' update --from-archive '${archivePath}' --server-root '${serverRoot}' --json`,
  70. `ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1 '${serverRoot}/bin/zcode' serve --daemon --server-root '${serverRoot}' --json`,
  71. ].join(" && "),
  72. );
  73. const statusResult = await wsl([
  74. `${serverRoot}/bin/zcode`,
  75. "status",
  76. "--server-root",
  77. serverRoot,
  78. "--json",
  79. ]);
  80. const status = JSON.parse(statusResult.stdout.toString("utf8").trim().split("\n").pop());
  81. assert(status.state === "ready", `Source Server ready, got ${status.state}`);
  82. const token = (await shell(`cat '${serverRoot}/run/ingress-token'`)).stdout
  83. .toString("utf8")
  84. .trim();
  85. assert(token.length >= 32, "ingress token exists");
  86. const binaryPayload = Buffer.concat([
  87. Buffer.from([0, 1, 2, 13, 10, 127, 128, 254, 255]),
  88. randomBytes(64 * 1024),
  89. ]);
  90. const binaryRoundTrip = await shell("cat", { input: binaryPayload });
  91. assert(binaryRoundTrip.stdout.equals(binaryPayload), "WSL stdio preserves 64 KiB binary data");
  92. const request = Buffer.from(
  93. `GET /api/server-info HTTP/1.1\r\nHost: source-server\r\nAuthorization: Bearer ${token}\r\nConnection: close\r\n\r\n`,
  94. "utf8",
  95. );
  96. const response = await wsl(
  97. [`${serverRoot}/bin/zcode`, "server", "proxy-stdio", "--server-root", serverRoot],
  98. { input: request },
  99. );
  100. const rawResponse = response.stdout.toString("utf8");
  101. assert(rawResponse.startsWith("HTTP/1.1 200"), "proxy response is HTTP 200");
  102. assert(rawResponse.includes('"serverId"'), "proxy response contains server-info JSON");
  103. console.log(
  104. `[verify-proxy-stdio-wsl] PASS target=${target} httpBytes=${response.stdout.length} binaryBytes=${binaryPayload.length}`,
  105. );
  106. } catch (error) {
  107. exitCode = 1;
  108. console.error("[verify-proxy-stdio-wsl] FAILED:", error instanceof Error ? error.message : error);
  109. } finally {
  110. await shell(
  111. `'${serverRoot}/bin/zcode' stop --server-root '${serverRoot}' --json >/dev/null 2>&1 || true; rm -rf '${bootstrapDir}' '${serverRoot}' '${archivePath}'`,
  112. { allowFailure: true },
  113. ).catch(() => undefined);
  114. }
  115. process.exit(exitCode);