telemetryRequestHeaders.test.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, expect, it, vi } from "vitest";
  5. import { createTelemetryCore } from "../src/telemetry/telemetryCore.js";
  6. import { createTelemetryAuthorizationLoader } from "../src/node.js";
  7. const homes: string[] = [];
  8. afterEach(async () => {
  9. await Promise.all(homes.splice(0).map((home) => rm(home, { recursive: true, force: true })));
  10. });
  11. const context = {
  12. clientLanguage: "zh-CN",
  13. clientTimezone: "Asia/Shanghai",
  14. screenResolution: "100x100",
  15. };
  16. it("adds every public header and re-reads authorization on retry and logout", async () => {
  17. const homeDir = await mkdtemp(join(tmpdir(), "telemetry-headers-"));
  18. homes.push(homeDir);
  19. let token: string | null = "Bearer first";
  20. const loadAuthorization = vi.fn(async () => token);
  21. const fetchImpl = vi
  22. .fn<typeof fetch>()
  23. .mockResolvedValueOnce(new Response(null, { status: 503 }))
  24. .mockResolvedValue(new Response(null, { status: 204 }));
  25. const core = createTelemetryCore({
  26. homeDir,
  27. fetchImpl,
  28. loadAuthorization,
  29. loadUserId: async () => "user-1",
  30. appVersion: "1.2.3",
  31. platform: "darwin",
  32. arch: "arm64",
  33. osVersion: "24.0",
  34. releaseChannel: "test",
  35. randomUUID: () => "device-1",
  36. resolveZCodeEndpointOrigin: () => "https://zcode.z.ai",
  37. sleep: async () => {
  38. token = "Bearer second";
  39. },
  40. });
  41. await core.reportAppLaunch(context);
  42. expect(fetchImpl.mock.calls[0]?.[1]?.redirect).toBe("error");
  43. expect(fetchImpl.mock.calls[0]?.[1]?.headers).toEqual({
  44. "Content-Type": "application/json",
  45. "User-Agent": "ZCode/1.2.3",
  46. "HTTP-Referer": "https://zcode.z.ai",
  47. "X-Title": "Z Code@electron",
  48. "X-ZCode-App-Version": "1.2.3",
  49. "X-Platform": "darwin-arm64",
  50. "X-Release-Channel": "test",
  51. "X-Client-Language": "zh-CN",
  52. "X-Client-Timezone": "Asia/Shanghai",
  53. "X-Os-Category": "macos",
  54. "X-Os-Version": "24.0",
  55. "X-Device-Mid": "device-1",
  56. Authorization: "Bearer first",
  57. });
  58. expect(new Headers(fetchImpl.mock.calls[1]?.[1]?.headers).get("Authorization")).toBe(
  59. "Bearer second",
  60. );
  61. expect(fetchImpl.mock.calls[1]?.[1]?.body).toBe(fetchImpl.mock.calls[0]?.[1]?.body);
  62. token = null;
  63. await core.reportAppLaunch(context);
  64. expect(new Headers(fetchImpl.mock.calls[2]?.[1]?.headers).has("Authorization")).toBe(false);
  65. expect(loadAuthorization).toHaveBeenCalledWith("user-1");
  66. loadAuthorization.mockRejectedValueOnce(new Error("secret credential error"));
  67. await core.reportAppLaunch(context);
  68. expect(new Headers(fetchImpl.mock.calls[3]?.[1]?.headers).has("Authorization")).toBe(false);
  69. });
  70. it.each(["zai", "bigmodel"])(
  71. "only reads JWT for active %s, never OAuth/API keys",
  72. async (provider) => {
  73. const values: Record<string, string> = {
  74. "oauth:active_provider": provider,
  75. [`oauth:${provider}:user_info`]: '{"id":"u1"}',
  76. zcodejwttoken: "jwt-1",
  77. };
  78. const load = vi.fn(async (key: string) => values[key] ?? null);
  79. const authorization = createTelemetryAuthorizationLoader({ load });
  80. expect(await authorization("u1")).toBe("Bearer jwt-1");
  81. values.zcodejwttoken = "jwt-2";
  82. expect(await authorization("u1")).toBe("Bearer jwt-2");
  83. expect(await authorization("other-user")).toBeNull();
  84. delete values["oauth:active_provider"];
  85. expect(await authorization("u1")).toBeNull();
  86. expect(await authorization("")).toBeNull();
  87. expect(
  88. load.mock.calls.every(([key]) => !key.includes("access_token") && !key.includes("api_key")),
  89. ).toBe(true);
  90. },
  91. );
  92. it("drops JWT when the account changes during the read, and fails closed on errors", async () => {
  93. let provider = "bigmodel";
  94. const authorization = createTelemetryAuthorizationLoader({
  95. load: async (key) => {
  96. if (key === "oauth:active_provider") return provider;
  97. if (key.endsWith(":user_info")) return '{"user_id":"u1"}';
  98. provider = "zai";
  99. return "old-jwt";
  100. },
  101. });
  102. expect(await authorization("u1")).toBeNull();
  103. const failed = createTelemetryAuthorizationLoader({
  104. load: async () => {
  105. throw new Error("secret");
  106. },
  107. });
  108. expect(await failed("u1")).toBeNull();
  109. });
  110. it.each([null, "", " ", "bad\r\nheader"])("omits absent or unsafe JWT: %j", async (token) => {
  111. const authorization = createTelemetryAuthorizationLoader({
  112. load: async (key) => {
  113. if (key === "oauth:active_provider") return "zai";
  114. if (key.endsWith(":user_info")) return '{"id":"u1"}';
  115. return token;
  116. },
  117. });
  118. expect(await authorization("u1")).toBeNull();
  119. });