auth.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import { fork } from "node:child_process";
  2. import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import type { HttpClientPort, HttpClientRequest, HttpClientResponse } from "@zcode/contracts";
  7. import {
  8. CliOAuthError,
  9. SHARED_ZCODE_CREDENTIAL_KEYS,
  10. createBigmodelOAuthClient,
  11. createCliOAuthClient,
  12. createCodingPlanApiKeyResolver,
  13. createSharedZCodeCredentialStore,
  14. loadSharedZCodeCredentialSync,
  15. } from "../src/auth/index.js";
  16. const TEST_ENV = {
  17. ZCODE_CREDENTIAL_SECRET: "test-secret",
  18. };
  19. afterEach(() => {
  20. vi.unstubAllEnvs();
  21. });
  22. describe("shared ZCode credentials", () => {
  23. it("stores ZAI login credentials with z-code compatible encrypted keys", async () => {
  24. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-"));
  25. try {
  26. const store = createSharedZCodeCredentialStore({
  27. baseDir: dir,
  28. env: TEST_ENV,
  29. });
  30. await store.saveZaiLoginCredentials({
  31. accessToken: "zai-access-token",
  32. jwtToken: "zcode-jwt-token",
  33. user: {
  34. email: "alice@example.com",
  35. name: "Alice",
  36. user_id: "u_1",
  37. },
  38. });
  39. const raw = JSON.parse(await readFile(store.filePath, "utf-8")) as Record<string, string>;
  40. expect(store.filePath).toBe(join(dir, ".zcode", "v2", "credentials.json"));
  41. expect(raw[SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]?.startsWith("enc:v1:")).toBe(true);
  42. expect(await store.load(SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider)).toBe("zai");
  43. expect(await store.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBe(
  44. "zai-access-token",
  45. );
  46. expect(await store.load(SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken)).toBe("zcode-jwt-token");
  47. expect(
  48. loadSharedZCodeCredentialSync(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken, {
  49. baseDir: dir,
  50. env: TEST_ENV,
  51. }),
  52. ).toBe("zai-access-token");
  53. } finally {
  54. await rm(dir, { force: true, recursive: true });
  55. }
  56. });
  57. it("reads legacy plaintext credential values", async () => {
  58. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-"));
  59. const credentialsDir = join(dir, ".zcode", "v2");
  60. const credentialsPath = join(credentialsDir, "credentials.json");
  61. try {
  62. await mkdir(credentialsDir, { recursive: true });
  63. await writeFile(
  64. credentialsPath,
  65. JSON.stringify({
  66. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: "legacy-token",
  67. }),
  68. );
  69. const store = createSharedZCodeCredentialStore({
  70. baseDir: dir,
  71. env: TEST_ENV,
  72. });
  73. expect(await store.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBe("legacy-token");
  74. } finally {
  75. await rm(dir, { force: true, recursive: true });
  76. }
  77. });
  78. it("preserves every key across concurrent read-modify-write mutations", async () => {
  79. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-concurrent-"));
  80. const store = createSharedZCodeCredentialStore({
  81. baseDir: dir,
  82. env: TEST_ENV,
  83. });
  84. const entries = Array.from({ length: 40 }, (_, index) => [`key-${index}`, `value-${index}`]);
  85. try {
  86. await Promise.all(entries.map(([key, value]) => store.save(key!, value!)));
  87. await Promise.all(
  88. entries.map(async ([key, value]) => {
  89. await expect(store.load(key!)).resolves.toBe(value);
  90. }),
  91. );
  92. } finally {
  93. await rm(dir, { force: true, recursive: true });
  94. }
  95. });
  96. it("deletes a credential only when its expected plaintext value is still current", async () => {
  97. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-compare-delete-"));
  98. const store = createSharedZCodeCredentialStore({
  99. baseDir: dir,
  100. env: TEST_ENV,
  101. });
  102. try {
  103. await store.save("oauth:snapshot", "snapshot-a");
  104. await expect(store.deleteIfValue("oauth:snapshot", "stale-snapshot")).resolves.toBe(false);
  105. await expect(store.load("oauth:snapshot")).resolves.toBe("snapshot-a");
  106. await expect(store.deleteIfValue("oauth:snapshot", "snapshot-a")).resolves.toBe(true);
  107. await expect(store.load("oauth:snapshot")).resolves.toBeNull();
  108. } finally {
  109. await rm(dir, { force: true, recursive: true });
  110. }
  111. });
  112. it("publishes a replacement credential and removes legacy keys in one mutation", async () => {
  113. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-replace-"));
  114. const store = createSharedZCodeCredentialStore({
  115. baseDir: dir,
  116. env: TEST_ENV,
  117. });
  118. try {
  119. await store.save("oauth:legacy-client", "client-a");
  120. await store.save("oauth:legacy-tokens", "tokens-a");
  121. await store.saveReplacing("oauth:canonical", "pair-a", [
  122. "oauth:legacy-client",
  123. "oauth:legacy-tokens",
  124. ]);
  125. await expect(store.load("oauth:canonical")).resolves.toBe("pair-a");
  126. await expect(store.load("oauth:legacy-client")).resolves.toBeNull();
  127. await expect(store.load("oauth:legacy-tokens")).resolves.toBeNull();
  128. } finally {
  129. await rm(dir, { force: true, recursive: true });
  130. }
  131. });
  132. it("preserves every key across independent Node processes", async () => {
  133. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-processes-"));
  134. const credentialsPath = join(dir, "credentials.json");
  135. const processCount = 4;
  136. const keysPerProcess = 8;
  137. try {
  138. await runConcurrentCredentialWorkers(credentialsPath, processCount, keysPerProcess);
  139. const store = createSharedZCodeCredentialStore({
  140. env: TEST_ENV,
  141. filePath: credentialsPath,
  142. });
  143. await Promise.all(
  144. Array.from({ length: processCount }, (_, processIndex) =>
  145. Array.from({ length: keysPerProcess }, async (_, keyIndex) => {
  146. await expect(store.load(`worker-${processIndex}:key-${keyIndex}`)).resolves.toBe(
  147. `value-${processIndex}-${keyIndex}`,
  148. );
  149. }),
  150. ).flat(),
  151. );
  152. } finally {
  153. await rm(dir, { force: true, recursive: true });
  154. }
  155. }, 15_000);
  156. it("backs up corrupt JSON and refuses to overwrite it", async () => {
  157. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-corrupt-"));
  158. const credentialsPath = join(dir, "credentials.json");
  159. const store = createSharedZCodeCredentialStore({
  160. env: TEST_ENV,
  161. filePath: credentialsPath,
  162. });
  163. try {
  164. await writeFile(credentialsPath, "{not-json", {
  165. encoding: "utf-8",
  166. mode: 0o644,
  167. });
  168. await Promise.all(
  169. Array.from({ length: 8 }, () =>
  170. expect(store.load("safe-key")).rejects.toThrow("Shared ZCode credentials are corrupt"),
  171. ),
  172. );
  173. await expect(store.save("safe-key", "safe-value")).rejects.toThrow(
  174. "Shared ZCode credentials are corrupt",
  175. );
  176. await expect(readFile(credentialsPath, "utf-8")).resolves.toBe("{not-json");
  177. const backups = (await readdir(dir)).filter((file) =>
  178. /^credentials\.json\.corrupt-.*\.bak$/.test(file),
  179. );
  180. expect(backups).toHaveLength(1);
  181. await expect(readFile(join(dir, backups[0]!), "utf-8")).resolves.toBe("{not-json");
  182. if (process.platform !== "win32") {
  183. expect((await stat(join(dir, backups[0]!))).mode & 0o777).toBe(0o600);
  184. }
  185. } finally {
  186. await rm(dir, { force: true, recursive: true });
  187. }
  188. });
  189. it("deduplicates corrupt credential backups across independent Node processes", async () => {
  190. const dir = await mkdtemp(join(tmpdir(), "zcode-auth-corrupt-processes-"));
  191. const credentialsPath = join(dir, "credentials.json");
  192. try {
  193. await writeFile(credentialsPath, "{not-json", "utf-8");
  194. await runConcurrentCredentialWorkers(credentialsPath, 6, 0, "read-corrupt");
  195. const backups = (await readdir(dir)).filter((file) =>
  196. /^credentials\.json\.corrupt-.*\.bak$/.test(file),
  197. );
  198. expect(backups).toHaveLength(1);
  199. } finally {
  200. await rm(dir, { force: true, recursive: true });
  201. }
  202. });
  203. });
  204. async function runConcurrentCredentialWorkers(
  205. filePath: string,
  206. processCount: number,
  207. keysPerProcess: number,
  208. operation: "save" | "read-corrupt" = "save",
  209. ): Promise<void> {
  210. const workerUrl = new URL("./fixtures/shared-credentials-concurrent-process.ts", import.meta.url);
  211. const children = Array.from({ length: processCount }, (_, processIndex) =>
  212. fork(workerUrl, {
  213. env: { ...process.env, NODE_NO_WARNINGS: "1" },
  214. execArgv: ["--import", "tsx"],
  215. stdio: ["ignore", "ignore", "inherit", "ipc"],
  216. }),
  217. );
  218. try {
  219. await Promise.all(
  220. children.map(
  221. (child) =>
  222. new Promise<void>((resolve, reject) => {
  223. child.once("error", reject);
  224. child.once("exit", (code) =>
  225. reject(new Error(`credential child exited early: ${code}`)),
  226. );
  227. child.on("message", (message: { type?: unknown }) => {
  228. if (message.type === "ready") resolve();
  229. });
  230. }),
  231. ),
  232. );
  233. const results = children.map(
  234. (child) =>
  235. new Promise<void>((resolve, reject) => {
  236. child.once("error", reject);
  237. child.once("exit", (code) => {
  238. if (code !== 0) reject(new Error(`credential child exited with code ${code}`));
  239. });
  240. child.on("message", (message: { error?: unknown; type?: unknown }) => {
  241. if (message.type === "done") resolve();
  242. if (message.type === "error") reject(new Error(String(message.error)));
  243. });
  244. }),
  245. );
  246. children.forEach((child, processIndex) => {
  247. child.send({
  248. filePath,
  249. keysPerProcess,
  250. operation,
  251. processIndex,
  252. type: "start",
  253. });
  254. });
  255. await Promise.all(results);
  256. } finally {
  257. for (const child of children) {
  258. if (child.connected) child.disconnect();
  259. child.kill();
  260. }
  261. }
  262. }
  263. // CLI 浏览器登录的轮询客户端按 providerId 泛化(zai/bigmodel),ready 数据统一为 accessToken。
  264. describe("CLI OAuth client", () => {
  265. it("initializes and polls the backend device flow", async () => {
  266. const httpClient = new FakeHttpClient([
  267. jsonResponse({
  268. code: 0,
  269. msg: "",
  270. data: {
  271. flow_id: "flow-1",
  272. poll_token: "poll-token",
  273. authorize_url: "https://chat.z.ai/oauth/authorize?state=state",
  274. expires_at: 1735000000,
  275. poll_interval_sec: 2,
  276. },
  277. }),
  278. jsonResponse({
  279. code: 0,
  280. msg: "",
  281. data: {
  282. status: "ready",
  283. token: "jwt-token",
  284. user: {
  285. user_id: "u_1",
  286. email: "alice@example.com",
  287. name: "Alice",
  288. },
  289. zai: {
  290. access_token: "zai-access-token",
  291. },
  292. },
  293. }),
  294. ]);
  295. const client = createCliOAuthClient({
  296. baseUrl: "https://zcode.example/api/v1/",
  297. httpClient,
  298. providerId: "zai",
  299. });
  300. const init = await client.init({ pollToken: "poll-token" });
  301. const poll = await client.poll({
  302. flowId: init.flow_id,
  303. pollToken: "poll-token",
  304. });
  305. expect(httpClient.requests[0]).toMatchObject({
  306. method: "POST",
  307. url: "https://zcode.example/api/v1/oauth/cli/init",
  308. headers: {
  309. Authorization: "Bearer poll-token",
  310. "Content-Type": "application/json",
  311. },
  312. });
  313. expect(new TextDecoder().decode(httpClient.requests[0]?.body)).toBe('{"provider":"zai"}');
  314. expect(httpClient.requests[1]).toMatchObject({
  315. method: "GET",
  316. url: "https://zcode.example/api/v1/oauth/cli/poll/flow-1",
  317. headers: {
  318. Authorization: "Bearer poll-token",
  319. },
  320. });
  321. expect(poll).toMatchObject({
  322. status: "ready",
  323. token: "jwt-token",
  324. providerId: "zai",
  325. accessToken: "zai-access-token",
  326. });
  327. });
  328. it("surfaces backend business errors", async () => {
  329. const client = createCliOAuthClient({
  330. httpClient: new FakeHttpClient([
  331. jsonResponse({
  332. code: 3004,
  333. msg: "invalid_flow",
  334. data: {},
  335. }),
  336. ]),
  337. providerId: "zai",
  338. });
  339. await expect(client.init({ pollToken: "poll-token" })).rejects.toMatchObject({
  340. businessCode: 3004,
  341. message: "invalid_flow",
  342. name: "CliOAuthError",
  343. } satisfies Partial<CliOAuthError>);
  344. });
  345. });
  346. describe("Coding Plan API key resolver", () => {
  347. it.each(["bigmodel", "zai"] as const)(
  348. "creates %s keys with Coding Plan usageScene",
  349. async (family) => {
  350. const httpClient = new FakeHttpClient([
  351. ...(family === "zai"
  352. ? [jsonResponse({ code: 200, data: { access_token: "biz-token" } })]
  353. : []),
  354. customerInfoResponse(),
  355. jsonResponse({ code: 200, data: [] }),
  356. jsonResponse({
  357. code: 200,
  358. data: { apiKey: "key", name: "zcode-api-key" },
  359. }),
  360. jsonResponse({
  361. code: 200,
  362. data: {
  363. accessToken: "project-token",
  364. tokenType: "Bearer",
  365. expiresIn: 600,
  366. expiresAt: Math.floor(Date.now() / 1000) + 600,
  367. },
  368. }),
  369. ]);
  370. await expect(
  371. createCodingPlanApiKeyResolver({ httpClient }).resolve({
  372. accessToken: "login-token",
  373. family,
  374. }),
  375. ).resolves.toBe("project-token");
  376. expect(httpClient.requests.some((request) => request.url.includes("/copy/"))).toBe(false);
  377. const issuance = httpClient.requests.at(-1)!;
  378. expect(issuance.url).toMatch(/\/api_keys\/key\/access_tokens$/);
  379. expect(issuance.method).toBe("POST");
  380. expect(JSON.parse(new TextDecoder().decode(issuance.body))).toMatchObject({
  381. clientType: "zcode",
  382. });
  383. const create = httpClient.requests.find(
  384. (request) => request.method === "POST" && request.url.endsWith("/api_keys"),
  385. );
  386. expect(create).toBeDefined();
  387. expect(JSON.parse(new TextDecoder().decode(create!.body))).toEqual({
  388. name: "zcode-api-key",
  389. usageScene: 1,
  390. });
  391. },
  392. );
  393. it("keeps the CLI default project even when it is a team project", async () => {
  394. const httpClient = new FakeHttpClient([
  395. jsonResponse({
  396. code: 200,
  397. data: {
  398. organizations: [
  399. {
  400. organizationId: "org",
  401. organizationName: "默认机构",
  402. projects: [
  403. { projectId: "personal", projectType: 1 },
  404. { projectId: "team", projectName: "默认项目", projectType: 2 },
  405. ],
  406. },
  407. ],
  408. },
  409. }),
  410. jsonResponse({ code: 200, data: [{ apiKey: "key", name: "zcode-api-key" }] }),
  411. jsonResponse({
  412. code: 200,
  413. data: {
  414. accessToken: "project-token",
  415. tokenType: "Bearer",
  416. expiresIn: 600,
  417. expiresAt: Date.now() / 1000 + 600,
  418. },
  419. }),
  420. ]);
  421. await expect(
  422. createCodingPlanApiKeyResolver({ httpClient }).resolve({
  423. accessToken: "login",
  424. family: "bigmodel",
  425. }),
  426. ).resolves.toBe("project-token");
  427. expect(httpClient.requests[1]?.url).toContain("/projects/team/api_keys");
  428. expect(httpClient.requests.at(-1)?.headers).toMatchObject({ authorization: "Bearer login" });
  429. });
  430. it("exchanges a ZAI OAuth access token for a short-lived project token", async () => {
  431. const httpClient = new FakeHttpClient([
  432. jsonResponse({
  433. code: 0,
  434. data: {
  435. access_token: "zai-biz-token",
  436. },
  437. }),
  438. customerInfoResponse(),
  439. jsonResponse({
  440. code: 200,
  441. data: [],
  442. }),
  443. jsonResponse({
  444. code: 200,
  445. data: {
  446. apiKey: "zai-api-key",
  447. name: "zcode-api-key",
  448. },
  449. }),
  450. jsonResponse({
  451. code: 200,
  452. data: {
  453. accessToken: "project-token",
  454. tokenType: "Bearer",
  455. expiresIn: 600,
  456. expiresAt: Math.floor(Date.now() / 1000) + 600,
  457. },
  458. }),
  459. ]);
  460. const resolver = createCodingPlanApiKeyResolver({ httpClient });
  461. await expect(
  462. resolver.resolve({
  463. accessToken: "zai-oauth-token",
  464. family: "zai",
  465. }),
  466. ).resolves.toBe("project-token");
  467. expect(httpClient.requests[0]?.url).toBe("https://api.z.ai/api/auth/z/login");
  468. expect(httpClient.requests[1]?.headers).toMatchObject({
  469. authorization: "Bearer zai-biz-token",
  470. });
  471. });
  472. it("resolves a BigModel OAuth access token through project access token issuance", async () => {
  473. const httpClient = new FakeHttpClient([
  474. customerInfoResponse(),
  475. jsonResponse({
  476. code: 200,
  477. data: [
  478. {
  479. apiKey: "bigmodel-api-key",
  480. name: "zcode-api-key",
  481. },
  482. ],
  483. }),
  484. jsonResponse({
  485. code: 200,
  486. data: {
  487. accessToken: "project-token",
  488. tokenType: "Bearer",
  489. expiresIn: 600,
  490. expiresAt: Math.floor(Date.now() / 1000) + 600,
  491. },
  492. }),
  493. ]);
  494. const resolver = createCodingPlanApiKeyResolver({ httpClient });
  495. await expect(
  496. resolver.resolve({
  497. accessToken: "bigmodel-oauth-token",
  498. family: "bigmodel",
  499. }),
  500. ).resolves.toBe("project-token");
  501. expect(httpClient.requests[0]?.url).toBe(
  502. "https://bigmodel.cn/api/biz/customer/getCustomerInfo",
  503. );
  504. expect(httpClient.requests[0]?.headers).toMatchObject({
  505. authorization: "bigmodel-oauth-token",
  506. });
  507. });
  508. it("uses bigmodel.cn for BigModel API key resolution when ZCODE_ENV=test", async () => {
  509. vi.stubEnv("ZCODE_ENV", "test");
  510. const httpClient = new FakeHttpClient([
  511. customerInfoResponse(),
  512. jsonResponse({
  513. code: 200,
  514. data: [
  515. {
  516. apiKey: "bigmodel-api-key",
  517. name: "zcode-api-key",
  518. },
  519. ],
  520. }),
  521. jsonResponse({
  522. code: 200,
  523. data: {
  524. accessToken: "project-token",
  525. tokenType: "Bearer",
  526. expiresIn: 600,
  527. expiresAt: Math.floor(Date.now() / 1000) + 600,
  528. },
  529. }),
  530. ]);
  531. const resolver = createCodingPlanApiKeyResolver({ httpClient });
  532. await resolver.resolve({
  533. accessToken: "bigmodel-oauth-token",
  534. family: "bigmodel",
  535. });
  536. expect(httpClient.requests[0]?.url).toBe(
  537. "https://bigmodel.cn/api/biz/customer/getCustomerInfo",
  538. );
  539. });
  540. });
  541. describe("BigModel OAuth client", () => {
  542. it("builds localhost authorize URLs and exchanges auth codes", async () => {
  543. const httpClient = new FakeHttpClient([
  544. jsonResponse({
  545. data: {
  546. accessToken: "bigmodel-access-token",
  547. refreshToken: "bigmodel-refresh-token",
  548. },
  549. }),
  550. ]);
  551. const client = createBigmodelOAuthClient({
  552. appSecret: "test-secret",
  553. httpClient,
  554. });
  555. const authorizeUrl = client.buildAuthorizeUrl({
  556. redirectUri: "http://127.0.0.1:1234/oauth/callback/bigmodel",
  557. state: "state-1",
  558. });
  559. const tokenSet = await client.exchangeCode({ code: "auth-code" });
  560. expect(authorizeUrl).toContain("https://bigmodel.cn/login?");
  561. expect(authorizeUrl).toContain("appId=zcode");
  562. expect(authorizeUrl).toContain("state=state-1");
  563. expect(tokenSet).toEqual({
  564. accessToken: "bigmodel-access-token",
  565. refreshToken: "bigmodel-refresh-token",
  566. });
  567. expect(new TextDecoder().decode(httpClient.requests[0]?.body)).toContain(
  568. '"authCode":"auth-code"',
  569. );
  570. });
  571. it("uses bigmodel.cn for authorize URL when ZCODE_ENV=test", () => {
  572. vi.stubEnv("ZCODE_ENV", "test");
  573. const httpClient = new FakeHttpClient([]);
  574. const client = createBigmodelOAuthClient({
  575. appSecret: "test-secret",
  576. httpClient,
  577. });
  578. const authorizeUrl = client.buildAuthorizeUrl({
  579. redirectUri: "http://127.0.0.1:1234/oauth/callback/bigmodel",
  580. state: "state-1",
  581. });
  582. expect(authorizeUrl).toContain("https://bigmodel.cn/login?");
  583. });
  584. it("uses bigmodel.cn for token exchange when ZCODE_ENV=test", async () => {
  585. vi.stubEnv("ZCODE_ENV", "test");
  586. const httpClient = new FakeHttpClient([
  587. jsonResponse({
  588. data: {
  589. accessToken: "bigmodel-access-token",
  590. },
  591. }),
  592. ]);
  593. const client = createBigmodelOAuthClient({
  594. appSecret: "test-secret",
  595. httpClient,
  596. });
  597. await client.exchangeCode({ code: "auth-code" });
  598. expect(httpClient.requests[0]?.url).toBe("https://bigmodel.cn/api/auth/tokenByAuthCode");
  599. });
  600. it("requires an explicit app secret before exchanging auth codes", async () => {
  601. const httpClient = new FakeHttpClient([]);
  602. const client = createBigmodelOAuthClient({ httpClient });
  603. await expect(client.exchangeCode({ code: "auth-code" })).rejects.toMatchObject({
  604. message: "BigModel OAuth appSecret is required.",
  605. name: "BigmodelOAuthError",
  606. });
  607. expect(httpClient.requests).toHaveLength(0);
  608. });
  609. });
  610. class FakeHttpClient implements HttpClientPort {
  611. readonly requests: HttpClientRequest[] = [];
  612. constructor(private readonly responses: HttpClientResponse[]) {}
  613. async request(request: HttpClientRequest): Promise<HttpClientResponse> {
  614. this.requests.push(request);
  615. const response = this.responses.shift();
  616. if (!response) {
  617. throw new Error("No fake response configured");
  618. }
  619. return response;
  620. }
  621. }
  622. function jsonResponse(body: unknown, status = 200): HttpClientResponse {
  623. const encoded = new TextEncoder().encode(JSON.stringify(body));
  624. return {
  625. body: encoded,
  626. bytes: encoded.byteLength,
  627. durationMs: 1,
  628. headers: {
  629. "content-type": "application/json",
  630. },
  631. status,
  632. statusText: status === 200 ? "OK" : "Error",
  633. url: "https://zcode.example/api/v1",
  634. };
  635. }
  636. function customerInfoResponse(): HttpClientResponse {
  637. return jsonResponse({
  638. code: 200,
  639. data: {
  640. organizations: [
  641. {
  642. organizationId: "org-1",
  643. organizationName: "默认机构",
  644. projects: [
  645. {
  646. projectId: "project-1",
  647. projectName: "默认项目",
  648. },
  649. ],
  650. },
  651. ],
  652. },
  653. });
  654. }