off-peak-request-auth-refresh.test.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { describe, expect, it, vi } from "vitest";
  2. import { refreshOffPeakRequestAuth } from "../src/model/off-peak-request-auth.js";
  3. const scope = "a".repeat(64);
  4. const auth = {
  5. apiKey: "zcode-jwt",
  6. accountScope: scope,
  7. apiKeyId: "old-key-id",
  8. headers: {
  9. Authorization: "Bearer zcode-jwt",
  10. "X-Coding-Plan-Api-Key": "old-pat",
  11. "X-Off-Peak-Ticket-ID": "ticket",
  12. "bigmodel-project": "project",
  13. },
  14. };
  15. const input = { providerId: "account:bigmodel-off-peak", modelId: "glm", attempt: 1 };
  16. const accountAccess = { type: "zhipu-account", accountType: "bigmodel", mode: "off-peak" } as const;
  17. describe("闲时每次模型请求刷新 PAT", () => {
  18. it("每次都向 owner 解析,更新 PAT 且保持票据和本轮身份头", async () => {
  19. let generation = 0;
  20. const refresh = vi.fn(async () => ({
  21. headersApplied: true,
  22. requestAuth: {
  23. apiKey: `pat-${++generation}`,
  24. apiKeyId: `key-id-${generation}`,
  25. accountScope: scope,
  26. },
  27. }));
  28. for (const attempt of [1, 2]) {
  29. const result = await refreshOffPeakRequestAuth({
  30. auth,
  31. input: { ...input, attempt },
  32. accountAccess,
  33. refresh,
  34. });
  35. expect(result).toEqual({
  36. ...auth,
  37. apiKeyId: `key-id-${attempt}`,
  38. headers: { ...auth.headers, "X-Coding-Plan-Api-Key": `pat-${attempt}` },
  39. });
  40. }
  41. expect(refresh).toHaveBeenCalledTimes(2);
  42. expect(refresh.mock.calls[0]?.[0]).toMatchObject({
  43. expectedAccountScope: scope,
  44. accountAccess,
  45. });
  46. });
  47. it("owner 缺失或拒绝刷新不得沿用静态 PAT", async () => {
  48. await expect(refreshOffPeakRequestAuth({ auth, input, accountAccess })).rejects.toThrow();
  49. await expect(
  50. refreshOffPeakRequestAuth({
  51. auth,
  52. input,
  53. accountAccess,
  54. refresh: async () => {
  55. throw new Error("scope changed");
  56. },
  57. }),
  58. ).rejects.toThrow("scope changed");
  59. await expect(
  60. refreshOffPeakRequestAuth({
  61. auth,
  62. input,
  63. accountAccess,
  64. refresh: async () => ({
  65. headersApplied: true,
  66. requestAuth: { apiKey: "other-pat", accountScope: "b".repeat(64) },
  67. }),
  68. }),
  69. ).rejects.toThrow();
  70. });
  71. it("保留无真实 Token 的 mock 静态注入", async () => {
  72. const refresh = vi.fn();
  73. const mock = { apiKey: "mock", headers: { "X-Coding-Plan-Api-Key": "mock" } };
  74. expect(await refreshOffPeakRequestAuth({ auth: mock, input, accountAccess, refresh })).toBe(
  75. mock,
  76. );
  77. expect(refresh).not.toHaveBeenCalled();
  78. });
  79. });
  80. it("真实 runner 同一个闲时 Model 连续请求也向 owner 刷新,不只首次派发刷新", async () => {
  81. const { runWithModelInvocationContext } = await import("@zcode/contracts");
  82. const { TestAiSdkModelAdapter, TestProviderConfigFixture } =
  83. await import("./test-provider-config.js");
  84. const seen: string[] = [];
  85. const adapter = new TestAiSdkModelAdapter({
  86. registry: new TestProviderConfigFixture({
  87. providers: {
  88. idle: {
  89. kind: "anthropic",
  90. accountMode: "off-peak",
  91. baseURL: "https://zcode.z.ai/api/v1/off-peak/anthropic",
  92. },
  93. },
  94. }),
  95. runtime: {
  96. async generateText(options) {
  97. seen.push(new Headers(options.headers).get("X-Coding-Plan-Api-Key")!);
  98. expect(new Headers(options.headers).get("X-Off-Peak-Ticket-ID")).toBe("ticket");
  99. return {
  100. text: "ok",
  101. finishReason: "stop",
  102. usage: { inputTokens: 1, outputTokens: 1 },
  103. totalUsage: { inputTokens: 1, outputTokens: 1 },
  104. } as never;
  105. },
  106. streamText() {
  107. throw Error("unused");
  108. },
  109. },
  110. });
  111. const model = adapter.createModel({
  112. providerId: "idle",
  113. modelId: "glm",
  114. accountMode: "off-peak",
  115. requestDependencies: { requestAuth: { source: { resolve: async () => auth } } },
  116. });
  117. let count = 0;
  118. const refresh = vi.fn(async (request) => {
  119. expect(request.expectedAccountScope).toBe(scope);
  120. expect(request.accountAccess.mode).toBe("off-peak");
  121. return {
  122. headersApplied: true,
  123. requestAuth: { apiKey: `fresh-${++count}`, accountScope: scope },
  124. };
  125. });
  126. for (const _ of [1, 2]) {
  127. await runWithModelInvocationContext({ refreshRuntimeHeadersBeforeAttempt: refresh }, () =>
  128. model.generateText({ messages: [{ role: "user", content: "continue" }] }),
  129. );
  130. }
  131. expect(seen).toEqual(["fresh-1", "fresh-2"]);
  132. });