GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(auth): implement timeout for browser opener and enhance error ha… · modelstudioai/cli@255a28d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs/agents
    • auth-change.md
  • packages/commands
    • src/commands
      • auth
        • login-openapi-guide.ts
        • login.ts
      • shared
        • local-server.ts
    • tests
      • auth-login-openapi-site.test.ts
      • local-server-open-path.test.ts
      • login-openapi-guide.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/agents/auth-change.md‎

Copy file name to clipboardExpand all lines: docs/agents/auth-change.md
+4-2Lines changed: 4 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,10 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx
4040
- `bl auth login --api-key ...` 先通过只读 `GET /models` 校验 Key,校验成功后才原子写入 `api_key` 与实际匹配的 `base_url`。公共 DashScope 站点使用 `/api/v1/models?page_no=1&page_size=1`,`*.maas.aliyuncs.com`(Workspace 与 Token Plan)使用 `/compatible-mode/v1/models`。显式 `--base-url` 只校验该站点,不自动改写;未显式指定时,普通 `sk-*` / `sk-ws-*` 按“当前 Profile 已保存的同类站点 → 基于 `workspace_id` 构造的各地域 Workspace 专属站点 → 公共地域”顺序选择首个成功结果,`sk-sp-*` 并行探测国内站与新加坡 Token Plan,其他格式同时尝试两类候选。所有候选失败时选择最有诊断价值的原始错误透传:无 HTTP status 的网络、超时或响应解析错误优先,其次为 HTTP 429/5xx,最后为其他 HTTP 错误;同级保持候选顺序。HTTP status、API code、request ID 与服务端 message 保持不变,不重新分类为 `AUTH`。任一失败都不落盘、不激活 Profile
4141
- 未显式传 `--config` 时,`sk-sp-*` 自动写入并激活 `token-plan`;普通 `sk-*` / `sk-ws-*` 仅在当前为 `token-plan` 时改写并激活 `default`,否则保留当前 Profile;其他格式不自动切换。显式 `--config` 始终优先。`sk-sp-*` 无论写入哪个 Profile 都会携带 Token Plan 的预设默认模型,并在保留已有项的基础上补齐 `api_key_capabilities`,不自动删除任何已有能力。登录仍不得删除其他鉴权域的凭证
4242
- `bl auth login --console` 更新 `access_token` 以及回调携带的 console 作用域字段;若所选 Profile 没有模型 API Key,会要求控制台页面创建并回传一个普通 API Key 与 Base URL 一并保存。该回调结果不重复执行 `/models` 校验,且不会创建或配置 Token Plan
43-
- `bl auth login --open-api` **不带** AK/SK:打开控制台 `/aksk-guide` 浏览器引导(不等浏览器回传、不启本地 callback;SecretKey 不会经页面回传)。会等待打开器进程返回,但 URL 与粘贴命令在此之前已打印——打开器挂起(Linux `xdg-open` 可能阻塞到浏览器退出)不得推迟可操作输出,顺序规则与 `login-console.ts`「先注册回调再打开」一致。支持 `--no-browser` 只打印 URL,以及 `--console-site` 选择国内/国际站。粘贴命令**无条件回显**引导页实际使用的 `--console-site`(含显式 `domestic`,否则 Profile 的 `console_site` 会覆盖用户意图)与按 `recoveryConfigName` 解析出的 `--config`,使粘贴回来等价于「引导页站点 + 目标 Profile」;浏览器自动打开失败时文案不得宣称「已打开」,且不得与警告重复同一句「请手动打开上方地址」,exit 仍为 0
44-
- `bl auth login --open-api --access-key-id … --access-key-secret …`:调用 OpenAPI 生成 CLI `access_token`,通过目标 Console 网关的只读 `loginInfo` 校验后,才一并写入 `access_key_id` / `access_key_secret` / `access_token` 和实际 `console_region` / `console_site`;失败不覆盖原凭证、不激活 Profile。一次成功登录同时产生 `openapi` 与 `console` 域凭证。`--console-site` 在 guide 与带 AK/SK 落盘路径均可用
43+
- `bl auth login --open-api` **不带** AK/SK:打开控制台 `/aksk-guide` 浏览器引导(不等浏览器回传、不启本地 callback;SecretKey 不会经页面回传)。URL 与粘贴命令必须在等待打开器之前打印(顺序规则与 `login-console.ts`「先注册回调再打开」一致),并且这条等待**由引导自己选择上限**:`openInBrowser(url, { timeoutMs: 5000 })`——Linux `xdg-open` 在部分桌面会挂到浏览器退出,不设上限就会占住终端、用户无法粘贴后续命令。被上限杀掉归类为「未确认」(`isOpenPathTimeout`),文案不得说成失败,也不得宣称「已打开」;结果文案不得与警告重复同一句「请手动打开上方地址」;exit 仍为 0。支持 `--no-browser` 只打印 URL,以及 `--console-site` 选择国内/国际站。粘贴命令**无条件回显**引导页实际使用的 `--console-site`(含显式 `domestic`)与按 `recoveryConfigName` 解析出的 `--config`,使粘贴回来等价于「引导页站点 + 目标 Profile」
44+
- `shared/local-server.ts` 的 `openPath` / `openInBrowser`:**等待上限是 opt-in,默认不设 `timeout`**。这条是硬约束,不要改成全局默认——`config/ui.ts` 的 `/api/agent/open`、`/api/asset/open` 把 reject 映射成 HTTP 400,`config ui` 启动与 `login-console.ts` 把 reject 说成「无法打开默认浏览器」;给它们加默认上限会把「已经打开但慢」误报成失败。要上限的调用方显式传 `timeoutMs`,并**必须**用 `isOpenPathTimeout(error)` 分支出「未确认」。上限生效靠的是到点 `SIGTERM` 杀掉子进程:`child.unref()` 单独不够,`execFile` 的 stdout/stderr 管道句柄仍会 ref 住事件循环(实测仍等满)
45+
- `bl auth login --open-api --access-key-id … --access-key-secret …`:调用 OpenAPI 生成 CLI `access_token`,通过目标 Console 网关的只读 `loginInfo` 校验后,才一并写入 `access_key_id` / `access_key_secret` / `access_token` 和实际 `console_region` / `console_site`;失败不覆盖原凭证、不激活 Profile。一次成功登录同时产生 `openapi` 与 `console` 域凭证。`--console-site` 在 guide 与带 AK/SK 落盘路径均可用,且落盘路径必须尊重它:`resolveCLIAccessTokenTarget` / `generateCLIAccessToken` / `validateConsoleAccessToken` 三跳都要用同一个由 `flags.consoleSite || settings.consoleSite || "domestic"` 解析出的站点(`generateCLIAccessToken` 内部会重算 target,漏一跳就回到旧值)。`region × site` 在 `console/gateway.ts` 是二维合法表,无需联动改 region
46+
- **命令自有 flag 与 `settings` 的同名字段**:`create-cli.ts` 只把全局 flag 与凭证域 flag(`GLOBAL_FLAGS` + `credentialFlagDefs(cmd)`)放进 `sources`,命令 `flags` map 里声明的键只进 `ctx.flags`。因此 `auth: "none"` 这类命令里,`settings.<field>` **读不到用户传的 flag**,而 `validate()` 收到的是 `ctx.flags`——于是出现「校验放行、执行时静默忽略」的窗口。凡是 run 里要用到命令自有 flag,必须显式 `flags.X || settings.X`,不得只读 `settings.X`;新增这类 flag 时补一条「flag 与 Profile 默认值不一致时以 flag 为准」的用例(`tests/auth-login-openapi-site.test.ts` 是模板)。`--dry-run` 提前 return 的分支不会覆盖这类缺陷,不能作为「flag 生效」的证据
4547
- `auth status` 未配置 OpenAPI 时提示:先 `auth login --open-api` 按引导获取 AccessKey;若已有则用 `--access-key-id` / `--access-key-secret` 直接配置。缺凭证的 AUTH hint 同样指向 `auth login --open-api`,并保留成对 flag / env 说明
4648
- `bl auth logout --console` 只清 `access_token`
4749
- `bl auth logout --open-api` 只清 `access_key_id` / `access_key_secret` / `security_token`
Collapse file

‎packages/commands/src/commands/auth/login-openapi-guide.ts‎

Copy file name to clipboardExpand all lines: packages/commands/src/commands/auth/login-openapi-guide.ts
+32-8Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import { formatCommand, type Identity, type LocalizedText } from "bailian-cli-core";
22
import { akskGuidePage } from "bailian-cli-runtime";
3-
import { openInBrowser } from "../shared/local-server.ts";
3+
import { isOpenPathTimeout, openInBrowser } from "../shared/local-server.ts";
44
import { resolveConsoleOrigin, type LoginDeps } from "./login-console.ts";
55

6+
/**
7+
* How long this guide may wait on the OS opener before calling the outcome
8+
* unconfirmed. The command prints a paste-ready follow-up command and must hand the
9+
* prompt back for it, so it opts into a cap that other `openPath` callers do not pay.
10+
*/
11+
const OPEN_WAIT_CAP_MS = 5_000;
12+
613
export interface OpenApiGuideOptions {
714
site?: string;
815
/** Profile name to echo as `--config` in the paste-ready command. */
@@ -47,6 +54,11 @@ export function openApiPasteCommand(identity: Identity, options: OpenApiPasteOpt
4754
* before awaiting the opener, so a slow or hanging `open` / `xdg-open` never withholds
4855
* what the user needs to act on — the same ordering rule `login-console.ts` follows by
4956
* registering the callback before opening the browser.
57+
*
58+
* The wait is capped via `openInBrowser(url, { timeoutMs })`: on desktops where
59+
* `xdg-open` stays attached to the browser, an uncapped await would keep the prompt
60+
* away and the user could not paste the follow-up command. An opener killed at that
61+
* cap is an unconfirmed outcome — never reported as a failure, never as a success.
5062
*/
5163
export async function runOpenApiGuide(
5264
deps: LoginDeps,
@@ -75,15 +87,27 @@ export async function runOpenApiGuide(
7587
let browserOpened = false;
7688
if (!options.noBrowser) {
7789
try {
78-
await openInBrowser(url);
90+
await openInBrowser(url, { timeoutMs: OPEN_WAIT_CAP_MS });
7991
browserOpened = true;
8092
} catch (error: unknown) {
81-
deps.output.warning(
82-
localizeGuide(deps, {
83-
"en-US": `Could not open a browser automatically (${error instanceof Error ? error.message : String(error)}). Open the URL above manually.`,
84-
"zh-CN": `无法自动打开浏览器(${error instanceof Error ? error.message : String(error)})。请手动打开上方地址。`,
85-
}),
86-
);
93+
if (isOpenPathTimeout(error)) {
94+
deps.output.warning(
95+
localizeGuide(deps, {
96+
"en-US":
97+
"Could not confirm the browser opened: the system open command did not return in time. Open the URL above manually if no tab appeared.",
98+
"zh-CN":
99+
"未能确认浏览器是否打开:系统打开命令超时未返回。若没有新标签页,请手动打开上方地址。",
100+
}),
101+
);
102+
} else {
103+
const reason = error instanceof Error ? error.message : String(error);
104+
deps.output.warning(
105+
localizeGuide(deps, {
106+
"en-US": `Could not open a browser automatically (${reason}). Open the URL above manually.`,
107+
"zh-CN": `无法自动打开浏览器(${reason})。请手动打开上方地址。`,
108+
}),
109+
);
110+
}
87111
}
88112
}
89113

Collapse file

‎packages/commands/src/commands/auth/login.ts‎

Copy file name to clipboardExpand all lines: packages/commands/src/commands/auth/login.ts
+14-3Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -362,21 +362,32 @@ export default defineCommand({
362362
return;
363363
}
364364
const resolvedBaseUrl = store.resolveBaseUrl();
365-
const target = resolveCLIAccessTokenTarget(settings, resolvedBaseUrl);
365+
// `--console-site` is a command-own flag: create-cli routes only global and
366+
// credential-domain flags into `sources`, so it never reaches `settings` for this
367+
// command (auth: "none"). Reading `settings.consoleSite` alone silently ignored the
368+
// flag — a new Profile asked for international saved domestic, and an international
369+
// Profile asked for domestic saved international. Honour the flag exactly like the
370+
// guide branch above already does, and reuse the same value for every hop:
371+
// generateCLIAccessToken re-derives the target from `settings` internally.
372+
const effectiveSettings = {
373+
...settings,
374+
consoleSite: site as "domestic" | "international",
375+
};
376+
const target = resolveCLIAccessTokenTarget(effectiveSettings, resolvedBaseUrl);
366377
ctx.output.progress({
367378
"en-US": "Generating CLI access token...",
368379
"zh-CN": "正在生成 CLI access token...",
369380
});
370381
const resp = await generateCLIAccessToken({
371382
identity,
372-
settings,
383+
settings: effectiveSettings,
373384
debug: (record) => ctx.output.debug(record),
374385
baseUrl: resolvedBaseUrl,
375386
accessKeyId: flags.accessKeyId!,
376387
accessKeySecret: flags.accessKeySecret!,
377388
});
378389
const accessToken = resp.cliAccessToken;
379-
await validateConsoleAccessToken({ ...target, token: accessToken }, settings, {
390+
await validateConsoleAccessToken({ ...target, token: accessToken }, effectiveSettings, {
380391
debug: (record) => ctx.output.debug(record),
381392
});
382393
await store.login({
Collapse file

‎packages/commands/src/commands/shared/local-server.ts‎

Copy file name to clipboardExpand all lines: packages/commands/src/commands/shared/local-server.ts
+30-3Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,35 @@ export function buildOpenInvocation(target: string, platform = process.platform)
6666
return { command: "xdg-open", args: [target] };
6767
}
6868

69+
export interface OpenPathOptions {
70+
/**
71+
* Kill the opener after this many milliseconds. Left unset, the promise waits as
72+
* long as the OS handler takes — the historical behaviour, and deliberately still
73+
* the default: callers like `config ui` map a rejected opener onto an HTTP 400 or a
74+
* "could not open" warning, so a blanket cap would turn "slow but already opened"
75+
* into a false failure. Callers that must hand the terminal back pass `timeoutMs`.
76+
*/
77+
timeoutMs?: number;
78+
}
79+
80+
/**
81+
* True when {@link openPath} killed the opener at its own cap, as opposed to the OS
82+
* handler failing. Any caller that sets `timeoutMs` must branch on this, so an
83+
* unconfirmed open is reported as "not confirmed" rather than "could not open".
84+
*/
85+
export function isOpenPathTimeout(error: unknown): boolean {
86+
return error instanceof Error && (error as { killed?: boolean }).killed === true;
87+
}
88+
6989
/**
7090
* Open a local file, directory, or URL with the OS default handler
7191
* (best-effort, cross-platform).
92+
*
93+
* When `timeoutMs` is set the child is killed at the cap. Killing is what releases
94+
* Node's event loop: `child.unref()` alone does not, because `execFile` keeps ref'd
95+
* stdout/stderr pipe handles, so an unref'd opener still delays the prompt.
7296
*/
73-
export function openPath(target: string): Promise<void> {
97+
export function openPath(target: string, options: OpenPathOptions = {}): Promise<void> {
7498
const invocation = buildOpenInvocation(target);
7599
return new Promise((resolve, reject) => {
76100
execFile(
@@ -79,6 +103,9 @@ export function openPath(target: string): Promise<void> {
79103
{
80104
windowsHide: true,
81105
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
106+
...(options.timeoutMs === undefined
107+
? {}
108+
: { timeout: options.timeoutMs, killSignal: "SIGTERM" }),
82109
},
83110
(err) => {
84111
if (err) reject(err);
@@ -89,6 +116,6 @@ export function openPath(target: string): Promise<void> {
89116
}
90117

91118
/** Open a URL in the user's default browser (best-effort, cross-platform). */
92-
export function openInBrowser(url: string): Promise<void> {
93-
return openPath(url);
119+
export function openInBrowser(url: string, options?: OpenPathOptions): Promise<void> {
120+
return openPath(url, options);
94121
}
Collapse file

‎packages/commands/tests/auth-login-openapi-site.test.ts‎

Copy file name to clipboard
+118Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { buildSettings, type AuthStore, type Identity, type LocalizedText } from "bailian-cli-core";
2+
import { expect, test, vi } from "vite-plus/test";
3+
4+
// 换票与控制台校验是这条链路仅有的两处网络出口。mock 掉它们,才能把断言集中在
5+
// 「用户传的 --console-site 最终落到了哪里」,而不是依赖真实 AK/SK。
6+
type ConsoleSite = "domestic" | "international";
7+
type TokenRequest = { settings: { consoleSite?: ConsoleSite }; baseUrl: string };
8+
type GatewayTarget = { region: string; site: ConsoleSite; token: string };
9+
10+
const generateCLIAccessToken = vi.hoisted(() =>
11+
vi.fn<(request: TokenRequest) => Promise<{ cliAccessToken: string }>>(async () => ({
12+
cliAccessToken: "cli-token-fake",
13+
})),
14+
);
15+
const validateConsoleAccessToken = vi.hoisted(() =>
16+
vi.fn<(target: GatewayTarget, settings: unknown, diagnostics: unknown) => Promise<void>>(
17+
async () => undefined,
18+
),
19+
);
20+
21+
vi.mock("bailian-cli-core", async (importOriginal) => {
22+
const actual = await importOriginal<typeof import("bailian-cli-core")>();
23+
return {
24+
...actual,
25+
generateCLIAccessToken: (request: TokenRequest) => generateCLIAccessToken(request),
26+
validateConsoleAccessToken: (target: GatewayTarget, settings: unknown, diagnostics: unknown) =>
27+
validateConsoleAccessToken(target, settings, diagnostics),
28+
};
29+
});
30+
31+
import login from "../src/commands/auth/login.ts";
32+
33+
const identity: Identity = {
34+
binName: "bl",
35+
version: "test",
36+
npmPackage: "bailian-cli",
37+
clientName: "bailian-cli-test",
38+
};
39+
40+
interface Harness {
41+
savedPatch: Record<string, unknown>;
42+
gatewayTarget: GatewayTarget | undefined;
43+
}
44+
45+
/**
46+
* `--console-site` 是命令自有 flag:create-cli 只把全局 flag 与凭证域 flag 放进
47+
* sources,所以它永远进不了 `settings`。落盘链路必须自己尊重 `ctx.flags`,
48+
* 否则会出现「新 Profile 传 international 存成 domestic」这类静默忽略。
49+
*/
50+
async function runPersist(
51+
flagSite: ConsoleSite | undefined,
52+
settingsSite: ConsoleSite | undefined,
53+
): Promise<Harness> {
54+
generateCLIAccessToken.mockClear();
55+
validateConsoleAccessToken.mockClear();
56+
const savedPatch: Record<string, unknown> = {};
57+
58+
const store = {
59+
path: "/tmp/unused/config.json",
60+
resolveBaseUrl: () => "https://dashscope.aliyuncs.com/compatible-mode/v1",
61+
stored: () => ({}),
62+
async login(patch: Record<string, unknown>) {
63+
Object.assign(savedPatch, patch);
64+
},
65+
} as unknown as AuthStore;
66+
67+
const settings = {
68+
...buildSettings({ flags: {}, file: {}, env: {} }),
69+
consoleSite: settingsSite,
70+
};
71+
const flags = {
72+
openApi: true,
73+
accessKeyId: "LTAI-fake",
74+
accessKeySecret: "secret-fake",
75+
...(flagSite === undefined ? {} : { consoleSite: flagSite }),
76+
};
77+
78+
await login.run({
79+
identity,
80+
settings,
81+
flags,
82+
authStore: store,
83+
localize: (text: LocalizedText) => (typeof text === "string" ? text : text["en-US"]),
84+
output: {
85+
info: () => undefined,
86+
warning: () => undefined,
87+
progress: () => undefined,
88+
result: () => undefined,
89+
debug: () => undefined,
90+
},
91+
} as never);
92+
93+
return { savedPatch, gatewayTarget: validateConsoleAccessToken.mock.calls[0]?.[0] };
94+
}
95+
96+
test("显式 --console-site international 落到新 Profile(settings 里什么都没有)", async () => {
97+
const { savedPatch, gatewayTarget } = await runPersist("international", undefined);
98+
expect(savedPatch.console_site).toBe("international");
99+
expect(gatewayTarget?.site).toBe("international");
100+
});
101+
102+
test("显式 --console-site domestic 覆盖 Profile 里已存的 international", async () => {
103+
const { savedPatch, gatewayTarget } = await runPersist("domestic", "international");
104+
expect(savedPatch.console_site).toBe("domestic");
105+
expect(gatewayTarget?.site).toBe("domestic");
106+
});
107+
108+
test("不传 --console-site 时仍沿用 Profile 默认", async () => {
109+
const { savedPatch, gatewayTarget } = await runPersist(undefined, "international");
110+
expect(savedPatch.console_site).toBe("international");
111+
expect(gatewayTarget?.site).toBe("international");
112+
});
113+
114+
test("换票请求也使用被覆盖后的站点(generateCLIAccessToken 内部会重算 target)", async () => {
115+
await runPersist("domestic", "international");
116+
const request = generateCLIAccessToken.mock.calls[0]?.[0];
117+
expect(request?.settings.consoleSite).toBe("domestic");
118+
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.