auth-login.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import { describe, expect, it } from "vitest";
  6. import type { HttpClientPort, HttpClientRequest, HttpClientResponse } from "@zcode/contracts";
  7. import {
  8. SHARED_ZCODE_CREDENTIAL_KEYS,
  9. createSharedZCodeCredentialStore,
  10. } from "@zcode/adapters/auth";
  11. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  12. import {
  13. standaloneAccountIdentityCredentialKey,
  14. standaloneAccountAuthSourceCredentialKey,
  15. standaloneAccountProviderCredentialKey,
  16. } from "../src/app/standalone-account-provider-runtime.js";
  17. import {
  18. configureCodingPlanApiKey,
  19. hasConfiguredStandaloneCodingPlan,
  20. loginZCodeCli,
  21. logoutZCodeCli,
  22. } from "../src/auth-login.js";
  23. const TEST_ENV = {
  24. ZCODE_CREDENTIAL_SECRET: "bootstrap-test-secret",
  25. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: fileURLToPath(
  26. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  27. ),
  28. };
  29. describe("ZCode CLI login", () => {
  30. it("没有任何 Standalone 账号凭据时不会误报已配置 Coding Plan", async () => {
  31. const dir = await mkdtemp(join(tmpdir(), "zcode-no-login-"));
  32. const credentialStore = createSharedZCodeCredentialStore({
  33. baseDir: dir,
  34. env: TEST_ENV,
  35. });
  36. try {
  37. await expect(
  38. hasConfiguredStandaloneCodingPlan({ credentialStore, env: TEST_ENV }),
  39. ).resolves.toBe(false);
  40. } finally {
  41. await rm(dir, { force: true, recursive: true });
  42. }
  43. });
  44. it("uses the production ZCode endpoint by default for OAuth init", async () => {
  45. const httpClient = new FakeHttpClient([
  46. jsonResponse({
  47. code: 0,
  48. msg: "",
  49. data: {
  50. flow_id: "flow-failed",
  51. poll_token: "poll-token",
  52. authorize_url: "https://chat.z.ai/oauth/authorize?state=failed",
  53. expires_at: 9999999999,
  54. poll_interval_sec: 2,
  55. },
  56. }),
  57. jsonResponse({
  58. code: 0,
  59. msg: "",
  60. data: {
  61. status: "failed",
  62. },
  63. }),
  64. ]);
  65. await expect(
  66. loginZCodeCli({
  67. env: TEST_ENV,
  68. httpClient,
  69. noBrowser: true,
  70. now: () => 1_000,
  71. pollToken: "poll-token",
  72. sleep: async () => undefined,
  73. }),
  74. ).rejects.toMatchObject({
  75. code: "auth_failed",
  76. });
  77. expect(httpClient.requests[0]?.url).toBe("https://zcode.z.ai/api/v1/oauth/cli/init");
  78. });
  79. it("polls OAuth, stores account credentials, and updates the configured default", async () => {
  80. const dir = await mkdtemp(join(tmpdir(), "zcode-login-"));
  81. const credentialsBaseDir = join(dir, "home");
  82. const personalProviderConfigPath = join(dir, "provider_config.json");
  83. const credentialStore = createSharedZCodeCredentialStore({
  84. baseDir: credentialsBaseDir,
  85. env: TEST_ENV,
  86. });
  87. const httpClient = new FakeHttpClient([
  88. jsonResponse({
  89. code: 0,
  90. msg: "",
  91. data: {
  92. flow_id: "flow-1",
  93. poll_token: "poll-token",
  94. authorize_url: "https://chat.z.ai/oauth/authorize?state=state",
  95. expires_at: 9999999999,
  96. poll_interval_sec: 2,
  97. },
  98. }),
  99. jsonResponse({
  100. code: 0,
  101. msg: "",
  102. data: {
  103. status: "pending",
  104. },
  105. }),
  106. jsonResponse({
  107. code: 0,
  108. msg: "",
  109. data: {
  110. status: "ready",
  111. token: "jwt-token",
  112. user: {
  113. user_id: "u_1",
  114. email: "alice@example.com",
  115. name: "Alice",
  116. },
  117. zai: {
  118. access_token: "zai-access-token",
  119. },
  120. },
  121. }),
  122. jsonResponse({
  123. code: 0,
  124. data: {
  125. access_token: "zai-biz-token",
  126. },
  127. }),
  128. jsonResponse({
  129. code: 200,
  130. data: {
  131. organizations: [
  132. {
  133. organizationId: "org-1",
  134. organizationName: "默认机构",
  135. projects: [
  136. {
  137. projectId: "project-1",
  138. projectName: "默认项目",
  139. },
  140. ],
  141. },
  142. ],
  143. },
  144. }),
  145. jsonResponse({
  146. code: 200,
  147. data: [],
  148. }),
  149. jsonResponse({
  150. code: 200,
  151. data: {
  152. apiKey: "zai-api-key",
  153. name: "zcode-api-key",
  154. },
  155. }),
  156. jsonResponse({
  157. code: 200,
  158. data: {
  159. accessToken: "project-token",
  160. tokenType: "Bearer",
  161. expiresIn: 600,
  162. expiresAt: Math.floor(Date.now() / 1000) + 600,
  163. },
  164. }),
  165. ]);
  166. const statuses: string[] = [];
  167. let authorizeUrl = "";
  168. try {
  169. const result = await loginZCodeCli({
  170. credentialStore,
  171. env: TEST_ENV,
  172. httpClient,
  173. noBrowser: true,
  174. now: () => 1_000,
  175. onAuthorizeUrl: (data) => {
  176. authorizeUrl = data.authorize_url;
  177. },
  178. onPollStatus: (data) => {
  179. statuses.push(data.status);
  180. },
  181. pollToken: "poll-token",
  182. sleep: async () => undefined,
  183. personalProviderConfigPath,
  184. });
  185. const modelSelectionConfig = JSON.parse(await readFile(personalProviderConfigPath, "utf-8"));
  186. const accountProviderCredentialKey = standaloneAccountProviderCredentialKey({
  187. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  188. accountIdentity: "u_1",
  189. });
  190. expect(authorizeUrl).toBe("https://chat.z.ai/oauth/authorize?state=state");
  191. expect(statuses).toEqual(["pending", "ready"]);
  192. expect(result).toMatchObject({
  193. configPath: personalProviderConfigPath,
  194. credentialsPath: credentialStore.filePath,
  195. model: `${BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan}/GLM-5.3`,
  196. providerId: "zai",
  197. user: {
  198. user_id: "u_1",
  199. email: "alice@example.com",
  200. name: "Alice",
  201. },
  202. });
  203. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBe(
  204. "zai-access-token",
  205. );
  206. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken)).toBe(
  207. "jwt-token",
  208. );
  209. expect(
  210. await credentialStore.load(
  211. standaloneAccountIdentityCredentialKey(
  212. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  213. ),
  214. ),
  215. ).toBe("u_1");
  216. expect(await credentialStore.load(accountProviderCredentialKey)).toBeNull();
  217. expect(modelSelectionConfig).toMatchObject({
  218. schemaVersion: 1,
  219. config: {
  220. defaultModelSelection: {
  221. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  222. modelId: "GLM-5.3",
  223. },
  224. },
  225. });
  226. } finally {
  227. await rm(dir, { force: true, recursive: true });
  228. }
  229. });
  230. it("clears shared ZAI credentials and standalone account access on logout", async () => {
  231. const dir = await mkdtemp(join(tmpdir(), "zcode-logout-"));
  232. const credentialStore = createSharedZCodeCredentialStore({
  233. baseDir: dir,
  234. env: TEST_ENV,
  235. });
  236. try {
  237. await credentialStore.saveZaiLoginCredentials({
  238. accessToken: "zai-access-token",
  239. jwtToken: "jwt-token",
  240. user: {
  241. user_id: "u_1",
  242. },
  243. });
  244. const accountProviderCredentialKey = standaloneAccountProviderCredentialKey({
  245. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  246. accountIdentity: "u_1",
  247. });
  248. await credentialStore.saveMany({
  249. [standaloneAccountIdentityCredentialKey(
  250. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  251. )]: "u_1",
  252. [standaloneAccountAuthSourceCredentialKey(
  253. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  254. )]: "manual",
  255. [accountProviderCredentialKey]: "coding-plan-key",
  256. });
  257. const result = await logoutZCodeCli({ credentialStore, env: TEST_ENV });
  258. expect(result.credentialsPath).toBe(credentialStore.filePath);
  259. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBeNull();
  260. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider)).toBeNull();
  261. expect(
  262. await credentialStore.load(
  263. standaloneAccountIdentityCredentialKey(
  264. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  265. ),
  266. ),
  267. ).toBeNull();
  268. expect(await credentialStore.load(accountProviderCredentialKey)).toBeNull();
  269. } finally {
  270. await rm(dir, { force: true, recursive: true });
  271. }
  272. });
  273. it.each(["oauth", undefined])("退出不解密来源为 %s 的历史旧 Key", async (source) => {
  274. const dir = await mkdtemp(join(tmpdir(), "zcode-logout-legacy-"));
  275. const credentialStore = createSharedZCodeCredentialStore({ baseDir: dir, env: TEST_ENV });
  276. const providerId = BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan;
  277. const legacyKey = standaloneAccountProviderCredentialKey({
  278. providerId,
  279. accountIdentity: "user",
  280. });
  281. try {
  282. await credentialStore.saveMany({
  283. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: "valid-oauth",
  284. [standaloneAccountIdentityCredentialKey(providerId)]: "user",
  285. ...(source ? { [standaloneAccountAuthSourceCredentialKey(providerId)]: source } : {}),
  286. });
  287. const raw = JSON.parse(await readFile(credentialStore.filePath, "utf8"));
  288. raw[legacyKey] = "enc:v1:broken-legacy-key";
  289. await writeFile(credentialStore.filePath, JSON.stringify(raw));
  290. await expect(logoutZCodeCli({ credentialStore, env: TEST_ENV })).resolves.toMatchObject({
  291. credentialsPath: credentialStore.filePath,
  292. });
  293. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBeNull();
  294. expect(
  295. await credentialStore.load(standaloneAccountIdentityCredentialKey(providerId)),
  296. ).toBeNull();
  297. expect(JSON.parse(await readFile(credentialStore.filePath, "utf8"))[legacyKey]).toBe(
  298. raw[legacyKey],
  299. );
  300. } finally {
  301. await rm(dir, { force: true, recursive: true });
  302. }
  303. });
  304. it("manual Coding Plan API Key uses the same Account Access and Selection facts", async () => {
  305. const dir = await mkdtemp(join(tmpdir(), "zcode-api-key-login-"));
  306. const credentialStore = createSharedZCodeCredentialStore({
  307. baseDir: join(dir, "home"),
  308. env: TEST_ENV,
  309. });
  310. const personalProviderConfigPath = join(dir, "provider_config.json");
  311. const zcodeBuiltinProviderConfigPath = join(dir, "zcode-builtin.json");
  312. const configuredProviderId = "configured-bigmodel-individual";
  313. await writeFile(
  314. zcodeBuiltinProviderConfigPath,
  315. JSON.stringify({
  316. schemaVersion: 1,
  317. revision: 1,
  318. config: {
  319. providerConfigRules: {
  320. templateRules: [],
  321. providerRules: [
  322. {
  323. providerId: configuredProviderId,
  324. config: {
  325. group: "bigmodel-family",
  326. builtinModelIds: ["model-from-config"],
  327. access: {
  328. type: "zhipu-account",
  329. accountType: "bigmodel",
  330. mode: "individual-coding-plan",
  331. },
  332. },
  333. },
  334. ],
  335. },
  336. modelConfigRules: {
  337. modelRules: [],
  338. modelApiRules: [],
  339. providerSiteRules: [],
  340. templateModelRules: [],
  341. builtinProviderModelRules: [],
  342. },
  343. },
  344. }),
  345. );
  346. try {
  347. const result = await configureCodingPlanApiKey({
  348. apiKey: "manual-key",
  349. credentialStore,
  350. env: {
  351. ...TEST_ENV,
  352. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: zcodeBuiltinProviderConfigPath,
  353. },
  354. personalProviderConfigPath,
  355. providerId: "bigmodel",
  356. });
  357. expect(result).toEqual({
  358. configPath: personalProviderConfigPath,
  359. model: `${configuredProviderId}/model-from-config`,
  360. providerId: "bigmodel",
  361. });
  362. await expect(
  363. hasConfiguredStandaloneCodingPlan({
  364. credentialStore,
  365. env: {
  366. ...TEST_ENV,
  367. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: zcodeBuiltinProviderConfigPath,
  368. },
  369. }),
  370. ).resolves.toBe(true);
  371. } finally {
  372. await rm(dir, { force: true, recursive: true });
  373. }
  374. });
  375. it("reports failed and expired OAuth flows as retryable login errors", async () => {
  376. const failedClient = new FakeHttpClient([
  377. jsonResponse({
  378. code: 0,
  379. msg: "",
  380. data: {
  381. flow_id: "flow-failed",
  382. poll_token: "poll-token",
  383. authorize_url: "https://chat.z.ai/oauth/authorize?state=failed",
  384. expires_at: 9999999999,
  385. poll_interval_sec: 2,
  386. },
  387. }),
  388. jsonResponse({
  389. code: 0,
  390. msg: "",
  391. data: {
  392. status: "failed",
  393. },
  394. }),
  395. ]);
  396. await expect(
  397. loginZCodeCli({
  398. env: TEST_ENV,
  399. httpClient: failedClient,
  400. noBrowser: true,
  401. now: () => 1_000,
  402. pollToken: "poll-token",
  403. sleep: async () => undefined,
  404. }),
  405. ).rejects.toMatchObject({
  406. code: "auth_failed",
  407. });
  408. const expiredClient = new FakeHttpClient([
  409. jsonResponse({
  410. code: 0,
  411. msg: "",
  412. data: {
  413. flow_id: "flow-expired",
  414. poll_token: "poll-token",
  415. authorize_url: "https://chat.z.ai/oauth/authorize?state=expired",
  416. expires_at: 1,
  417. poll_interval_sec: 2,
  418. },
  419. }),
  420. ]);
  421. await expect(
  422. loginZCodeCli({
  423. env: TEST_ENV,
  424. httpClient: expiredClient,
  425. noBrowser: true,
  426. now: () => 2_000,
  427. pollToken: "poll-token",
  428. sleep: async () => undefined,
  429. }),
  430. ).rejects.toMatchObject({
  431. code: "auth_timeout",
  432. });
  433. });
  434. it("aborts a ZAI OAuth login while waiting for authorization", async () => {
  435. const abortController = new AbortController();
  436. let sleepStarted: (() => void) | undefined;
  437. const sleepPromise = new Promise<void>((resolve) => {
  438. sleepStarted = resolve;
  439. });
  440. const httpClient = new FakeHttpClient([
  441. jsonResponse({
  442. code: 0,
  443. msg: "",
  444. data: {
  445. flow_id: "flow-abort",
  446. poll_token: "poll-token",
  447. authorize_url: "https://chat.z.ai/oauth/authorize?state=abort",
  448. expires_at: 9999999999,
  449. poll_interval_sec: 2,
  450. },
  451. }),
  452. jsonResponse({
  453. code: 0,
  454. msg: "",
  455. data: {
  456. status: "pending",
  457. },
  458. }),
  459. ]);
  460. const loginPromise = loginZCodeCli({
  461. abortSignal: abortController.signal,
  462. env: TEST_ENV,
  463. httpClient,
  464. noBrowser: true,
  465. now: () => 1_000,
  466. pollToken: "poll-token",
  467. sleep: async () => {
  468. sleepStarted?.();
  469. await new Promise<void>(() => undefined);
  470. },
  471. });
  472. await sleepPromise;
  473. abortController.abort(new Error("login cancelled"));
  474. await expect(loginPromise).rejects.toThrow("login cancelled");
  475. expect(httpClient.requests).toHaveLength(2);
  476. });
  477. });
  478. class FakeHttpClient implements HttpClientPort {
  479. readonly requests: HttpClientRequest[] = [];
  480. constructor(private readonly responses: HttpClientResponse[]) {}
  481. async request(request: HttpClientRequest): Promise<HttpClientResponse> {
  482. this.requests.push(request);
  483. const response = this.responses.shift();
  484. if (!response) {
  485. throw new Error("No fake response configured");
  486. }
  487. return response;
  488. }
  489. }
  490. function jsonResponse(body: unknown): HttpClientResponse {
  491. const encoded = new TextEncoder().encode(JSON.stringify(body));
  492. return {
  493. body: encoded,
  494. bytes: encoded.byteLength,
  495. durationMs: 1,
  496. headers: {
  497. "content-type": "application/json",
  498. },
  499. status: 200,
  500. statusText: "OK",
  501. url: "https://zcode.example/api/v1",
  502. };
  503. }