tui-login-polling.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. import assert from "node:assert/strict";
  2. import { test, type TestContext } from "node:test";
  3. import { mkdtemp, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join, resolve } from "node:path";
  6. import type { HttpClientPort, HttpClientResponse, SessionEvent } from "@zcode/contracts";
  7. import {
  8. createCliOAuthClient,
  9. createSharedZCodeCredentialStore,
  10. SHARED_ZCODE_CREDENTIAL_KEYS as keys,
  11. } from "@zcode/adapters/auth";
  12. import { NodePersonalProviderConfigRepository } from "@zcode/provider-node";
  13. import {
  14. loginZCodeCli,
  15. loginBigmodelCodingPlan,
  16. type LoginZCodeCliOptions,
  17. } from "../../bootstrap/src/auth-login.js";
  18. import { startProcessProviderRegistryRuntime } from "../../bootstrap/src/app/process-provider-registry-runtime.js";
  19. import { listRegistryBackedModels } from "../../bootstrap/src/app/provider-registry-selection.js";
  20. import {
  21. createStandaloneAccountIdentityFromSecret,
  22. resolveStandaloneCodingPlanProvider,
  23. standaloneAccountAuthSourceCredentialKey,
  24. standaloneAccountIdentityCredentialKey,
  25. standaloneAccountProviderCredentialKey,
  26. } from "../../bootstrap/src/app/standalone-account-provider-runtime.js";
  27. import { createTuiSubmitPrompt } from "../src/tui-prompt-handler.js";
  28. import { createCliModeState } from "../src/tui-command-state.js";
  29. import type { CommandCenterApp } from "../src/command-center.js";
  30. import type { RunDependencies } from "../src/cli-types.js";
  31. import type { TuiOptions } from "../../tui/src/types.js";
  32. import { runLoginCommand } from "../src/login-command.js";
  33. const authorizeUrl = "https://login.example.test/authorize?state=test-state";
  34. const pollToken = "test-private-poll-token";
  35. const ready = (providerId: "zai" | "bigmodel") => ({
  36. status: "ready",
  37. token: "test-backend-jwt",
  38. user: { user_id: "test-account", name: "Test User" },
  39. [providerId]:
  40. providerId === "zai"
  41. ? { access_token: "test-oauth-token" }
  42. : { accessToken: "test-business-token", refreshToken: "test-refresh-token" },
  43. });
  44. const TEST_PROJECT_MATERIAL = {
  45. token: "test-project-token",
  46. apiKeyId: "test-api-key-id",
  47. organizationId: "test-org",
  48. projectId: "test-project",
  49. };
  50. function response(data: unknown, status = 200): HttpClientResponse {
  51. const body = new TextEncoder().encode(JSON.stringify({ code: 0, data }));
  52. return {
  53. url: "https://example.test",
  54. status,
  55. statusText: "test",
  56. headers: {},
  57. body,
  58. bytes: body.length,
  59. durationMs: 0,
  60. };
  61. }
  62. async function fixture(t: TestContext, providerId: "zai" | "bigmodel" = "bigmodel") {
  63. const dir = await mkdtemp(join(tmpdir(), "zcode-login-test-"));
  64. t.after(() => rm(dir, { recursive: true, force: true }));
  65. const personalFile = join(dir, "provider_config.json");
  66. const personal = new NodePersonalProviderConfigRepository({
  67. filePath: personalFile,
  68. pollingIntervalMs: false,
  69. });
  70. await personal.update((current) => current);
  71. personal.dispose();
  72. const env = {
  73. ZCODE_DATA_BASE_DIR: dir,
  74. ZCODE_CREDENTIAL_SECRET: "test-encryption-key",
  75. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: resolve(
  76. import.meta.dirname,
  77. "../../../../../config/provider/zcode-builtin.json",
  78. ),
  79. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: personalFile,
  80. };
  81. const store = createSharedZCodeCredentialStore({ env });
  82. let now = 1_000_000;
  83. const sleeps: number[] = [];
  84. const requests: Parameters<HttpClientPort["request"]>[0][] = [];
  85. const f = {
  86. env,
  87. store,
  88. sleeps,
  89. requests,
  90. advance: (ms: number) => {
  91. now += ms;
  92. },
  93. poll: async (_signal?: AbortSignal): Promise<HttpClientResponse> => response(ready(providerId)),
  94. options: {} as LoginZCodeCliOptions,
  95. };
  96. const httpClient: HttpClientPort = {
  97. async request(request, options) {
  98. requests.push(request);
  99. assert.equal(request.headers?.Authorization, `Bearer ${pollToken}`);
  100. assert.ok(options?.signal);
  101. if (request.method === "POST") {
  102. assert.deepEqual(JSON.parse(new TextDecoder().decode(request.body)), {
  103. provider: providerId,
  104. });
  105. return response({
  106. flow_id: "flow/with space",
  107. authorize_url: authorizeUrl,
  108. expires_at: now / 1000 + 120,
  109. poll_interval_sec: 1,
  110. });
  111. }
  112. assert.match(request.url, /\/oauth\/cli\/poll\/flow%2Fwith%20space$/);
  113. return f.poll(options?.signal);
  114. },
  115. };
  116. f.options = {
  117. env,
  118. credentialStore: store,
  119. providerId,
  120. httpClient,
  121. noBrowser: true,
  122. pollToken,
  123. now: () => now,
  124. sleep: async (ms) => {
  125. sleeps.push(ms);
  126. now += ms;
  127. },
  128. // OAuth 登录只解析项目访问材料,不再落盘派生 API Key(staging 9af2a442d3 改为请求期换取 Token)。
  129. apiKeyResolver: {
  130. async resolveMaterial(input, options) {
  131. assert.equal(input.family, providerId);
  132. assert.equal(
  133. input.accessToken,
  134. providerId === "zai" ? "test-oauth-token" : "test-business-token",
  135. );
  136. assert.ok(options?.signal);
  137. return TEST_PROJECT_MATERIAL;
  138. },
  139. } as unknown as LoginZCodeCliOptions["apiKeyResolver"],
  140. };
  141. return f;
  142. }
  143. for (const providerId of ["zai", "bigmodel"] as const) {
  144. test(`${providerId} browser polling persists credentials and refreshes the running Registry`, async (t) => {
  145. const f = await fixture(t, providerId);
  146. const runtime = await startProcessProviderRegistryRuntime(f.env, {
  147. standalone: { credentialStore: f.store },
  148. });
  149. t.after(() => runtime.dispose());
  150. const configured = await resolveStandaloneCodingPlanProvider(providerId, f.env);
  151. assert.equal(runtime.runtime.registryService.getProvider(configured.providerId), undefined);
  152. let attempts = 0;
  153. f.poll = async () => {
  154. attempts++;
  155. if (attempts === 1) return response({ status: "pending" });
  156. if (attempts === 2) throw new TypeError("test temporary network error");
  157. if (attempts === 3)
  158. return { ...response(null, 503), body: new TextEncoder().encode("unavailable") };
  159. if (attempts === 4) return response(null, 429);
  160. return response(ready(providerId));
  161. };
  162. const result =
  163. providerId === "bigmodel"
  164. ? await loginBigmodelCodingPlan(f.options)
  165. : await loginZCodeCli(f.options);
  166. assert.equal(result.providerId, providerId);
  167. assert.equal(result.user.user_id, "test-account");
  168. assert.equal(attempts, 5);
  169. assert.deepEqual(f.sleeps, [1000, 1000, 1000, 1000]);
  170. assert.equal(await f.store.load(keys.zcodeJwtToken), "test-backend-jwt");
  171. // Z.ai 以账号用户 ID 为连接身份;BigModel 以组织与项目的稳定摘要为连接身份。
  172. const expectedIdentity =
  173. providerId === "zai"
  174. ? "test-account"
  175. : createStandaloneAccountIdentityFromSecret(
  176. JSON.stringify([TEST_PROJECT_MATERIAL.organizationId, TEST_PROJECT_MATERIAL.projectId]),
  177. );
  178. assert.equal(
  179. await f.store.load(standaloneAccountIdentityCredentialKey(configured.providerId)),
  180. expectedIdentity,
  181. );
  182. assert.equal(
  183. await f.store.load(standaloneAccountAuthSourceCredentialKey(configured.providerId)),
  184. "oauth",
  185. );
  186. assert.equal(
  187. await f.store.load(
  188. standaloneAccountProviderCredentialKey({
  189. providerId: configured.providerId,
  190. accountIdentity: expectedIdentity,
  191. }),
  192. ),
  193. null,
  194. );
  195. assert.ok(runtime.runtime.registryService.getProvider(configured.providerId)?.models.length);
  196. assert.deepEqual(await runtime.modelSelectionConfigRepository.read(), {
  197. providerId: configured.providerId,
  198. modelId: configured.modelId,
  199. });
  200. if (providerId === "bigmodel")
  201. assert.equal(await f.store.load(keys.bigmodelRefreshToken), "test-refresh-token");
  202. });
  203. }
  204. test("OAuth init does not require an echoed poll secret and accepts both BigModel token spellings", async () => {
  205. for (const token of [
  206. { access_token: "token", refresh_token: "refresh" },
  207. { accessToken: "token", refreshToken: "refresh" },
  208. ]) {
  209. const client = createCliOAuthClient({
  210. providerId: "bigmodel",
  211. httpClient: {
  212. async request(request) {
  213. return request.method === "POST"
  214. ? response({
  215. flow_id: "flow",
  216. authorize_url: authorizeUrl,
  217. expires_at: 12345,
  218. poll_interval_sec: 1,
  219. })
  220. : response({ ...ready("bigmodel"), bigmodel: token });
  221. },
  222. },
  223. });
  224. assert.equal(Object.hasOwn(await client.init({ pollToken }), "poll_token"), false);
  225. const result = await client.poll({ flowId: "flow", pollToken });
  226. assert.equal(result.status, "ready");
  227. if (result.status === "ready") assert.equal(result.refreshToken, "refresh");
  228. }
  229. });
  230. for (const failure of ["failed", "unauthorized", "malformed"] as const) {
  231. test(`terminal polling failure ${failure} does not write credentials or retry`, async (t) => {
  232. const f = await fixture(t);
  233. f.poll = async () =>
  234. failure === "unauthorized"
  235. ? response(null, 401)
  236. : response(
  237. failure === "failed" ? { status: "failed" } : { ...ready("bigmodel"), bigmodel: {} },
  238. );
  239. await assert.rejects(loginBigmodelCodingPlan(f.options));
  240. assert.equal(await f.store.load(keys.activeProvider), null);
  241. assert.equal(f.sleeps.length, 0);
  242. });
  243. }
  244. test("cancelling in-flight polling ignores a late ready response", { timeout: 2000 }, async (t) => {
  245. const f = await fixture(t);
  246. const controller = new AbortController();
  247. let finish!: (data: HttpClientResponse) => void;
  248. let started!: () => void;
  249. const polling = new Promise<void>((resolve) => {
  250. started = resolve;
  251. });
  252. let requestSignal: AbortSignal | undefined;
  253. f.poll = (signal) => {
  254. requestSignal = signal;
  255. started();
  256. return new Promise((resolve) => {
  257. finish = resolve;
  258. });
  259. };
  260. const login = loginBigmodelCodingPlan({ ...f.options, abortSignal: controller.signal });
  261. await polling;
  262. controller.abort(new Error("test login cancelled"));
  263. await assert.rejects(login, /test login cancelled/);
  264. assert.equal(requestSignal?.aborted, true);
  265. finish(response(ready("bigmodel")));
  266. await Promise.resolve();
  267. assert.equal(await f.store.load(keys.activeProvider), null);
  268. });
  269. test("login timeout interrupts an unresponsive transport", { timeout: 2000 }, async (t) => {
  270. const f = await fixture(t);
  271. f.poll = () => new Promise(() => {});
  272. await assert.rejects(loginBigmodelCodingPlan({ ...f.options, timeoutMs: 30 }), {
  273. code: "auth_timeout",
  274. });
  275. assert.equal(await f.store.load(keys.activeProvider), null);
  276. });
  277. test("a response received after flow expiry is not persisted", async (t) => {
  278. const f = await fixture(t);
  279. f.poll = async () => {
  280. f.advance(121_000);
  281. return response(ready("bigmodel"));
  282. };
  283. await assert.rejects(loginBigmodelCodingPlan(f.options), { code: "auth_timeout" });
  284. assert.equal(await f.store.load(keys.activeProvider), null);
  285. });
  286. test("cancellation during API key resolution does not save the login", async (t) => {
  287. const f = await fixture(t);
  288. const controller = new AbortController();
  289. await assert.rejects(
  290. loginBigmodelCodingPlan({
  291. ...f.options,
  292. abortSignal: controller.signal,
  293. apiKeyResolver: {
  294. async resolveMaterial() {
  295. controller.abort(new Error("cancel before save"));
  296. return TEST_PROJECT_MATERIAL;
  297. },
  298. } as unknown as LoginZCodeCliOptions["apiKeyResolver"],
  299. }),
  300. /cancel before save/,
  301. );
  302. assert.equal(await f.store.load(keys.activeProvider), null);
  303. });
  304. test("browser failure keeps authorization URL available and polling completes", async (t) => {
  305. const f = await fixture(t);
  306. let shown = "";
  307. const result = await loginBigmodelCodingPlan({
  308. ...f.options,
  309. noBrowser: false,
  310. onAuthorizeUrl: (data) => {
  311. shown = data.authorize_url;
  312. },
  313. openBrowser: async () => ({
  314. command: "test-open",
  315. opened: false,
  316. reason: "test headless host",
  317. }),
  318. });
  319. assert.equal(shown, authorizeUrl);
  320. assert.equal(result.browser?.opened, false);
  321. });
  322. test(
  323. "TUI renders the login URL in the current session and refreshes models after authorization",
  324. { timeout: 5000 },
  325. async (t) => {
  326. const f = await fixture(t);
  327. const runtime = await startProcessProviderRegistryRuntime(f.env, {
  328. standalone: { credentialStore: f.store },
  329. });
  330. let authorize!: () => void;
  331. const authorization = new Promise<void>((resolve) => {
  332. authorize = resolve;
  333. });
  334. let urlShown!: () => void;
  335. const authorizationShown = new Promise<void>((resolve) => {
  336. urlShown = resolve;
  337. });
  338. f.poll = async () => {
  339. await authorization;
  340. return response(ready("bigmodel"));
  341. };
  342. const app = {
  343. sessionId: "login-session",
  344. traceId: "login-trace",
  345. getModel: () => "",
  346. getLocale: () => "en-US",
  347. listModels: () => listRegistryBackedModels(runtime.runtime.registryService),
  348. listThoughtLevels: () => [],
  349. } as unknown as CommandCenterApp;
  350. const handler = createTuiSubmitPrompt(
  351. {
  352. env: f.env,
  353. cwd: () => process.cwd(),
  354. skipUserConfig: true,
  355. loadDotenv: () => ({ keys: [], loaded: false, path: "" }),
  356. createZCodeApp: async () => app,
  357. startProcessProviderRegistryRuntime: async () => runtime,
  358. loginBigmodelCodingPlan: (options: Parameters<typeof loginBigmodelCodingPlan>[0]) =>
  359. loginBigmodelCodingPlan({
  360. ...f.options,
  361. ...options,
  362. onAuthorizeUrl: async (data) => {
  363. await options?.onAuthorizeUrl?.(data);
  364. urlShown();
  365. },
  366. }),
  367. } as unknown as RunDependencies,
  368. createCliModeState(),
  369. "test",
  370. );
  371. t.after(() => handler.close?.());
  372. const React = await import("react");
  373. const { createTestRenderer } = await import("@mbears/opentui-core/testing");
  374. const { createRoot } = await import("@mbears/opentui-react");
  375. const { CodeRenderable } = await import("@mbears/opentui-core");
  376. const { TuiApp } = await import("../../tui/src/app.js");
  377. const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
  378. const previous = environment.IS_REACT_ACT_ENVIRONMENT;
  379. environment.IS_REACT_ACT_ENVIRONMENT = true;
  380. const terminal = await createTestRenderer({
  381. width: 120,
  382. height: 45,
  383. screenMode: "alternate-screen",
  384. useThread: false,
  385. });
  386. const root = createRoot(terminal.renderer);
  387. let loginCompletion: ReturnType<typeof handler> | undefined;
  388. const seenEvents: SessionEvent[] = [];
  389. const options: TuiOptions = {
  390. noColor: true,
  391. stdin: process.stdin,
  392. stdout: process.stdout,
  393. stderr: process.stderr,
  394. getMainSessionId: () => app.sessionId,
  395. locale: "en-US",
  396. submitPrompt: (input, options) => {
  397. loginCompletion = handler(input, {
  398. ...options,
  399. onEvent: async (event) => {
  400. seenEvents.push(event);
  401. await options.onEvent?.(event);
  402. },
  403. });
  404. return loginCompletion;
  405. },
  406. ...(await handler.getSessionMetadata!()),
  407. listModelOptions: handler.listModelOptions,
  408. };
  409. const action = async (run: () => void | Promise<void>) => {
  410. await React.act(async () => {
  411. await run();
  412. });
  413. const waitForHighlights = async (node: typeof terminal.renderer.root): Promise<void> => {
  414. if (node instanceof CodeRenderable) await node.highlightingDone;
  415. await Promise.all(
  416. node.getChildren().map((child) => waitForHighlights(child as typeof node)),
  417. );
  418. };
  419. await React.act(async () => {
  420. await terminal.renderOnce();
  421. await waitForHighlights(terminal.renderer.root);
  422. await terminal.renderOnce();
  423. });
  424. };
  425. try {
  426. await action(() =>
  427. root.render(
  428. React.createElement(TuiApp, {
  429. options,
  430. onExit() {},
  431. hasCopyableSelection: () => false,
  432. copySelection: async () => ({ kind: "empty" as const }),
  433. }),
  434. ),
  435. );
  436. await action(() => terminal.mockInput.typeText("/login bigmodel-coding-plan"));
  437. await action(async () => {
  438. terminal.mockInput.pressEnter();
  439. await authorizationShown;
  440. });
  441. assert.equal(seenEvents.length, 1);
  442. assert.equal(seenEvents[0]!.sessionId, app.sessionId);
  443. assert.match(terminal.captureCharFrame(), /login\.example\.test\/authorize/);
  444. assert.doesNotMatch(terminal.captureCharFrame(), /test-private-poll-token/);
  445. // Waiting for the actual command completion also waits for credential and Registry barriers.
  446. await action(async () => {
  447. authorize();
  448. await loginCompletion;
  449. });
  450. await action(() => terminal.mockInput.typeText("/model"));
  451. assert.match(terminal.captureCharFrame(), /GLM-/);
  452. assert.doesNotMatch(terminal.captureCharFrame(), /No available models/);
  453. } finally {
  454. await action(async () => {
  455. authorize();
  456. await loginCompletion;
  457. });
  458. await React.act(() => root.unmount());
  459. terminal.renderer.destroy();
  460. if (previous === undefined) delete environment.IS_REACT_ACT_ENVIRONMENT;
  461. else environment.IS_REACT_ACT_ENVIRONMENT = previous;
  462. }
  463. },
  464. );
  465. test("standalone login accepts provider selection and keeps authorization URL out of JSON stdout", async () => {
  466. let stdout = "";
  467. let stderr = "";
  468. let selected = "";
  469. const deps = {
  470. env: {},
  471. cwd: () => process.cwd(),
  472. loadDotenv: () => ({ keys: [], loaded: false, path: "" }),
  473. loginZCodeCli: async (options: LoginZCodeCliOptions) => {
  474. selected = options.providerId!;
  475. assert.equal(options.noBrowser, true);
  476. await options.onAuthorizeUrl?.({
  477. authorize_url: authorizeUrl,
  478. expires_at: 12345,
  479. flow_id: "flow",
  480. poll_interval_sec: 1,
  481. });
  482. return {
  483. providerId: "bigmodel",
  484. user: { user_id: "test-account" },
  485. model: "provider/model",
  486. configPath: "test-config",
  487. credentialsPath: "test-credentials",
  488. };
  489. },
  490. } as unknown as RunDependencies;
  491. const context = {
  492. stdout: {
  493. write: (text: string) => {
  494. stdout += text;
  495. },
  496. },
  497. stderr: {
  498. write: (text: string) => {
  499. stderr += text;
  500. },
  501. },
  502. } as unknown as Parameters<typeof runLoginCommand>[0];
  503. const options = { json: true } as Parameters<typeof runLoginCommand>[1];
  504. assert.equal(await runLoginCommand(context, options, deps, true, ["bigmodel"]), 0);
  505. assert.equal(selected, "bigmodel");
  506. assert.equal(JSON.parse(stdout).provider, "bigmodel");
  507. assert.match(stderr, /login\.example\.test/);
  508. assert.doesNotMatch(stdout, /authorize/);
  509. });