nodeApiClientEndpoint.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { DEFAULT_ZCODE_ENDPOINT_ORIGIN } from "@zcode/shared";
  6. import { setDataBaseDir } from "../src/paths.js";
  7. import { createNodeApiClient } from "../src/providers/api/nodeApiClient.js";
  8. import { buildZCodeSourceHeaders, ZCODE_SOURCE_HEADERS } from "../src/providers/sourceHeaders.js";
  9. describe("NodeApiClient endpoint rewriting", () => {
  10. const tempDirs: string[] = [];
  11. afterEach(() => {
  12. setDataBaseDir(null);
  13. for (const dir of tempDirs.splice(0)) {
  14. rmSync(dir, { recursive: true, force: true });
  15. }
  16. });
  17. it("rewrites only the configured zcode endpoint origin", async () => {
  18. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  19. const client = createNodeApiClient({
  20. fetchImpl: fetchImpl as typeof fetch,
  21. resolveZCodeEndpointOrigin: async () => "http://localhost:3030",
  22. });
  23. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/event/report?x=1`);
  24. await client.request("https://example.com/static/config.json");
  25. await client.request("https://feedback.example.invalid/api/v1/tickets");
  26. await client.request("https://api.z.ai/v1/models");
  27. expect(fetchImpl.mock.calls.map(([input]) => String(input))).toEqual([
  28. "http://localhost:3030/api/v1/event/report?x=1",
  29. "https://example.com/static/config.json",
  30. "https://feedback.example.invalid/api/v1/tickets",
  31. "https://api.z.ai/v1/models",
  32. ]);
  33. });
  34. it("只给当前 zcode endpoint 请求统一补来源 headers", async () => {
  35. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  36. const client = createNodeApiClient({
  37. fetchImpl: fetchImpl as typeof fetch,
  38. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  39. });
  40. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  41. await client.request("https://api.z.ai/v1/models");
  42. const zcodeHeaders = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  43. expect(zcodeHeaders.get("User-Agent")).toMatch(/^ZCode\//);
  44. expect(zcodeHeaders.get("X-Title")).toBe(ZCODE_SOURCE_HEADERS["X-Title"]);
  45. expect(zcodeHeaders.get("X-OpenRouter-Title")).toBeNull();
  46. expect(zcodeHeaders.get("X-OpenRouter-Categories")).toBeNull();
  47. expect(zcodeHeaders.get("HTTP-Referer")).toBe("https://zcode.z.ai");
  48. expect(zcodeHeaders.get("X-App-Version")).toBeNull();
  49. expect(zcodeHeaders.get("X-ZCode-App-Version")).toBeTruthy();
  50. expect(zcodeHeaders.get("X-Platform")).toBe(`${process.platform}-${process.arch}`);
  51. expect(zcodeHeaders.get("X-Release-Channel")).toBeTruthy();
  52. expect(zcodeHeaders.get("X-Client-Language")).toBeTruthy();
  53. expect(zcodeHeaders.get("X-Client-Timezone")).toBeTruthy();
  54. expect(zcodeHeaders.get("X-Os-Category")).toBeTruthy();
  55. expect(zcodeHeaders.get("X-Os-Version")).toBeTruthy();
  56. expect(zcodeHeaders.get("x-request-id")).toMatch(
  57. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
  58. );
  59. const externalHeaders = new Headers(fetchImpl.mock.calls[1]?.[1]?.headers);
  60. expect(externalHeaders.get("x-request-id")).toMatch(
  61. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
  62. );
  63. expect(externalHeaders.get("User-Agent")).toBeNull();
  64. });
  65. it("保留调用方显式传入的 zcode endpoint headers", async () => {
  66. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  67. const client = createNodeApiClient({
  68. fetchImpl: fetchImpl as typeof fetch,
  69. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  70. });
  71. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/oauth/token`, {
  72. headers: {
  73. "User-Agent": "CustomAgent/1.0",
  74. "X-Device-Mid": "caller-device-mid",
  75. "X-Title": "Custom Title",
  76. Authorization: "Bearer token",
  77. },
  78. });
  79. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  80. expect(headers.get("User-Agent")).toBe("CustomAgent/1.0");
  81. expect(headers.get("X-Title")).toBe("Custom Title");
  82. expect(headers.get("X-OpenRouter-Title")).toBeNull();
  83. expect(headers.get("X-OpenRouter-Categories")).toBeNull();
  84. expect(headers.get("Authorization")).toBe("Bearer token");
  85. expect(headers.get("X-Device-Mid")).toBe("caller-device-mid");
  86. expect(headers.get("HTTP-Referer")).toBe("https://zcode.z.ai");
  87. expect(headers.get("x-request-id")).toMatch(
  88. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
  89. );
  90. });
  91. it("给当前 zcode endpoint 请求补既有 deviceMid header", async () => {
  92. const dataBaseDir = mkdtempSync(join(tmpdir(), "zcode-device-mid-"));
  93. tempDirs.push(dataBaseDir);
  94. setDataBaseDir(dataBaseDir);
  95. const configDir = join(dataBaseDir, ".zcode", "v2");
  96. mkdirSync(configDir, { recursive: true });
  97. writeFileSync(
  98. join(configDir, "telemetry-state.json"),
  99. JSON.stringify({ deviceMid: "device-mid-1" }),
  100. "utf-8",
  101. );
  102. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  103. const client = createNodeApiClient({
  104. fetchImpl: fetchImpl as typeof fetch,
  105. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  106. });
  107. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  108. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  109. expect(headers.get("X-Device-Mid")).toBe("device-mid-1");
  110. });
  111. it.each([
  112. { name: "state 文件缺失", content: null },
  113. { name: "state JSON 损坏", content: "{" },
  114. { name: "deviceMid 为空字符串", content: JSON.stringify({ deviceMid: "" }) },
  115. { name: "deviceMid 含不可打印字符", content: JSON.stringify({ deviceMid: "mid\n1" }) },
  116. ])("$name 时不注入 deviceMid header", async ({ content }) => {
  117. const dataBaseDir = mkdtempSync(join(tmpdir(), "zcode-device-mid-invalid-"));
  118. tempDirs.push(dataBaseDir);
  119. setDataBaseDir(dataBaseDir);
  120. const configDir = join(dataBaseDir, ".zcode", "v2");
  121. mkdirSync(configDir, { recursive: true });
  122. if (content !== null) {
  123. writeFileSync(join(configDir, "telemetry-state.json"), content, "utf-8");
  124. }
  125. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  126. const client = createNodeApiClient({
  127. fetchImpl: fetchImpl as typeof fetch,
  128. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  129. });
  130. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  131. expect(fetchImpl).toHaveBeenCalledTimes(1);
  132. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  133. expect(headers.get("X-Device-Mid")).toBeNull();
  134. });
  135. it("统一来源 headers 支持可控的客户端上下文字段", () => {
  136. expect(
  137. buildZCodeSourceHeaders({
  138. appVersion: "2.14.0",
  139. arch: "arm64",
  140. clientLanguage: "zh-CN",
  141. clientTimezone: "Asia/Shanghai",
  142. osVersion: "Darwin 25.0.0",
  143. platform: "darwin",
  144. releaseChannel: "production",
  145. }),
  146. ).toMatchObject({
  147. "X-Platform": "darwin-arm64",
  148. "X-Release-Channel": "production",
  149. "X-Client-Language": "zh-CN",
  150. "X-Client-Timezone": "Asia/Shanghai",
  151. "X-Os-Category": "macos",
  152. "X-Os-Version": "Darwin 25.0.0",
  153. "X-ZCode-App-Version": "2.14.0",
  154. });
  155. });
  156. });