auth.test.ts 28 KB

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