auth-login.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. import { mkdtemp, readdir, 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 { createSystemCredentialCipher } from "@zcode/shared/credential-security";
  13. import { acquireFileLock, atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  14. import {
  15. standaloneAccountIdentityCredentialKey,
  16. standaloneAccountAuthSourceCredentialKey,
  17. standaloneAccountProviderCredentialKey,
  18. } from "../src/app/standalone-account-provider-runtime.js";
  19. import {
  20. configureCodingPlanApiKey,
  21. hasConfiguredStandaloneCodingPlan,
  22. loginZCodeCli,
  23. logoutZCodeCli,
  24. } from "../src/auth-login.js";
  25. const TEST_ENV = {
  26. ZCODE_CREDENTIAL_SECRET: "bootstrap-test-secret",
  27. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: fileURLToPath(
  28. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  29. ),
  30. };
  31. describe("ZCode CLI login", () => {
  32. it("没有任何 Standalone 账号凭据时不会误报已配置 Coding Plan", async () => {
  33. const dir = await mkdtemp(join(tmpdir(), "zcode-no-login-"));
  34. const credentialStore = createSharedZCodeCredentialStore({
  35. baseDir: dir,
  36. env: TEST_ENV,
  37. });
  38. try {
  39. await expect(
  40. hasConfiguredStandaloneCodingPlan({ credentialStore, env: TEST_ENV }),
  41. ).resolves.toBe(false);
  42. } finally {
  43. await rm(dir, { force: true, recursive: true });
  44. }
  45. });
  46. it("uses the production ZCode endpoint by default for OAuth init", async () => {
  47. const dir = await mkdtemp(join(tmpdir(), "zcode-login-endpoint-"));
  48. const filePath = join(dir, "credentials.json");
  49. // Bug 原因:未注入 store 时会访问真实用户目录,失败的登录也会先用测试密钥迁移旧凭据。
  50. // 显式绑定临时文件,避免只模拟 HTTP 却漏掉了持久化副作用。
  51. const credentialStore = createSharedZCodeCredentialStore({ filePath, env: TEST_ENV });
  52. const httpClient = new FakeHttpClient([
  53. jsonResponse({
  54. code: 0,
  55. msg: "",
  56. data: {
  57. flow_id: "flow-failed",
  58. poll_token: "poll-token",
  59. authorize_url: "https://chat.z.ai/oauth/authorize?state=failed",
  60. expires_at: 9999999999,
  61. poll_interval_sec: 2,
  62. },
  63. }),
  64. jsonResponse({
  65. code: 0,
  66. msg: "",
  67. data: {
  68. status: "failed",
  69. },
  70. }),
  71. ]);
  72. try {
  73. await writeFile(filePath, JSON.stringify({ fixture: "existing-credential" }));
  74. await expect(
  75. loginZCodeCli({
  76. credentialStore,
  77. env: TEST_ENV,
  78. httpClient,
  79. noBrowser: true,
  80. now: () => 1_000,
  81. pollToken: "poll-token",
  82. sleep: async () => undefined,
  83. }),
  84. ).rejects.toMatchObject({
  85. code: "auth_failed",
  86. });
  87. expect(httpClient.requests[0]?.url).toBe("https://zcode.z.ai/api/v1/oauth/cli/init");
  88. // 登录失败前也会读取并迁移凭据,必须确实使用此测试的临时文件。
  89. const persisted = JSON.parse(await readFile(filePath, "utf8"));
  90. expect(persisted.fixture).toMatch(/^enc:v2:env:/);
  91. await expect(credentialStore.load("fixture")).resolves.toBe("existing-credential");
  92. } finally {
  93. await rm(dir, { force: true, recursive: true });
  94. }
  95. });
  96. it("polls OAuth, stores account credentials, and updates the configured default", async () => {
  97. const dir = await mkdtemp(join(tmpdir(), "zcode-login-"));
  98. const credentialsBaseDir = join(dir, "home");
  99. const personalProviderConfigPath = join(dir, "provider_config.json");
  100. const credentialStore = createSharedZCodeCredentialStore({
  101. baseDir: credentialsBaseDir,
  102. env: TEST_ENV,
  103. });
  104. const httpClient = new FakeHttpClient([
  105. jsonResponse({
  106. code: 0,
  107. msg: "",
  108. data: {
  109. flow_id: "flow-1",
  110. poll_token: "poll-token",
  111. authorize_url: "https://chat.z.ai/oauth/authorize?state=state",
  112. expires_at: 9999999999,
  113. poll_interval_sec: 2,
  114. },
  115. }),
  116. jsonResponse({
  117. code: 0,
  118. msg: "",
  119. data: {
  120. status: "pending",
  121. },
  122. }),
  123. jsonResponse({
  124. code: 0,
  125. msg: "",
  126. data: {
  127. status: "ready",
  128. token: "jwt-token",
  129. user: {
  130. user_id: "u_1",
  131. email: "alice@example.com",
  132. name: "Alice",
  133. },
  134. zai: {
  135. access_token: "zai-access-token",
  136. },
  137. },
  138. }),
  139. jsonResponse({
  140. code: 0,
  141. data: {
  142. access_token: "zai-biz-token",
  143. },
  144. }),
  145. jsonResponse({
  146. code: 200,
  147. data: {
  148. organizations: [
  149. {
  150. organizationId: "org-1",
  151. organizationName: "默认机构",
  152. projects: [
  153. {
  154. projectId: "project-1",
  155. projectName: "默认项目",
  156. },
  157. ],
  158. },
  159. ],
  160. },
  161. }),
  162. jsonResponse({
  163. code: 200,
  164. data: [],
  165. }),
  166. jsonResponse({
  167. code: 200,
  168. data: {
  169. apiKey: "zai-api-key",
  170. name: "zcode-api-key",
  171. },
  172. }),
  173. jsonResponse({
  174. code: 200,
  175. data: {
  176. accessToken: "project-token",
  177. tokenType: "Bearer",
  178. expiresIn: 600,
  179. expiresAt: Math.floor(Date.now() / 1000) + 600,
  180. },
  181. }),
  182. ]);
  183. const statuses: string[] = [];
  184. let authorizeUrl = "";
  185. try {
  186. const result = await loginZCodeCli({
  187. credentialStore,
  188. env: TEST_ENV,
  189. httpClient,
  190. noBrowser: true,
  191. now: () => 1_000,
  192. onAuthorizeUrl: (data) => {
  193. authorizeUrl = data.authorize_url;
  194. },
  195. onPollStatus: (data) => {
  196. statuses.push(data.status);
  197. },
  198. pollToken: "poll-token",
  199. sleep: async () => undefined,
  200. personalProviderConfigPath,
  201. });
  202. const modelSelectionConfig = JSON.parse(await readFile(personalProviderConfigPath, "utf-8"));
  203. const accountProviderCredentialKey = standaloneAccountProviderCredentialKey({
  204. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  205. accountIdentity: "u_1",
  206. });
  207. expect(authorizeUrl).toBe("https://chat.z.ai/oauth/authorize?state=state");
  208. expect(statuses).toEqual(["pending", "ready"]);
  209. expect(result).toMatchObject({
  210. configPath: personalProviderConfigPath,
  211. credentialsPath: credentialStore.filePath,
  212. model: `${BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan}/GLM-5.3`,
  213. providerId: "zai",
  214. user: {
  215. user_id: "u_1",
  216. email: "alice@example.com",
  217. name: "Alice",
  218. },
  219. });
  220. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBe(
  221. "zai-access-token",
  222. );
  223. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken)).toBe(
  224. "jwt-token",
  225. );
  226. expect(
  227. await credentialStore.load(
  228. standaloneAccountIdentityCredentialKey(
  229. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  230. ),
  231. ),
  232. ).toBe("u_1");
  233. expect(await credentialStore.load(accountProviderCredentialKey)).toBeNull();
  234. expect(modelSelectionConfig).toMatchObject({
  235. schemaVersion: 1,
  236. config: {
  237. defaultModelSelection: {
  238. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  239. modelId: "GLM-5.3",
  240. },
  241. },
  242. });
  243. } finally {
  244. await rm(dir, { force: true, recursive: true });
  245. }
  246. });
  247. it("clears shared ZAI credentials and standalone account access on logout", async () => {
  248. const dir = await mkdtemp(join(tmpdir(), "zcode-logout-"));
  249. const credentialStore = createSharedZCodeCredentialStore({
  250. baseDir: dir,
  251. env: TEST_ENV,
  252. });
  253. try {
  254. await credentialStore.saveZaiLoginCredentials({
  255. accessToken: "zai-access-token",
  256. jwtToken: "jwt-token",
  257. user: {
  258. user_id: "u_1",
  259. },
  260. });
  261. const accountProviderCredentialKey = standaloneAccountProviderCredentialKey({
  262. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  263. accountIdentity: "u_1",
  264. });
  265. await credentialStore.saveMany({
  266. [standaloneAccountIdentityCredentialKey(
  267. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  268. )]: "u_1",
  269. [standaloneAccountAuthSourceCredentialKey(
  270. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  271. )]: "manual",
  272. [accountProviderCredentialKey]: "coding-plan-key",
  273. });
  274. const result = await logoutZCodeCli({ credentialStore, env: TEST_ENV });
  275. expect(result.credentialsPath).toBe(credentialStore.filePath);
  276. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBeNull();
  277. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider)).toBeNull();
  278. expect(
  279. await credentialStore.load(
  280. standaloneAccountIdentityCredentialKey(
  281. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  282. ),
  283. ),
  284. ).toBeNull();
  285. expect(await credentialStore.load(accountProviderCredentialKey)).toBeNull();
  286. } finally {
  287. await rm(dir, { force: true, recursive: true });
  288. }
  289. });
  290. it.each(["oauth", undefined])("退出不解密来源为 %s 的历史旧 Key", async (source) => {
  291. const dir = await mkdtemp(join(tmpdir(), "zcode-logout-legacy-"));
  292. const credentialStore = createSharedZCodeCredentialStore({ baseDir: dir, env: TEST_ENV });
  293. const providerId = BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan;
  294. const legacyKey = standaloneAccountProviderCredentialKey({
  295. providerId,
  296. accountIdentity: "user",
  297. });
  298. try {
  299. await credentialStore.saveMany({
  300. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: "valid-oauth",
  301. [standaloneAccountIdentityCredentialKey(providerId)]: "user",
  302. ...(source ? { [standaloneAccountAuthSourceCredentialKey(providerId)]: source } : {}),
  303. });
  304. const raw = JSON.parse(await readFile(credentialStore.filePath, "utf8"));
  305. raw[legacyKey] = "enc:v1:broken-legacy-key";
  306. await writeFile(credentialStore.filePath, JSON.stringify(raw));
  307. await expect(logoutZCodeCli({ credentialStore, env: TEST_ENV })).resolves.toMatchObject({
  308. credentialsPath: credentialStore.filePath,
  309. });
  310. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken)).toBeNull();
  311. expect(
  312. await credentialStore.load(standaloneAccountIdentityCredentialKey(providerId)),
  313. ).toBeNull();
  314. expect(JSON.parse(await readFile(credentialStore.filePath, "utf8"))[legacyKey]).toBe(
  315. raw[legacyKey],
  316. );
  317. } finally {
  318. await rm(dir, { force: true, recursive: true });
  319. }
  320. });
  321. it("manual Coding Plan API Key uses the same Account Access and Selection facts", async () => {
  322. const dir = await mkdtemp(join(tmpdir(), "zcode-api-key-login-"));
  323. const credentialStore = createSharedZCodeCredentialStore({
  324. baseDir: join(dir, "home"),
  325. env: TEST_ENV,
  326. });
  327. const personalProviderConfigPath = join(dir, "provider_config.json");
  328. const zcodeBuiltinProviderConfigPath = join(dir, "zcode-builtin.json");
  329. const configuredProviderId = "configured-bigmodel-individual";
  330. await writeFile(
  331. zcodeBuiltinProviderConfigPath,
  332. JSON.stringify({
  333. schemaVersion: 1,
  334. revision: 1,
  335. config: {
  336. providerConfigRules: {
  337. templateRules: [],
  338. providerRules: [
  339. {
  340. providerId: configuredProviderId,
  341. config: {
  342. group: "bigmodel-family",
  343. builtinModelIds: ["model-from-config"],
  344. access: {
  345. type: "zhipu-account",
  346. accountType: "bigmodel",
  347. mode: "individual-coding-plan",
  348. },
  349. },
  350. },
  351. ],
  352. },
  353. modelConfigRules: {
  354. modelRules: [],
  355. modelApiRules: [],
  356. providerSiteRules: [],
  357. templateModelRules: [],
  358. builtinProviderModelRules: [],
  359. },
  360. },
  361. }),
  362. );
  363. try {
  364. const result = await configureCodingPlanApiKey({
  365. apiKey: "manual-key",
  366. credentialStore,
  367. env: {
  368. ...TEST_ENV,
  369. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: zcodeBuiltinProviderConfigPath,
  370. },
  371. personalProviderConfigPath,
  372. providerId: "bigmodel",
  373. });
  374. expect(result).toEqual({
  375. configPath: personalProviderConfigPath,
  376. model: `${configuredProviderId}/model-from-config`,
  377. providerId: "bigmodel",
  378. });
  379. await expect(
  380. hasConfiguredStandaloneCodingPlan({
  381. credentialStore,
  382. env: {
  383. ...TEST_ENV,
  384. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: zcodeBuiltinProviderConfigPath,
  385. },
  386. }),
  387. ).resolves.toBe(true);
  388. } finally {
  389. await rm(dir, { force: true, recursive: true });
  390. }
  391. });
  392. for (const providerId of ["zai", "bigmodel"] as const) {
  393. for (const pauseAt of ["credential-lock", "config-lock"] as const) {
  394. it(`${providerId} API Key 登录在 ${pauseAt} 期间恢复后不得提交旧凭据或默认配置`, async () => {
  395. const dir = await mkdtemp(join(tmpdir(), "zcode-manual-login-recovery-"));
  396. const credentialStore = createSharedZCodeCredentialStore({ baseDir: dir, env: TEST_ENV });
  397. const personalProviderConfigPath = join(dir, "provider_config.json");
  398. const original = JSON.stringify({
  399. schemaVersion: 1,
  400. config: {
  401. providerConfigRules: { providerRules: [] },
  402. modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
  403. },
  404. });
  405. let entered!: () => void;
  406. const waiting = new Promise<void>((resolve) => {
  407. entered = resolve;
  408. });
  409. const capture = credentialStore.captureRecoveryGuard.bind(credentialStore);
  410. credentialStore.captureRecoveryGuard = async () => {
  411. const guard = await capture();
  412. if (pauseAt === "credential-lock") entered();
  413. return guard;
  414. };
  415. let observing = false;
  416. const stop = credentialStore.onDidChange?.(() => {
  417. if (observing && pauseAt === "config-lock") entered();
  418. });
  419. let unlock: (() => Promise<void>) | undefined;
  420. try {
  421. await credentialStore.save("before", "old-value");
  422. await writeFile(personalProviderConfigPath, original);
  423. unlock = await acquireFileLock(
  424. pauseAt === "credential-lock" ? credentialStore.filePath : personalProviderConfigPath,
  425. [],
  426. 0,
  427. 10000,
  428. );
  429. observing = true;
  430. const options = {
  431. providerId,
  432. apiKey: "synthetic-api-key",
  433. credentialStore,
  434. env: TEST_ENV,
  435. personalProviderConfigPath,
  436. };
  437. const pending = configureCodingPlanApiKey(options).then(
  438. (result) => ({ result }),
  439. (error: unknown) => ({ error }),
  440. );
  441. // 配置等待由实际凭据保存确认;凭据等待由实际 guard 捕获确认,不靠睡眠猜测。
  442. await waiting;
  443. if (pauseAt === "credential-lock") {
  444. await atomicWritePrivateTextFile(
  445. `${credentialStore.filePath}.recovery-generation`,
  446. "recovered",
  447. );
  448. await atomicWritePrivateTextFile(credentialStore.filePath, "{}");
  449. } else {
  450. await withFileLock(credentialStore.filePath, async () => {
  451. await atomicWritePrivateTextFile(
  452. `${credentialStore.filePath}.recovery-generation`,
  453. "recovered",
  454. );
  455. await atomicWritePrivateTextFile(credentialStore.filePath, "{}");
  456. });
  457. }
  458. await unlock();
  459. unlock = undefined;
  460. expect(await pending).toMatchObject({
  461. error: { code: "ZCODE_CREDENTIAL_STORE_CHANGED" },
  462. });
  463. expect(await readFile(credentialStore.filePath, "utf8")).toBe("{}");
  464. expect(await readFile(personalProviderConfigPath, "utf8")).toBe(original);
  465. await expect(configureCodingPlanApiKey(options)).resolves.toMatchObject({ providerId });
  466. expect(await readFile(personalProviderConfigPath, "utf8")).not.toBe(original);
  467. } finally {
  468. stop?.();
  469. await unlock?.();
  470. await rm(dir, { recursive: true, force: true });
  471. }
  472. });
  473. }
  474. for (const pauseAt of ["init", "poll", "material", "config-lock"] as const) {
  475. it(`${providerId} 在 ${pauseAt} 等待期间恢复凭据库后拒绝旧登录,新登录仍可成功`, async () => {
  476. const dir = await mkdtemp(join(tmpdir(), "zcode-login-recovery-"));
  477. const credentialStore = createSharedZCodeCredentialStore({ baseDir: dir, env: TEST_ENV });
  478. const personalProviderConfigPath = join(dir, "provider_config.json");
  479. const originalConfig = JSON.stringify({
  480. schemaVersion: 1,
  481. config: {
  482. providerConfigRules: { providerRules: [] },
  483. modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
  484. },
  485. });
  486. let release!: () => void;
  487. let entered!: () => void;
  488. let paused = true;
  489. let unlockConfig: (() => Promise<void>) | undefined;
  490. const gate = new Promise<void>((resolve) => {
  491. release = resolve;
  492. });
  493. const waiting = new Promise<void>((resolve) => {
  494. entered = resolve;
  495. });
  496. const pause = async (stage: string) => {
  497. if (paused && stage === pauseAt) {
  498. entered();
  499. await gate;
  500. }
  501. };
  502. const options = () => {
  503. const http = new FakeHttpClient([
  504. jsonResponse({
  505. code: 0,
  506. data: {
  507. flow_id: "recovery-flow",
  508. authorize_url: "https://example.com/authorize",
  509. expires_at: 9999999999,
  510. poll_interval_sec: 1,
  511. },
  512. }),
  513. jsonResponse({
  514. code: 0,
  515. data: {
  516. status: "ready",
  517. token: "new-jwt",
  518. user: { user_id: "test-user", name: "Test" },
  519. [providerId]: { access_token: "new-access" },
  520. },
  521. }),
  522. ]);
  523. return {
  524. providerId,
  525. credentialStore,
  526. personalProviderConfigPath,
  527. env: TEST_ENV,
  528. noBrowser: true,
  529. pollToken: "test-poll",
  530. sleep: async () => undefined,
  531. httpClient: {
  532. request: async (request: HttpClientRequest) => {
  533. if (request.url.endsWith("/init")) await pause("init");
  534. if (request.url.includes("/poll/")) await pause("poll");
  535. return http.request(request);
  536. },
  537. },
  538. apiKeyResolver: {
  539. clear() {},
  540. resolve: async () => "test-pat",
  541. resolveMaterial: async () => {
  542. await pause("material");
  543. return {
  544. token: "test-pat",
  545. apiKeyId: "key",
  546. organizationId: "org",
  547. projectId: "project",
  548. };
  549. },
  550. },
  551. };
  552. };
  553. const stopObserving = credentialStore.onDidChange?.(async () => {
  554. if (
  555. pauseAt === "config-lock" &&
  556. (await credentialStore.load(
  557. standaloneAccountIdentityCredentialKey(
  558. providerId === "zai"
  559. ? BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
  560. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  561. ),
  562. ))
  563. )
  564. entered();
  565. });
  566. try {
  567. await credentialStore.save("before", "old-value");
  568. await writeFile(personalProviderConfigPath, originalConfig);
  569. if (pauseAt === "config-lock")
  570. unlockConfig = await acquireFileLock(personalProviderConfigPath, [], 0, 10000);
  571. const pending = loginZCodeCli(options()).then(
  572. (result) => ({ result }),
  573. (error: unknown) => ({ error }),
  574. );
  575. await waiting;
  576. // 与 Desktop 恢复相同的提交边界:同一锁内先推进代次,再原子替换空库。
  577. await withFileLock(credentialStore.filePath, async () => {
  578. await atomicWritePrivateTextFile(
  579. `${credentialStore.filePath}.recovery-generation`,
  580. "recovered",
  581. );
  582. await atomicWritePrivateTextFile(credentialStore.filePath, "{}");
  583. });
  584. paused = false;
  585. release();
  586. await unlockConfig?.();
  587. unlockConfig = undefined;
  588. const completion = await pending;
  589. expect(completion).toMatchObject({
  590. error: {
  591. code: pauseAt === "config-lock" ? "config_update_failed" : "credential_write_failed",
  592. cause: { code: "ZCODE_CREDENTIAL_STORE_CHANGED" },
  593. },
  594. });
  595. expect(await readFile(credentialStore.filePath, "utf8")).toBe("{}");
  596. expect(await readFile(personalProviderConfigPath, "utf8")).toBe(originalConfig);
  597. await expect(loginZCodeCli(options())).resolves.toMatchObject({ providerId });
  598. expect(await credentialStore.load(SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider)).toBe(
  599. providerId,
  600. );
  601. expect(await readFile(personalProviderConfigPath, "utf8")).not.toBe(originalConfig);
  602. } finally {
  603. release();
  604. await unlockConfig?.();
  605. stopObserving?.();
  606. await rm(dir, { force: true, recursive: true });
  607. }
  608. });
  609. }
  610. }
  611. it("reports failed and expired OAuth flows as retryable login errors", async () => {
  612. const dir = await mkdtemp(join(tmpdir(), "zcode-login-failure-"));
  613. const credentialStore = createSharedZCodeCredentialStore({ baseDir: dir, env: TEST_ENV });
  614. const failedClient = new FakeHttpClient([
  615. jsonResponse({
  616. code: 0,
  617. msg: "",
  618. data: {
  619. flow_id: "flow-failed",
  620. poll_token: "poll-token",
  621. authorize_url: "https://chat.z.ai/oauth/authorize?state=failed",
  622. expires_at: 9999999999,
  623. poll_interval_sec: 2,
  624. },
  625. }),
  626. jsonResponse({
  627. code: 0,
  628. msg: "",
  629. data: {
  630. status: "failed",
  631. },
  632. }),
  633. ]);
  634. try {
  635. await expect(
  636. loginZCodeCli({
  637. credentialStore,
  638. env: TEST_ENV,
  639. httpClient: failedClient,
  640. noBrowser: true,
  641. now: () => 1_000,
  642. pollToken: "poll-token",
  643. sleep: async () => undefined,
  644. }),
  645. ).rejects.toMatchObject({
  646. code: "auth_failed",
  647. });
  648. const expiredClient = new FakeHttpClient([
  649. jsonResponse({
  650. code: 0,
  651. msg: "",
  652. data: {
  653. flow_id: "flow-expired",
  654. poll_token: "poll-token",
  655. authorize_url: "https://chat.z.ai/oauth/authorize?state=expired",
  656. expires_at: 1,
  657. poll_interval_sec: 2,
  658. },
  659. }),
  660. ]);
  661. await expect(
  662. loginZCodeCli({
  663. credentialStore,
  664. env: TEST_ENV,
  665. httpClient: expiredClient,
  666. noBrowser: true,
  667. now: () => 2_000,
  668. pollToken: "poll-token",
  669. sleep: async () => undefined,
  670. }),
  671. ).rejects.toMatchObject({
  672. code: "auth_timeout",
  673. });
  674. } finally {
  675. await rm(dir, { force: true, recursive: true });
  676. }
  677. });
  678. it("系统凭据库不可用时在 OAuth init 前失败,不展示授权地址", async () => {
  679. const dir = await mkdtemp(join(tmpdir(), "zcode-login-store-unavailable-"));
  680. const filePath = join(dir, "credentials.json");
  681. // 不配置受管密钥:空库在首次写入时才访问系统库,拒绝访问模拟锁定或缺少 Secret Service。
  682. const env = {};
  683. const keyStoreCalls: string[] = [];
  684. const credentialStore = createSharedZCodeCredentialStore({
  685. cipher: createSystemCredentialCipher({
  686. env,
  687. filePath,
  688. keyStore: {
  689. get: async () => {
  690. keyStoreCalls.push("get");
  691. throw new Error("denied");
  692. },
  693. set: async () => {
  694. keyStoreCalls.push("set");
  695. throw new Error("denied");
  696. },
  697. },
  698. }),
  699. env,
  700. filePath,
  701. });
  702. const httpClient = new FakeHttpClient([
  703. jsonResponse({
  704. code: 0,
  705. msg: "",
  706. data: {
  707. flow_id: "flow-store-unavailable",
  708. poll_token: "poll-token",
  709. authorize_url: "https://chat.z.ai/oauth/authorize?state=store-unavailable",
  710. expires_at: 9999999999,
  711. poll_interval_sec: 2,
  712. },
  713. }),
  714. jsonResponse({
  715. code: 0,
  716. msg: "",
  717. data: {
  718. status: "ready",
  719. token: "jwt-token",
  720. user: { user_id: "u_1" },
  721. zai: { access_token: "zai-access-token" },
  722. },
  723. }),
  724. ]);
  725. let authorizeUrlShown = false;
  726. try {
  727. await expect(
  728. loginZCodeCli({
  729. apiKeyResolver: {
  730. clear() {},
  731. resolve: async () => "test-pat",
  732. resolveMaterial: async () => ({
  733. token: "test-pat",
  734. apiKeyId: "key",
  735. organizationId: "org",
  736. projectId: "project",
  737. }),
  738. },
  739. baseUrl: "https://zcode.example/api/v1",
  740. credentialStore,
  741. env,
  742. httpClient,
  743. noBrowser: true,
  744. now: () => 1_000,
  745. onAuthorizeUrl: () => {
  746. authorizeUrlShown = true;
  747. },
  748. pollToken: "poll-token",
  749. sleep: async () => undefined,
  750. }),
  751. ).rejects.toHaveProperty("code", "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE");
  752. expect(keyStoreCalls).toEqual(["get"]);
  753. expect(httpClient.requests).toHaveLength(0);
  754. expect(authorizeUrlShown).toBe(false);
  755. await expect(readdir(dir)).resolves.toEqual([]);
  756. } finally {
  757. await rm(dir, { force: true, recursive: true });
  758. }
  759. });
  760. it("aborts a ZAI OAuth login while waiting for authorization", async () => {
  761. const dir = await mkdtemp(join(tmpdir(), "zcode-login-abort-"));
  762. const credentialStore = createSharedZCodeCredentialStore({ baseDir: dir, env: TEST_ENV });
  763. const abortController = new AbortController();
  764. let sleepStarted: (() => void) | undefined;
  765. const sleepPromise = new Promise<void>((resolve) => {
  766. sleepStarted = resolve;
  767. });
  768. const httpClient = new FakeHttpClient([
  769. jsonResponse({
  770. code: 0,
  771. msg: "",
  772. data: {
  773. flow_id: "flow-abort",
  774. poll_token: "poll-token",
  775. authorize_url: "https://chat.z.ai/oauth/authorize?state=abort",
  776. expires_at: 9999999999,
  777. poll_interval_sec: 2,
  778. },
  779. }),
  780. jsonResponse({
  781. code: 0,
  782. msg: "",
  783. data: {
  784. status: "pending",
  785. },
  786. }),
  787. ]);
  788. try {
  789. const loginPromise = loginZCodeCli({
  790. abortSignal: abortController.signal,
  791. credentialStore,
  792. env: TEST_ENV,
  793. httpClient,
  794. noBrowser: true,
  795. now: () => 1_000,
  796. pollToken: "poll-token",
  797. sleep: async () => {
  798. sleepStarted?.();
  799. await new Promise<void>(() => undefined);
  800. },
  801. });
  802. await sleepPromise;
  803. abortController.abort(new Error("login cancelled"));
  804. await expect(loginPromise).rejects.toThrow("login cancelled");
  805. expect(httpClient.requests).toHaveLength(2);
  806. } finally {
  807. await rm(dir, { force: true, recursive: true });
  808. }
  809. });
  810. });
  811. class FakeHttpClient implements HttpClientPort {
  812. readonly requests: HttpClientRequest[] = [];
  813. constructor(private readonly responses: HttpClientResponse[]) {}
  814. async request(request: HttpClientRequest): Promise<HttpClientResponse> {
  815. this.requests.push(request);
  816. const response = this.responses.shift();
  817. if (!response) {
  818. throw new Error("No fake response configured");
  819. }
  820. return response;
  821. }
  822. }
  823. function jsonResponse(body: unknown): HttpClientResponse {
  824. const encoded = new TextEncoder().encode(JSON.stringify(body));
  825. return {
  826. body: encoded,
  827. bytes: encoded.byteLength,
  828. durationMs: 1,
  829. headers: {
  830. "content-type": "application/json",
  831. },
  832. status: 200,
  833. statusText: "OK",
  834. url: "https://zcode.example/api/v1",
  835. };
  836. }