auth.test.ts 31 KB

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