nodeApiClientEndpoint.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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("X-Client-Language 跟随注入的界面语言,而不是进程 Intl locale", async () => {
  92. // 从 Dock 启动时进程无 LANG,Intl 回退 en-US;界面语言才是唯一数据源。
  93. const resolvedOptions = Intl.DateTimeFormat.prototype.resolvedOptions;
  94. const intlSpy = vi
  95. .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions")
  96. .mockImplementation(function (this: Intl.DateTimeFormat) {
  97. return { ...resolvedOptions.call(this), locale: "en-US" };
  98. });
  99. let uiLocale = "zh-CN";
  100. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  101. const client = createNodeApiClient({
  102. fetchImpl: fetchImpl as typeof fetch,
  103. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  104. resolveClientLanguage: () => uiLocale,
  105. });
  106. try {
  107. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/zcode-plan/billing/balance`);
  108. uiLocale = "en-US";
  109. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  110. uiLocale = "zh-CN";
  111. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/marketing/touch`, {
  112. headers: { "X-Client-Language": "en-US" },
  113. });
  114. } finally {
  115. intlSpy.mockRestore();
  116. }
  117. const languages = fetchImpl.mock.calls.map(([, init]) =>
  118. new Headers(init?.headers).get("X-Client-Language"),
  119. );
  120. // 切换语言后下一次请求立即生效;调用方显式传入的值仍然优先。
  121. expect(languages).toEqual(["zh-CN", "en-US", "en-US"]);
  122. });
  123. it("尚未收到界面语言时回退 Intl locale", async () => {
  124. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  125. const client = createNodeApiClient({
  126. fetchImpl: fetchImpl as typeof fetch,
  127. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  128. resolveClientLanguage: () => undefined,
  129. });
  130. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  131. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  132. expect(headers.get("X-Client-Language")).toBe(buildZCodeSourceHeaders()["X-Client-Language"]);
  133. });
  134. it("给当前 zcode endpoint 请求补既有 deviceMid header", async () => {
  135. const dataBaseDir = mkdtempSync(join(tmpdir(), "zcode-device-mid-"));
  136. tempDirs.push(dataBaseDir);
  137. setDataBaseDir(dataBaseDir);
  138. const configDir = join(dataBaseDir, ".zcode", "v2");
  139. mkdirSync(configDir, { recursive: true });
  140. writeFileSync(
  141. join(configDir, "telemetry-state.json"),
  142. JSON.stringify({ deviceMid: "device-mid-1" }),
  143. "utf-8",
  144. );
  145. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  146. const client = createNodeApiClient({
  147. fetchImpl: fetchImpl as typeof fetch,
  148. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  149. });
  150. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  151. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  152. expect(headers.get("X-Device-Mid")).toBe("device-mid-1");
  153. });
  154. it.each([
  155. { name: "state 文件缺失", content: null },
  156. { name: "state JSON 损坏", content: "{" },
  157. { name: "deviceMid 为空字符串", content: JSON.stringify({ deviceMid: "" }) },
  158. { name: "deviceMid 含不可打印字符", content: JSON.stringify({ deviceMid: "mid\n1" }) },
  159. ])("$name 时不注入 deviceMid header", async ({ content }) => {
  160. const dataBaseDir = mkdtempSync(join(tmpdir(), "zcode-device-mid-invalid-"));
  161. tempDirs.push(dataBaseDir);
  162. setDataBaseDir(dataBaseDir);
  163. const configDir = join(dataBaseDir, ".zcode", "v2");
  164. mkdirSync(configDir, { recursive: true });
  165. if (content !== null) {
  166. writeFileSync(join(configDir, "telemetry-state.json"), content, "utf-8");
  167. }
  168. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  169. const client = createNodeApiClient({
  170. fetchImpl: fetchImpl as typeof fetch,
  171. resolveZCodeEndpointOrigin: async () => "https://zcode.z.ai",
  172. });
  173. await client.request(`${DEFAULT_ZCODE_ENDPOINT_ORIGIN}/api/v1/client/configs`);
  174. expect(fetchImpl).toHaveBeenCalledTimes(1);
  175. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  176. expect(headers.get("X-Device-Mid")).toBeNull();
  177. });
  178. it("统一来源 headers 支持可控的客户端上下文字段", () => {
  179. expect(
  180. buildZCodeSourceHeaders({
  181. appVersion: "2.14.0",
  182. arch: "arm64",
  183. clientLanguage: "zh-CN",
  184. clientTimezone: "Asia/Shanghai",
  185. osVersion: "Darwin 25.0.0",
  186. platform: "darwin",
  187. releaseChannel: "production",
  188. }),
  189. ).toMatchObject({
  190. "X-Platform": "darwin-arm64",
  191. "X-Release-Channel": "production",
  192. "X-Client-Language": "zh-CN",
  193. "X-Client-Timezone": "Asia/Shanghai",
  194. "X-Os-Category": "macos",
  195. "X-Os-Version": "Darwin 25.0.0",
  196. "X-ZCode-App-Version": "2.14.0",
  197. });
  198. });
  199. });