From e280bba7e71f033b1dfe1d819c96fbaa517d5d59 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Wed, 18 Nov 2026 14:06:51 +0800 Subject: [PATCH 1/4] feat(auth): add open-api browser guide and polish AccessKey setup copy - `bl auth login --open-api` without AK/SK opens the console `/aksk-guide` page (non-blocking, no local callback) and tells users to paste credentials back in the terminal afterward. Passing `--access-key-id` / `--access-key-secret` still validates and saves as before. - Also tighten guide/`auth status`/AUTH hint wording to remove the redundant "not configured" message, and sync README, skill setup, and auth docs. --- README.md | 6 +- README.zh.md | 6 +- docs/agents/auth-change.md | 4 +- packages/cli/README.md | 6 +- packages/cli/README.zh.md | 6 +- .../src/commands/auth/login-openapi-guide.ts | 69 +++++++++++ packages/commands/src/commands/auth/login.ts | 107 +++++++++++++++--- packages/commands/src/commands/auth/status.ts | 11 +- packages/commands/tests/e2e/auth.e2e.test.ts | 57 +++++++++- packages/runtime/src/error-handler.ts | 4 +- packages/runtime/src/index.ts | 2 + packages/runtime/src/urls.ts | 8 ++ .../tests/command-reference-output.test.ts | 9 +- skills/bailian-cli/reference/auth.md | 24 ++-- skills/bailian-protocol/assets/setup.md | 12 +- 15 files changed, 286 insertions(+), 45 deletions(-) create mode 100644 packages/commands/src/commands/auth/login-openapi-guide.ts diff --git a/README.md b/README.md index 29649b765..6d84cd754 100644 --- a/README.md +++ b/README.md @@ -228,11 +228,15 @@ Get an ordinary key from the [DashScope Console](https://bailian.console.aliyun. ### Alibaba Cloud OpenAPI AK/SK -Token Plan seat and member management requires an Alibaba Cloud AccessKey. Get yours from the [RAM Console](https://ram.console.aliyun.com/manage/ak). +Token Plan seat/member management and console token refresh need an Alibaba Cloud AccessKey. Run the setup guide, or get keys from the [RAM Console](https://ram.console.aliyun.com/manage/ak) and paste them. > Recommended: create a RAM sub-account with minimum privileges instead of using the root account's AK/SK. ```bash +# Open the setup guide (when finished, paste your AccessKey back in the terminal) +bl auth login --open-api + +# If you already have an AccessKey, configure it directly bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ... ``` diff --git a/README.zh.md b/README.zh.md index de80a6354..aa73c1db2 100644 --- a/README.zh.md +++ b/README.zh.md @@ -227,11 +227,15 @@ bl auth login --api-key ### 阿里云 OpenAPI AK/SK -Token Plan 的席位与成员管理需要阿里云 AccessKey。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。 +Token Plan 的席位与成员管理、以及控制台会话换票需要阿里云 AccessKey。可先运行引导获取,或前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取后粘贴。 > 建议:创建 RAM 子账号并授予最小权限,避免使用主账号 AK/SK。 ```bash +# 打开引导页(按照引导完成操作后,回到命令行粘贴 AccessKey) +bl auth login --open-api + +# 若已有 AccessKey,直接配置 bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ... ``` diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index 99cea7cad..48bbc36c6 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -40,7 +40,9 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - `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 - 未显式传 `--config` 时,`sk-sp-*` 自动写入并激活 `token-plan`;普通 `sk-*` / `sk-ws-*` 仅在当前为 `token-plan` 时改写并激活 `default`,否则保留当前 Profile;其他格式不自动切换。显式 `--config` 始终优先。`sk-sp-*` 无论写入哪个 Profile 都会携带 Token Plan 的预设默认模型,并在保留已有项的基础上补齐 `api_key_capabilities`,不自动删除任何已有能力。登录仍不得删除其他鉴权域的凭证 - `bl auth login --console` 更新 `access_token` 以及回调携带的 console 作用域字段;若所选 Profile 没有模型 API Key,会要求控制台页面创建并回传一个普通 API Key 与 Base URL 一并保存。该回调结果不重复执行 `/models` 校验,且不会创建或配置 Token Plan -- `bl auth login --open-api ...` 调用 OpenAPI 生成 CLI `access_token`,通过目标 Console 网关的只读 `loginInfo` 校验后,才一并写入 `access_key_id` / `access_key_secret` / `access_token` 和实际 `console_region` / `console_site`;失败不覆盖原凭证、不激活 Profile。一次成功登录同时产生 `openapi` 与 `console` 域凭证 +- `bl auth login --open-api` **不带** AK/SK:打开控制台 `/aksk-guide` 浏览器引导(非阻塞,不启本地 callback;SecretKey 不会经页面回传)。支持 `--no-browser` 只打印 URL,以及 `--console-site` 选择国内/国际站。引导完成后用户自行粘贴 `auth login --open-api --access-key-id … --access-key-secret …` +- `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` 域凭证 +- `auth status` 未配置 OpenAPI 时提示:先 `auth login --open-api` 按引导获取 AccessKey;若已有则用 `--access-key-id` / `--access-key-secret` 直接配置。缺凭证的 AUTH hint 同样指向 `auth login --open-api`,并保留成对 flag / env 说明 - `bl auth logout --console` 只清 `access_token` - `bl auth logout --open-api` 只清 `access_key_id` / `access_key_secret` / `security_token` - `bl auth logout` 清 `api_key` + `base_url` + `access_token` + `access_key_*` diff --git a/packages/cli/README.md b/packages/cli/README.md index 29649b765..6d84cd754 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -228,11 +228,15 @@ Get an ordinary key from the [DashScope Console](https://bailian.console.aliyun. ### Alibaba Cloud OpenAPI AK/SK -Token Plan seat and member management requires an Alibaba Cloud AccessKey. Get yours from the [RAM Console](https://ram.console.aliyun.com/manage/ak). +Token Plan seat/member management and console token refresh need an Alibaba Cloud AccessKey. Run the setup guide, or get keys from the [RAM Console](https://ram.console.aliyun.com/manage/ak) and paste them. > Recommended: create a RAM sub-account with minimum privileges instead of using the root account's AK/SK. ```bash +# Open the setup guide (when finished, paste your AccessKey back in the terminal) +bl auth login --open-api + +# If you already have an AccessKey, configure it directly bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ... ``` diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index de80a6354..aa73c1db2 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -227,11 +227,15 @@ bl auth login --api-key ### 阿里云 OpenAPI AK/SK -Token Plan 的席位与成员管理需要阿里云 AccessKey。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。 +Token Plan 的席位与成员管理、以及控制台会话换票需要阿里云 AccessKey。可先运行引导获取,或前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取后粘贴。 > 建议:创建 RAM 子账号并授予最小权限,避免使用主账号 AK/SK。 ```bash +# 打开引导页(按照引导完成操作后,回到命令行粘贴 AccessKey) +bl auth login --open-api + +# 若已有 AccessKey,直接配置 bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ... ``` diff --git a/packages/commands/src/commands/auth/login-openapi-guide.ts b/packages/commands/src/commands/auth/login-openapi-guide.ts new file mode 100644 index 000000000..8e723b6a3 --- /dev/null +++ b/packages/commands/src/commands/auth/login-openapi-guide.ts @@ -0,0 +1,69 @@ +import { formatCommand, type Identity, type LocalizedText } from "bailian-cli-core"; +import { akskGuidePage } from "bailian-cli-runtime"; +import { openInBrowser } from "../shared/local-server.ts"; +import { resolveConsoleOrigin, type LoginDeps } from "./login-console.ts"; + +export interface OpenApiGuideOptions { + site?: string; + noBrowser?: boolean; +} + +function localizeGuide(deps: LoginDeps, text: LocalizedText): string { + if (typeof text === "string") return text; + return deps.localize ? deps.localize(text) : text["en-US"]; +} + +/** Console URL for the OpenAPI AK/SK browser guide. */ +export function resolveAkskGuideUrl(site?: string): string { + return akskGuidePage(resolveConsoleOrigin(site)); +} + +/** Paste-ready command after the browser guide completes. */ +export function openApiPasteCommand(identity: Identity): string { + return formatCommand( + identity, + "auth login --open-api --access-key-id --access-key-secret ", + ); +} + +/** + * Open (or print) the AK/SK guide page. Does not wait for a callback — SecretKey + * never returns through the browser. + */ +export async function runOpenApiGuide( + deps: LoginDeps, + options: OpenApiGuideOptions = {}, +): Promise<{ url: string }> { + const url = resolveAkskGuideUrl(options.site); + const paste = openApiPasteCommand(deps.identity); + + deps.output.info( + `${localizeGuide(deps, { + "en-US": "Open the following URL in your browser:", + "zh-CN": "请在浏览器中打开以下地址:", + })}\n${url}`, + ); + + if (!options.noBrowser) { + void openInBrowser(url).then( + () => undefined, + (error: unknown) => { + deps.output.warning( + localizeGuide(deps, { + "en-US": `Could not open a browser automatically (${error instanceof Error ? error.message : String(error)}). Open the URL above manually.`, + "zh-CN": `无法自动打开浏览器(${error instanceof Error ? error.message : String(error)})。请手动打开上方地址。`, + }), + ); + }, + ); + } + + deps.output.info( + localizeGuide(deps, { + "en-US": `After finishing the guide, return here and paste your AccessKey:\n ${paste}`, + "zh-CN": `按照引导完成操作后,回到当前命令行粘贴AccessKey:\n ${paste}`, + }), + ); + + return { url }; +} diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index 89d328004..5d43ed870 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -11,6 +11,7 @@ import { } from "bailian-cli-core"; import { persistApiKey, validateApiKey } from "./login-api-key.ts"; import { resolveConsoleOrigin, runConsoleLogin, runConsoleTokenLogin } from "./login-console.ts"; +import { resolveAkskGuideUrl, runOpenApiGuide } from "./login-openapi-guide.ts"; const LOGIN_MODE_HINT = "Choose exactly one login mode: --api-key, --console, or --open-api"; @@ -26,7 +27,7 @@ export default defineCommand({ }, auth: "none", usageArgs: - "--api-key | --console [--no-browser | --token-stdin --console-region ] | --open-api --access-key-id --access-key-secret ", + "--api-key | --console [--no-browser | --token-stdin --console-region ] | --open-api [--no-browser] [--access-key-id --access-key-secret ]", flags: { apiKey: { type: "string", @@ -56,8 +57,9 @@ export default defineCommand({ noBrowser: { type: "switch", description: { - "en-US": "With --console, print the login URL without opening a browser", - "zh-CN": "与 --console 一起使用,只打印登录地址,不自动打开浏览器", + "en-US": + "With --console or --open-api (setup guide), print the URL without opening a browser", + "zh-CN": "与 --console 或 --open-api(配置引导)一起使用,只打印地址,不自动打开浏览器", }, }, tokenStdin: { @@ -85,8 +87,10 @@ export default defineCommand({ openApi: { type: "switch", description: { - "en-US": "Store Alibaba Cloud OpenAPI AK/SK credentials", - "zh-CN": "保存阿里云 OpenAPI AK/SK 凭证", + "en-US": + "Open the AccessKey setup guide, or save keys when --access-key-id and --access-key-secret are both set", + "zh-CN": + "打开 AccessKey 配置引导;同时提供 --access-key-id 与 --access-key-secret 时则校验并保存", }, }, accessKeyId: { @@ -111,15 +115,26 @@ export default defineCommand({ "--console --no-browser --console-site international", "--console --token-stdin --console-site international --console-region ap-southeast-1", "--api-key sk-xxxxx", + "--open-api", + "--open-api --no-browser --console-site international", "--open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx", ], validate: (flags) => { const apiKeyMode = hasValue(flags.apiKey); const consoleMode = flags.console === true; const openApiMode = flags.openApi === true; + const openApiHasId = hasValue(flags.accessKeyId); + const openApiHasSecret = hasValue(flags.accessKeySecret); + const openApiPersist = openApiMode && openApiHasId && openApiHasSecret; + const openApiGuide = openApiMode && !openApiHasId && !openApiHasSecret; - if (!consoleMode && (flags.noBrowser || flags.tokenStdin || hasValue(flags.consoleRegion))) { - return "Use --no-browser, --token-stdin and --console-region only with --console. / --no-browser、--token-stdin 和 --console-region 只能与 --console 一起使用。"; + if (flags.tokenStdin || hasValue(flags.consoleRegion)) { + if (!consoleMode) { + return "Use --token-stdin and --console-region only with --console. / --token-stdin 和 --console-region 只能与 --console 一起使用。"; + } + } + if (flags.noBrowser && !consoleMode && !openApiMode) { + return "Use --no-browser with --console or --open-api. / --no-browser 只能与 --console 或 --open-api 一起使用。"; } if (flags.noBrowser && flags.tokenStdin) { return "Choose either --no-browser or --token-stdin. / --no-browser 与 --token-stdin 不能同时使用。"; @@ -136,21 +151,23 @@ export default defineCommand({ if (!apiKeyMode && hasValue(flags.baseUrl)) { return "Use --base-url only with --api-key"; } - if (!consoleMode && hasValue(flags.consoleSite)) { - return "Use --console-site only with --console"; + if (hasValue(flags.consoleSite) && !consoleMode && !openApiGuide) { + return "Use --console-site with --console or --open-api (setup guide). / --console-site 只能与 --console 或 --open-api(配置引导)一起使用。"; } - if (!openApiMode && (hasValue(flags.accessKeyId) || hasValue(flags.accessKeySecret))) { + if (!openApiMode && (openApiHasId || openApiHasSecret)) { return "Use --open-api with --access-key-id and --access-key-secret"; } + if (openApiMode && flags.noBrowser && openApiPersist) { + return "Use --no-browser with --open-api setup guide (omit AK/SK). / --no-browser 只能与 --open-api 配置引导(不带 AK/SK)一起使用。"; + } // Login writes one credential domain per invocation. Multi-mode inputs such // as `--console --api-key` are rejected instead of partly applying one path. const modeCount = [apiKeyMode, consoleMode, openApiMode].filter(Boolean).length; if (modeCount !== 1) return LOGIN_MODE_HINT; - // AK/SK are a credential pair. `auth login --open-api` persists exactly what - // the user typed and does not fill the missing half from env/config. - if (openApiMode && (!hasValue(flags.accessKeyId) || !hasValue(flags.accessKeySecret))) { + // AK/SK are a credential pair. Persist only what the user typed; guide when neither half is set. + if (openApiMode && openApiHasId !== openApiHasSecret) { return "Provide --access-key-id and --access-key-secret with --open-api"; } @@ -258,13 +275,73 @@ export default defineCommand({ } if (flags.openApi) { + const openApiGuide = !hasValue(flags.accessKeyId) && !hasValue(flags.accessKeySecret); + const site = flags.consoleSite || settings.consoleSite || "domestic"; + + if (openApiGuide) { + const guideUrl = resolveAkskGuideUrl(site); + if (settings.dryRun) { + ctx.output.result( + { + action: "auth.login", + method: "open-api-guide", + url: guideUrl, + no_browser: !!flags.noBrowser, + config_file: store.path, + }, + { + text: ctx.localize( + flags.noBrowser + ? { + "en-US": `Would print the AccessKey setup URL without opening a browser:\n${guideUrl}`, + "zh-CN": `将打印 AccessKey 配置地址,不自动打开浏览器:\n${guideUrl}`, + } + : { + "en-US": `Would open the AccessKey setup URL in your browser:\n${guideUrl}`, + "zh-CN": `将在浏览器中打开 AccessKey 配置地址:\n${guideUrl}`, + }, + ), + }, + ); + return; + } + const { url } = await runOpenApiGuide(deps, { + site, + noBrowser: flags.noBrowser, + }); + ctx.output.result( + { + action: "auth.login", + method: "open-api-guide", + url, + no_browser: !!flags.noBrowser, + config: settings.configName ?? "default", + config_file: store.path, + }, + { + text: ctx.localize( + flags.noBrowser + ? { + "en-US": "Browser not opened automatically. Open the URL above manually.", + "zh-CN": "未自动打开浏览器,请手动打开上方地址。", + } + : { + "en-US": "Opened the setup page in your default browser.", + "zh-CN": "已在默认浏览器打开引导页面。", + }, + ), + }, + ); + return; + } + if (settings.dryRun) { ctx.output.result( { action: "auth.login", method: "openapi", config_file: store.path }, { text: ctx.localize({ - "en-US": "Would save OpenAPI AK/SK credentials and generate CLI access token.", - "zh-CN": "将保存 OpenAPI AK/SK 凭证并生成 CLI access token。", + "en-US": "Would save AccessKey credentials and generate a CLI access token.", + "zh-CN": "将保存 AccessKey 凭证并生成 CLI access token。", }), }, ); diff --git a/packages/commands/src/commands/auth/status.ts b/packages/commands/src/commands/auth/status.ts index e03d2f02b..d29a04c71 100644 --- a/packages/commands/src/commands/auth/status.ts +++ b/packages/commands/src/commands/auth/status.ts @@ -56,7 +56,7 @@ export default defineCommand({ hint: [ `API key (model): ${formatCommand(identity, "auth login --api-key ")} or DASHSCOPE_API_KEY`, `Console gateway: ${formatCommand(identity, "auth login --console")}`, - `OpenAPI (AK/SK): ${formatCommand(identity, "auth login --open-api --access-key-id --access-key-secret ")}`, + `OpenAPI (AK/SK): ${formatCommand(identity, "auth login --open-api")} (or paste --access-key-id / --access-key-secret)`, `Get API Key: ${API_KEY_PAGE}`, ].join("\n"), }); @@ -97,9 +97,12 @@ export default defineCommand({ if (openapi) { lines.push(` OpenAPI (AK/SK): ${openapi.source} ${openapi.access_key_id}`); } else { - lines.push( - ` OpenAPI (AK/SK): not configured (run ${formatCommand(identity, "auth login --open-api")})`, - ); + // 与 Console 行一致:状态一行说完,避免再重复 “未配置” + const openApiHint = localize({ + "en-US": `run ${formatCommand(identity, "auth login --open-api")} to get an AccessKey via the guide; if you already have one, configure with ${formatCommand(identity, "auth login --open-api --access-key-id --access-key-secret ")}`, + "zh-CN": `运行 ${formatCommand(identity, "auth login --open-api")} 按照引导获取 AccessKey,若已有 AccessKey,使用 ${formatCommand(identity, "auth login --open-api --access-key-id --access-key-secret ")} 进行配置`, + }); + lines.push(` OpenAPI (AK/SK): not configured (${openApiHint})`); } ctx.output.result( { diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index 3543ab7d4..292e2ff9b 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -116,7 +116,9 @@ describe("e2e: auth", () => { "international", ]); expect(consoleSiteWithoutConsole.exitCode).toBe(2); - expect(consoleSiteWithoutConsole.stderr).toMatch(/Use --console-site only with --console/); + expect(consoleSiteWithoutConsole.stderr).toMatch( + /Use --console-site with --console or --open-api \(setup guide\)/, + ); }); test("auth login --open-api 要求 AK/SK 成对输入", async () => { @@ -131,6 +133,52 @@ describe("e2e: auth", () => { expect(stderr).toMatch(/Provide --access-key-id and --access-key-secret with --open-api/); }); + test("auth login --open-api 无 AK/SK 时走浏览器引导(--no-browser / --dry-run)", async () => { + const configDir = mkdtempSync(join(tmpdir(), "bl-auth-openapi-guide-")); + try { + const dryRun = await runCommandE2e( + AUTH_ROUTES, + ["auth", "login", "--open-api", "--dry-run"], + { BAILIAN_CONFIG_DIR: configDir }, + ); + expect(dryRun.exitCode, dryRun.stderr).toBe(0); + expect(dryRun.stdout).toMatch(/aksk-guide/); + expect(dryRun.stdout).toMatch(/Would open the AccessKey setup URL/); + expect(existsSync(join(configDir, "config.json"))).toBe(false); + + const noBrowser = await runCommandE2e( + AUTH_ROUTES, + ["auth", "login", "--open-api", "--no-browser", "--console-site", "international"], + { BAILIAN_CONFIG_DIR: configDir }, + ); + expect(noBrowser.exitCode, noBrowser.stderr).toBe(0); + expect(noBrowser.stdout + noBrowser.stderr).toMatch( + /modelstudio\.console\.alibabacloud\.com\/aksk-guide/, + ); + expect(noBrowser.stdout + noBrowser.stderr).toMatch( + /auth login --open-api --access-key-id --access-key-secret /, + ); + expect(existsSync(join(configDir, "config.json"))).toBe(false); + + const noBrowserWithKeys = await runCommandE2e(AUTH_ROUTES, [ + "auth", + "login", + "--open-api", + "--no-browser", + "--access-key-id", + "LTAI-e2e", + "--access-key-secret", + "secret-e2e", + ]); + expect(noBrowserWithKeys.exitCode).toBe(2); + expect(noBrowserWithKeys.stderr).toMatch( + /Use --no-browser with --open-api setup guide \(omit AK\/SK\)/, + ); + } finally { + rmSync(configDir, { recursive: true, force: true }); + } + }); + test("auth login --open-api --dry-run 使用 placeholder 时不请求服务端、不写配置", async () => { const configDir = mkdtempSync(join(tmpdir(), "bl-auth-openapi-dry-run-")); try { @@ -156,7 +204,7 @@ describe("e2e: auth", () => { }, ); expect(exitCode, stderr).toBe(0); - expect(stdout).toContain("Would save OpenAPI AK/SK credentials"); + expect(stdout).toContain("Would save AccessKey credentials"); expect(existsSync(join(configDir, "config.json"))).toBe(false); } finally { rmSync(configDir, { recursive: true, force: true }); @@ -1139,6 +1187,11 @@ describe("e2e: auth", () => { expect(text.exitCode, text.stderr).toBe(0); expect(text.stdout).toContain("API key (model): not configured"); expect(text.stdout).toContain("尚未配置模型 API Key"); + expect(text.stdout).toContain("OpenAPI (AK/SK): not configured"); + expect(text.stdout).toContain("bl auth login --open-api"); + expect(text.stdout).toContain( + "bl auth login --open-api --access-key-id --access-key-secret ", + ); }); test("auth logout 清除当前 Config 的全部凭证和 Base URL,保留普通配置", async () => { diff --git a/packages/runtime/src/error-handler.ts b/packages/runtime/src/error-handler.ts index 292817044..6d5ee2846 100644 --- a/packages/runtime/src/error-handler.ts +++ b/packages/runtime/src/error-handler.ts @@ -118,9 +118,9 @@ export function errorHint( case "expired-console-session": return consoleRecoveryHint(commandPrefix, configName); case "missing-openapi-pair": - return `Set BAILIAN_ACCESS_KEY_ID and BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET), pass --access-key-id and --access-key-secret, or run \`${recoveryCommand(commandPrefix, "auth login --open-api", configName)}\`.`; + return `Set BAILIAN_ACCESS_KEY_ID / BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_*), pass --access-key-id / --access-key-secret, or run \`${recoveryCommand(commandPrefix, "auth login --open-api", configName)}\` then paste your AccessKey.`; case "incomplete-openapi-config": - return `Run \`${recoveryCommand(commandPrefix, "auth login --open-api --access-key-id --access-key-secret ", configName)}\` again to save a complete pair.`; + return `Save a complete pair with \`${recoveryCommand(commandPrefix, "auth login --open-api --access-key-id --access-key-secret ", configName)}\`, or run \`${recoveryCommand(commandPrefix, "auth login --open-api", configName)}\` for the setup guide.`; case "incomplete-openapi-flag": case "incomplete-openapi-env": return hint; diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 3c581b292..7d398cfff 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -35,6 +35,8 @@ export { BAILIAN_CONSOLE_ROOT, BAILIAN_CONSOLE, API_KEY_PAGE, + AKSK_GUIDE_PATH, + akskGuidePage, KNOWLEDGE_BILLING_PAGE, TOKEN_PLAN_PAGE, MCP_WEBSEARCH_PAGE, diff --git a/packages/runtime/src/urls.ts b/packages/runtime/src/urls.ts index 6ed664156..524ab1e3a 100644 --- a/packages/runtime/src/urls.ts +++ b/packages/runtime/src/urls.ts @@ -15,6 +15,14 @@ export const BAILIAN_CONSOLE = `${BAILIAN_CONSOLE_ROOT}/cn-beijing`; /** Direct deep link to API key management page. */ export const API_KEY_PAGE = `${BAILIAN_CONSOLE}/?tab=app#/api-key`; +/** OpenAPI AK/SK browser guide path on the Bailian / Model Studio console. */ +export const AKSK_GUIDE_PATH = "/aksk-guide"; + +/** Build the OpenAPI AK/SK browser guide URL for a console origin. */ +export function akskGuidePage(consoleOrigin: string): string { + return `${consoleOrigin.replace(/\/$/, "")}${AKSK_GUIDE_PATH}`; +} + /** Running-time billing, shared trial allowance and model-call charges for RAG. */ export const KNOWLEDGE_BILLING_PAGE = "https://help.aliyun.com/zh/model-studio/billing-for-knowledge-base"; diff --git a/packages/runtime/tests/command-reference-output.test.ts b/packages/runtime/tests/command-reference-output.test.ts index ce80fa8c4..094928761 100644 --- a/packages/runtime/tests/command-reference-output.test.ts +++ b/packages/runtime/tests/command-reference-output.test.ts @@ -118,7 +118,9 @@ test.each(["bl", "aliyun bl"])( expect(hints[0]).toContain(`or run \`${commandPrefix} auth login\`.`); expect(hints[0]).toContain(`${commandPrefix} auth status`); expect(hints[0]).toContain("Get API Key:"); - expect(hints[1]).toContain(`or run \`${commandPrefix} auth login --open-api\`.`); + expect(hints[1]).toContain( + `or run \`${commandPrefix} auth login --open-api\` then paste your AccessKey.`, + ); expect(hints[1]).not.toMatch(/[\u4e00-\u9fff]/u); expect(hints[2]).toBe( "Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.", @@ -126,9 +128,10 @@ test.each(["bl", "aliyun bl"])( expect(hints[3]).toBe( "Set both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, or unset the partial env vars.", ); - expect(hints[4]).toBe( - `Run \`${commandPrefix} auth login --open-api --access-key-id --access-key-secret \` again to save a complete pair.`, + expect(hints[4]).toContain( + `Save a complete pair with \`${commandPrefix} auth login --open-api --access-key-id --access-key-secret \``, ); + expect(hints[4]).toContain(`\`${commandPrefix} auth login --open-api\` for the setup guide`); expect(hints.slice(1).join("\n")).not.toContain("auth status"); }, ); diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index e9e000da1..432c35154 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -41,12 +41,12 @@ bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxx ### `bl auth login` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `auth login` | -| **Description** | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | -| **Authentication** | No Auth | -| **Usage** | `bl auth login --api-key \| --console [--no-browser \| --token-stdin --console-region ] \| --open-api --access-key-id --access-key-secret ` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `auth login` | +| **Description** | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | +| **Authentication** | No Auth | +| **Usage** | `bl auth login --api-key \| --console [--no-browser \| --token-stdin --console-region ] \| --open-api [--no-browser] [--access-key-id --access-key-secret ]` | #### Flags @@ -55,11 +55,11 @@ bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxx | `--api-key ` | string | no | Model API key to validate and store | | `--base-url ` | string | no | Model API base URL to validate and store with --api-key | | `--console` | switch | no | Sign in via browser (China by default; use --console-site international for the international site). Creates an ordinary API key if needed; subscription plans require --api-key | -| `--no-browser` | switch | no | With --console, print the login URL without opening a browser | +| `--no-browser` | switch | no | With --console or --open-api (setup guide), print the URL without opening a browser | | `--token-stdin` | switch | no | With --console, read one raw access token from piped stdin and validate before saving; requires --console-region, no browser or local server | | `--console-region ` | string | no | Console gateway region (e.g. cn-beijing, ap-southeast-1) | | `--console-site ` | string | no | Console site: domestic, international | -| `--open-api` | switch | no | Store Alibaba Cloud OpenAPI AK/SK credentials | +| `--open-api` | switch | no | Open the AccessKey setup guide, or save keys when --access-key-id and --access-key-secret are both set | | `--access-key-id ` | string | no | Alibaba Cloud Access Key ID to store | | `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret to store | @@ -81,6 +81,14 @@ bl auth login --console --token-stdin --console-site international --console-reg bl auth login --api-key sk-xxxxx ``` +```bash +bl auth login --open-api +``` + +```bash +bl auth login --open-api --no-browser --console-site international +``` + ```bash bl auth login --open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx ``` diff --git a/skills/bailian-protocol/assets/setup.md b/skills/bailian-protocol/assets/setup.md index f53f7ad1c..123c74cf8 100644 --- a/skills/bailian-protocol/assets/setup.md +++ b/skills/bailian-protocol/assets/setup.md @@ -56,11 +56,11 @@ Verify: `bl --version` (prints `bl X.Y.Z`). For the exact command-to-auth mapping, read the owning skill's `reference/index.md` or run `bl --help`. -| Auth | How | Used by | -| ------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------- | -| Console | `bl auth login --console` or `... --console-site international` | Recommended; may create an ordinary API Key | -| API key | `bl auth login --api-key ` | Existing keys, including Token Plan consumption | -| OpenAPI AK/SK | `bl auth login --open-api --access-key-id --access-key-secret ` or Alibaba env vars | Token Plan management commands (`token-plan`) | +| Auth | How | Used by | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | +| Console | `bl auth login --console` or `... --console-site international` | Recommended; may create an ordinary API Key | +| API key | `bl auth login --api-key ` | Existing keys, including Token Plan consumption | +| OpenAPI AK/SK | Setup guide: `bl auth login --open-api`; if you already have keys: `bl auth login --open-api --access-key-id --access-key-secret `; or Alibaba env vars | Token Plan management / console recovery | ```bash bl auth status @@ -71,7 +71,7 @@ bl auth logout --open-api - Get a DashScope API key: https://bailian.console.aliyun.com/cn-beijing/?spm=a2ty07.github&tab=app#/api-key - Get a Token Plan API key: https://bailian.console.aliyun.com/cn-beijing?spm=a2ty07.github&tab=plan#/efm/subscription/overview -- Get an Alibaba Cloud AccessKey for OpenAPI AK/SK: https://ram.console.aliyun.com/manage/ak +- Get an Alibaba Cloud AccessKey for OpenAPI AK/SK: run `bl auth login --open-api` and follow the guide, then paste with `--access-key-id` / `--access-key-secret`; if you already have keys, pass them directly; or https://ram.console.aliyun.com/manage/ak - Console login: China site https://bailian.console.aliyun.com?spm=a2ty07.github or international site https://modelstudio.console.alibabacloud.com ### Token Plan model consumption From 33d192b1a59d5bc7ebe0a8e490c28fe73eb53812 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Thu, 26 Nov 2026 12:11:43 +0800 Subject: [PATCH 2/4] docs(auth): surface OpenAPI guide in protocol and auth status --- packages/commands/src/commands/auth/status.ts | 22 +++++++++++-------- packages/commands/tests/e2e/auth.e2e.test.ts | 6 ++--- skills/bailian-protocol/SKILL.md | 3 +++ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/packages/commands/src/commands/auth/status.ts b/packages/commands/src/commands/auth/status.ts index d29a04c71..28182863b 100644 --- a/packages/commands/src/commands/auth/status.ts +++ b/packages/commands/src/commands/auth/status.ts @@ -40,12 +40,20 @@ export default defineCommand({ const authenticated = !!(apiKey || consoleCred || openapi); const configName = settings.configName ?? "default"; const configFile = ctx.authStore.path; + const openApiGuide = formatCommand(identity, "auth login --open-api"); const modelKeyHint = apiKey ? undefined : localize({ "en-US": `No model API key is configured. Model commands need: ${formatCommand(identity, "auth login --console")}, or ${formatCommand(identity, "auth login --api-key ")}`, "zh-CN": `尚未配置模型 API Key。模型命令需要:${formatCommand(identity, "auth login --console")},或 ${formatCommand(identity, "auth login --api-key ")}`, }); + const openApiHint = openapi + ? undefined + : localize({ + "en-US": `OpenAPI (AK/SK) is not configured. To use AK/SK capabilities, run the browser guide: ${openApiGuide}`, + "zh-CN": `OpenAPI(AK/SK)未配置。如需使用 AK/SK 相关能力,可运行浏览器引导完成配置:${openApiGuide}`, + }); + const statusHint = [modelKeyHint, openApiHint].filter(Boolean).join("\n") || undefined; if (!authenticated) { ctx.output.result({ @@ -56,7 +64,7 @@ export default defineCommand({ hint: [ `API key (model): ${formatCommand(identity, "auth login --api-key ")} or DASHSCOPE_API_KEY`, `Console gateway: ${formatCommand(identity, "auth login --console")}`, - `OpenAPI (AK/SK): ${formatCommand(identity, "auth login --open-api")} (or paste --access-key-id / --access-key-secret)`, + `OpenAPI (AK/SK): ${openApiGuide} (browser guide; or paste --access-key-id / --access-key-secret)`, `Get API Key: ${API_KEY_PAGE}`, ].join("\n"), }); @@ -71,7 +79,7 @@ export default defineCommand({ api_key: apiKey, console: consoleCred, openapi, - ...(modelKeyHint ? { hint: modelKeyHint } : {}), + ...(statusHint ? { hint: statusHint } : {}), }); return; } @@ -97,12 +105,8 @@ export default defineCommand({ if (openapi) { lines.push(` OpenAPI (AK/SK): ${openapi.source} ${openapi.access_key_id}`); } else { - // 与 Console 行一致:状态一行说完,避免再重复 “未配置” - const openApiHint = localize({ - "en-US": `run ${formatCommand(identity, "auth login --open-api")} to get an AccessKey via the guide; if you already have one, configure with ${formatCommand(identity, "auth login --open-api --access-key-id --access-key-secret ")}`, - "zh-CN": `运行 ${formatCommand(identity, "auth login --open-api")} 按照引导获取 AccessKey,若已有 AccessKey,使用 ${formatCommand(identity, "auth login --open-api --access-key-id --access-key-secret ")} 进行配置`, - }); - lines.push(` OpenAPI (AK/SK): not configured (${openApiHint})`); + lines.push(" OpenAPI (AK/SK): not configured"); + if (openApiHint) lines.push(` ${openApiHint}`); } ctx.output.result( { @@ -112,7 +116,7 @@ export default defineCommand({ api_key: apiKey, console: consoleCred, openapi, - ...(modelKeyHint ? { hint: modelKeyHint } : {}), + ...(statusHint ? { hint: statusHint } : {}), }, { text: lines.join("\n") }, ); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index 292e2ff9b..36d7809a0 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -1181,6 +1181,8 @@ describe("e2e: auth", () => { expect(data.console?.region).toBe("cn-beijing"); expect(data.hint).toContain("尚未配置模型 API Key"); expect(data.hint).toContain("bl auth login --api-key "); + expect(data.hint).toContain("OpenAPI(AK/SK)未配置"); + expect(data.hint).toContain("bl auth login --open-api"); expect(json.stdout).not.toContain("console-token-placeholder"); const text = await runCommandE2e(AUTH_ROUTES, ["auth", "status", "--output", "text"], env); @@ -1188,10 +1190,8 @@ describe("e2e: auth", () => { expect(text.stdout).toContain("API key (model): not configured"); expect(text.stdout).toContain("尚未配置模型 API Key"); expect(text.stdout).toContain("OpenAPI (AK/SK): not configured"); + expect(text.stdout).toContain("OpenAPI(AK/SK)未配置"); expect(text.stdout).toContain("bl auth login --open-api"); - expect(text.stdout).toContain( - "bl auth login --open-api --access-key-id --access-key-secret ", - ); }); test("auth logout 清除当前 Config 的全部凭证和 Base URL,保留普通配置", async () => { diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index 01395fdce..d5b597bd0 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -173,9 +173,12 @@ Install, API key / console login, endpoint override, and config keys: **API Key login:** Token Plan and other subscription plans cannot use `--console`. For them, or when the user already has an ordinary API Key, run `bl auth login --api-key `. +**OpenAPI AK/SK:** When the user asks to configure AccessKey / AK/SK, run `bl auth login --open-api` (browser guide). If they already have keys, pass `--access-key-id` / `--access-key-secret`. + ```bash bl auth status # check current auth bl auth login --console --console-site international # example: international console +bl auth login --open-api # OpenAPI AK/SK browser guide bl text chat --message "Write a poem about spring" # explicit text-model smoke test ``` From a222f9fec36f9ccb71ffe411acac3e348aea9b5b Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Fri, 27 Nov 2026 12:43:51 +0800 Subject: [PATCH 3/4] fix(auth): preserve site/config in open-api paste command and report browser open accurately --- docs/agents/auth-change.md | 4 +- .../src/commands/auth/login-openapi-guide.ts | 68 ++++++---- packages/commands/src/commands/auth/login.ts | 32 +++-- packages/commands/tests/e2e/auth.e2e.test.ts | 38 +++++- .../tests/login-openapi-guide.test.ts | 127 ++++++++++++++++++ skills/bailian-cli/reference/auth.md | 16 ++- 6 files changed, 242 insertions(+), 43 deletions(-) create mode 100644 packages/commands/tests/login-openapi-guide.test.ts diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index 48bbc36c6..fcd10fd78 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -40,8 +40,8 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - `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 - 未显式传 `--config` 时,`sk-sp-*` 自动写入并激活 `token-plan`;普通 `sk-*` / `sk-ws-*` 仅在当前为 `token-plan` 时改写并激活 `default`,否则保留当前 Profile;其他格式不自动切换。显式 `--config` 始终优先。`sk-sp-*` 无论写入哪个 Profile 都会携带 Token Plan 的预设默认模型,并在保留已有项的基础上补齐 `api_key_capabilities`,不自动删除任何已有能力。登录仍不得删除其他鉴权域的凭证 - `bl auth login --console` 更新 `access_token` 以及回调携带的 console 作用域字段;若所选 Profile 没有模型 API Key,会要求控制台页面创建并回传一个普通 API Key 与 Base URL 一并保存。该回调结果不重复执行 `/models` 校验,且不会创建或配置 Token Plan -- `bl auth login --open-api` **不带** AK/SK:打开控制台 `/aksk-guide` 浏览器引导(非阻塞,不启本地 callback;SecretKey 不会经页面回传)。支持 `--no-browser` 只打印 URL,以及 `--console-site` 选择国内/国际站。引导完成后用户自行粘贴 `auth login --open-api --access-key-id … --access-key-secret …` -- `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` 域凭证 +- `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 +- `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 落盘路径均可用 - `auth status` 未配置 OpenAPI 时提示:先 `auth login --open-api` 按引导获取 AccessKey;若已有则用 `--access-key-id` / `--access-key-secret` 直接配置。缺凭证的 AUTH hint 同样指向 `auth login --open-api`,并保留成对 flag / env 说明 - `bl auth logout --console` 只清 `access_token` - `bl auth logout --open-api` 只清 `access_key_id` / `access_key_secret` / `security_token` diff --git a/packages/commands/src/commands/auth/login-openapi-guide.ts b/packages/commands/src/commands/auth/login-openapi-guide.ts index 8e723b6a3..e2f78f6ef 100644 --- a/packages/commands/src/commands/auth/login-openapi-guide.ts +++ b/packages/commands/src/commands/auth/login-openapi-guide.ts @@ -5,9 +5,16 @@ import { resolveConsoleOrigin, type LoginDeps } from "./login-console.ts"; export interface OpenApiGuideOptions { site?: string; + /** Profile name to echo as `--config` in the paste-ready command. */ + config?: string; noBrowser?: boolean; } +export interface OpenApiPasteOptions { + site?: string; + config?: string; +} + function localizeGuide(deps: LoginDeps, text: LocalizedText): string { if (typeof text === "string") return text; return deps.localize ? deps.localize(text) : text["en-US"]; @@ -19,23 +26,37 @@ export function resolveAkskGuideUrl(site?: string): string { } /** Paste-ready command after the browser guide completes. */ -export function openApiPasteCommand(identity: Identity): string { - return formatCommand( - identity, - "auth login --open-api --access-key-id --access-key-secret ", - ); +export function openApiPasteCommand(identity: Identity, options: OpenApiPasteOptions = {}): string { + const parts = ["auth login --open-api --access-key-id --access-key-secret "]; + // Always echo the resolved site. It is exactly the site the guide page targeted, + // so pinning it can never be wrong; omitting it lets a Profile default override an + // explicit choice (e.g. file `console_site: international` + `--console-site domestic` + // would otherwise save the credential to the international gateway). + if (options.site) { + parts.push(`--console-site ${options.site}`); + } + if (options.config?.trim()) { + parts.push(`--config ${options.config.trim()}`); + } + return formatCommand(identity, parts.join(" ")); } /** * Open (or print) the AK/SK guide page. Does not wait for a callback — SecretKey - * never returns through the browser. + * never returns through the browser. The URL and the paste-ready command are printed + * before awaiting the opener, so a slow or hanging `open` / `xdg-open` never withholds + * what the user needs to act on — the same ordering rule `login-console.ts` follows by + * registering the callback before opening the browser. */ export async function runOpenApiGuide( deps: LoginDeps, options: OpenApiGuideOptions = {}, -): Promise<{ url: string }> { +): Promise<{ url: string; browserOpened: boolean }> { const url = resolveAkskGuideUrl(options.site); - const paste = openApiPasteCommand(deps.identity); + const paste = openApiPasteCommand(deps.identity, { + site: options.site, + config: options.config, + }); deps.output.info( `${localizeGuide(deps, { @@ -44,20 +65,6 @@ export async function runOpenApiGuide( })}\n${url}`, ); - if (!options.noBrowser) { - void openInBrowser(url).then( - () => undefined, - (error: unknown) => { - deps.output.warning( - localizeGuide(deps, { - "en-US": `Could not open a browser automatically (${error instanceof Error ? error.message : String(error)}). Open the URL above manually.`, - "zh-CN": `无法自动打开浏览器(${error instanceof Error ? error.message : String(error)})。请手动打开上方地址。`, - }), - ); - }, - ); - } - deps.output.info( localizeGuide(deps, { "en-US": `After finishing the guide, return here and paste your AccessKey:\n ${paste}`, @@ -65,5 +72,20 @@ export async function runOpenApiGuide( }), ); - return { url }; + let browserOpened = false; + if (!options.noBrowser) { + try { + await openInBrowser(url); + browserOpened = true; + } catch (error: unknown) { + deps.output.warning( + localizeGuide(deps, { + "en-US": `Could not open a browser automatically (${error instanceof Error ? error.message : String(error)}). Open the URL above manually.`, + "zh-CN": `无法自动打开浏览器(${error instanceof Error ? error.message : String(error)})。请手动打开上方地址。`, + }), + ); + } + } + + return { url, browserOpened }; } diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index 5d43ed870..a7677e616 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -27,7 +27,7 @@ export default defineCommand({ }, auth: "none", usageArgs: - "--api-key | --console [--no-browser | --token-stdin --console-region ] | --open-api [--no-browser] [--access-key-id --access-key-secret ]", + "--api-key | --console [--no-browser | --token-stdin --console-region ] | --open-api [--no-browser] [--console-site ] [--access-key-id --access-key-secret ]", flags: { apiKey: { type: "string", @@ -118,6 +118,7 @@ export default defineCommand({ "--open-api", "--open-api --no-browser --console-site international", "--open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx", + "--open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx --console-site international", ], validate: (flags) => { const apiKeyMode = hasValue(flags.apiKey); @@ -126,7 +127,6 @@ export default defineCommand({ const openApiHasId = hasValue(flags.accessKeyId); const openApiHasSecret = hasValue(flags.accessKeySecret); const openApiPersist = openApiMode && openApiHasId && openApiHasSecret; - const openApiGuide = openApiMode && !openApiHasId && !openApiHasSecret; if (flags.tokenStdin || hasValue(flags.consoleRegion)) { if (!consoleMode) { @@ -151,8 +151,8 @@ export default defineCommand({ if (!apiKeyMode && hasValue(flags.baseUrl)) { return "Use --base-url only with --api-key"; } - if (hasValue(flags.consoleSite) && !consoleMode && !openApiGuide) { - return "Use --console-site with --console or --open-api (setup guide). / --console-site 只能与 --console 或 --open-api(配置引导)一起使用。"; + if (hasValue(flags.consoleSite) && !consoleMode && !openApiMode) { + return "Use --console-site with --console or --open-api. / --console-site 只能与 --console 或 --open-api 一起使用。"; } if (!openApiMode && (openApiHasId || openApiHasSecret)) { return "Use --open-api with --access-key-id and --access-key-secret"; @@ -305,8 +305,12 @@ export default defineCommand({ ); return; } - const { url } = await runOpenApiGuide(deps, { + // Global `--config` lives in settings, not command flags; recoveryConfigName + // is set for an explicit flag or an active named profile. + const pasteConfig = settings.recoveryConfigName?.trim() || undefined; + const { url, browserOpened } = await runOpenApiGuide(deps, { site, + config: pasteConfig, noBrowser: flags.noBrowser, }); ctx.output.result( @@ -315,6 +319,7 @@ export default defineCommand({ method: "open-api-guide", url, no_browser: !!flags.noBrowser, + browser_opened: browserOpened, config: settings.configName ?? "default", config_file: store.path, }, @@ -325,10 +330,19 @@ export default defineCommand({ "en-US": "Browser not opened automatically. Open the URL above manually.", "zh-CN": "未自动打开浏览器,请手动打开上方地址。", } - : { - "en-US": "Opened the setup page in your default browser.", - "zh-CN": "已在默认浏览器打开引导页面。", - }, + : browserOpened + ? { + "en-US": "Opened the setup page in your default browser.", + "zh-CN": "已在默认浏览器打开引导页面。", + } + : { + // The warning above already carries the errno reason and the + // manual-open instruction, so the status line reports what is + // still usable instead of repeating that the browser did not open. + "en-US": + "Guide URL and follow-up command printed above; paste your AccessKey after finishing the guide.", + "zh-CN": "已打印引导地址与后续命令,完成引导后粘贴 AccessKey 即可。", + }, ), }, ); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index 36d7809a0..89cc694b7 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -117,7 +117,7 @@ describe("e2e: auth", () => { ]); expect(consoleSiteWithoutConsole.exitCode).toBe(2); expect(consoleSiteWithoutConsole.stderr).toMatch( - /Use --console-site with --console or --open-api \(setup guide\)/, + /Use --console-site with --console or --open-api/, ); }); @@ -148,7 +148,16 @@ describe("e2e: auth", () => { const noBrowser = await runCommandE2e( AUTH_ROUTES, - ["auth", "login", "--open-api", "--no-browser", "--console-site", "international"], + [ + "auth", + "login", + "--open-api", + "--no-browser", + "--console-site", + "international", + "--config", + "release-review", + ], { BAILIAN_CONFIG_DIR: configDir }, ); expect(noBrowser.exitCode, noBrowser.stderr).toBe(0); @@ -156,10 +165,33 @@ describe("e2e: auth", () => { /modelstudio\.console\.alibabacloud\.com\/aksk-guide/, ); expect(noBrowser.stdout + noBrowser.stderr).toMatch( - /auth login --open-api --access-key-id --access-key-secret /, + /auth login --open-api --access-key-id --access-key-secret --console-site international --config release-review/, ); expect(existsSync(join(configDir, "config.json"))).toBe(false); + const persistWithSite = await runCommandE2e( + AUTH_ROUTES, + [ + "auth", + "login", + "--open-api", + "--access-key-id", + "LTAI-e2e", + "--access-key-secret", + "secret-e2e", + "--console-site", + "international", + // Mirror the full echoed paste command, `--config` included, so the + // guide output stays something the user can paste back verbatim. + "--config", + "release-review", + "--dry-run", + ], + { BAILIAN_CONFIG_DIR: configDir }, + ); + expect(persistWithSite.exitCode, persistWithSite.stderr).toBe(0); + expect(persistWithSite.stdout).toMatch(/Would save AccessKey credentials/); + const noBrowserWithKeys = await runCommandE2e(AUTH_ROUTES, [ "auth", "login", diff --git a/packages/commands/tests/login-openapi-guide.test.ts b/packages/commands/tests/login-openapi-guide.test.ts new file mode 100644 index 000000000..0200ce9bf --- /dev/null +++ b/packages/commands/tests/login-openapi-guide.test.ts @@ -0,0 +1,127 @@ +import { buildSettings, type AuthStore, type Identity, type LocalizedText } from "bailian-cli-core"; +import { expect, test, vi } from "vite-plus/test"; + +const openInBrowser = vi.hoisted(() => vi.fn<(url: string) => Promise>()); + +vi.mock("../src/commands/shared/local-server.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + openInBrowser: (url: string) => openInBrowser(url), + }; +}); + +import { openApiPasteCommand, runOpenApiGuide } from "../src/commands/auth/login-openapi-guide.ts"; +import type { LoginDeps } from "../src/commands/auth/login-console.ts"; + +const identity = { binName: "bl" } as Identity; + +function localize(text: LocalizedText): string { + return typeof text === "string" ? text : text["en-US"]; +} + +function messageText(message: unknown): string { + if (typeof message === "string") return message; + if (message && typeof message === "object" && "en-US" in message) { + return String((message as { "en-US": string })["en-US"]); + } + return String(message); +} + +function makeDeps(options?: { infos?: string[]; warnings?: string[] }): LoginDeps { + const infos = options?.infos; + const warnings = options?.warnings; + return { + identity, + settings: buildSettings({ flags: {}, file: {}, env: {} }), + authStore: {} as AuthStore, + localize, + output: { + info: (message) => { + infos?.push(messageText(message)); + }, + warning: (message) => { + warnings?.push(messageText(message)); + }, + debug: () => undefined, + }, + }; +} + +test("openApiPasteCommand keeps non-domestic site and explicit config", () => { + expect(openApiPasteCommand(identity)).toBe( + "bl auth login --open-api --access-key-id --access-key-secret ", + ); + expect(openApiPasteCommand(identity, { site: "domestic" })).toBe( + "bl auth login --open-api --access-key-id --access-key-secret --console-site domestic", + ); + expect(openApiPasteCommand(identity, { site: "international", config: "release-review" })).toBe( + "bl auth login --open-api --access-key-id --access-key-secret --console-site international --config release-review", + ); + // An explicit domestic has to survive paste-back: dropping the flag would let a + // Profile default of `console_site: international` win on the save path. + expect(openApiPasteCommand(identity, { site: "domestic", config: "p" })).toBe( + "bl auth login --open-api --access-key-id --access-key-secret --console-site domestic --config p", + ); +}); + +test("runOpenApiGuide awaits browser open and reports failure without claiming success", async () => { + const warnings: string[] = []; + const infos: string[] = []; + openInBrowser.mockReset(); + openInBrowser.mockRejectedValue(new Error("spawn open ENOENT")); + + const result = await runOpenApiGuide(makeDeps({ infos, warnings }), { + site: "international", + config: "release-review", + }); + + expect(result.browserOpened).toBe(false); + expect(result.url).toMatch(/modelstudio\.console\.alibabacloud\.com\/aksk-guide/); + expect(openInBrowser).toHaveBeenCalledOnce(); + expect(warnings.join("\n")).toMatch(/Could not open a browser automatically/); + expect(infos.join("\n")).toMatch(/--console-site international --config release-review/); + expect(infos.join("\n")).not.toMatch(/Opened the setup page/); +}); + +test("runOpenApiGuide marks browserOpened when open succeeds", async () => { + openInBrowser.mockReset(); + openInBrowser.mockResolvedValue(undefined); + + const result = await runOpenApiGuide(makeDeps(), { site: "domestic", noBrowser: false }); + + expect(result.browserOpened).toBe(true); + expect(openInBrowser).toHaveBeenCalledOnce(); +}); + +test("runOpenApiGuide prints the paste command before the opener resolves", async () => { + let releaseOpen: () => void = () => undefined; + openInBrowser.mockReset(); + openInBrowser.mockImplementation( + () => + new Promise((resolve) => { + releaseOpen = resolve; + }), + ); + + const infos: string[] = []; + const pendingGuide = runOpenApiGuide(makeDeps({ infos }), { site: "international" }); + + // A hanging `open` / `xdg-open` must not withhold the actionable output. + await new Promise((resolve) => setImmediate(resolve)); + expect(infos.join("\n")).toMatch( + /--access-key-id --access-key-secret --console-site international/, + ); + + releaseOpen(); + expect((await pendingGuide).browserOpened).toBe(true); +}); + +test("runOpenApiGuide with --no-browser skips openInBrowser", async () => { + openInBrowser.mockReset(); + + const result = await runOpenApiGuide(makeDeps(), { noBrowser: true }); + + expect(result.browserOpened).toBe(false); + expect(openInBrowser).not.toHaveBeenCalled(); +}); diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index 432c35154..8d74dd2ef 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -41,12 +41,12 @@ bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxx ### `bl auth login` -| Field | Value | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `auth login` | -| **Description** | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | -| **Authentication** | No Auth | -| **Usage** | `bl auth login --api-key \| --console [--no-browser \| --token-stdin --console-region ] \| --open-api [--no-browser] [--access-key-id --access-key-secret ]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `auth login` | +| **Description** | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | +| **Authentication** | No Auth | +| **Usage** | `bl auth login --api-key \| --console [--no-browser \| --token-stdin --console-region ] \| --open-api [--no-browser] [--console-site ] [--access-key-id --access-key-secret ]` | #### Flags @@ -93,6 +93,10 @@ bl auth login --open-api --no-browser --console-site international bl auth login --open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx ``` +```bash +bl auth login --open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx --console-site international +``` + ### `bl auth logout` | Field | Value | From 255a28d72da8d5d7b18b8db908051781335be7bc Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Fri, 27 Nov 2026 14:44:10 +0800 Subject: [PATCH 4/4] feat(auth): implement timeout for browser opener and enhance error handling in OpenAPI guide --- docs/agents/auth-change.md | 6 +- .../src/commands/auth/login-openapi-guide.ts | 40 ++++-- packages/commands/src/commands/auth/login.ts | 17 ++- .../src/commands/shared/local-server.ts | 33 ++++- .../tests/auth-login-openapi-site.test.ts | 118 ++++++++++++++++++ .../tests/local-server-open-path.test.ts | 89 +++++++++++++ .../tests/login-openapi-guide.test.ts | 29 ++++- 7 files changed, 314 insertions(+), 18 deletions(-) create mode 100644 packages/commands/tests/auth-login-openapi-site.test.ts create mode 100644 packages/commands/tests/local-server-open-path.test.ts diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index fcd10fd78..35d576cfa 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -40,8 +40,10 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - `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 - 未显式传 `--config` 时,`sk-sp-*` 自动写入并激活 `token-plan`;普通 `sk-*` / `sk-ws-*` 仅在当前为 `token-plan` 时改写并激活 `default`,否则保留当前 Profile;其他格式不自动切换。显式 `--config` 始终优先。`sk-sp-*` 无论写入哪个 Profile 都会携带 Token Plan 的预设默认模型,并在保留已有项的基础上补齐 `api_key_capabilities`,不自动删除任何已有能力。登录仍不得删除其他鉴权域的凭证 - `bl auth login --console` 更新 `access_token` 以及回调携带的 console 作用域字段;若所选 Profile 没有模型 API Key,会要求控制台页面创建并回传一个普通 API Key 与 Base URL 一并保存。该回调结果不重复执行 `/models` 校验,且不会创建或配置 Token Plan -- `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 -- `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 落盘路径均可用 +- `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」 +- `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 住事件循环(实测仍等满) +- `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 +- **命令自有 flag 与 `settings` 的同名字段**:`create-cli.ts` 只把全局 flag 与凭证域 flag(`GLOBAL_FLAGS` + `credentialFlagDefs(cmd)`)放进 `sources`,命令 `flags` map 里声明的键只进 `ctx.flags`。因此 `auth: "none"` 这类命令里,`settings.` **读不到用户传的 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 生效」的证据 - `auth status` 未配置 OpenAPI 时提示:先 `auth login --open-api` 按引导获取 AccessKey;若已有则用 `--access-key-id` / `--access-key-secret` 直接配置。缺凭证的 AUTH hint 同样指向 `auth login --open-api`,并保留成对 flag / env 说明 - `bl auth logout --console` 只清 `access_token` - `bl auth logout --open-api` 只清 `access_key_id` / `access_key_secret` / `security_token` diff --git a/packages/commands/src/commands/auth/login-openapi-guide.ts b/packages/commands/src/commands/auth/login-openapi-guide.ts index e2f78f6ef..108a806d8 100644 --- a/packages/commands/src/commands/auth/login-openapi-guide.ts +++ b/packages/commands/src/commands/auth/login-openapi-guide.ts @@ -1,8 +1,15 @@ import { formatCommand, type Identity, type LocalizedText } from "bailian-cli-core"; import { akskGuidePage } from "bailian-cli-runtime"; -import { openInBrowser } from "../shared/local-server.ts"; +import { isOpenPathTimeout, openInBrowser } from "../shared/local-server.ts"; import { resolveConsoleOrigin, type LoginDeps } from "./login-console.ts"; +/** + * How long this guide may wait on the OS opener before calling the outcome + * unconfirmed. The command prints a paste-ready follow-up command and must hand the + * prompt back for it, so it opts into a cap that other `openPath` callers do not pay. + */ +const OPEN_WAIT_CAP_MS = 5_000; + export interface OpenApiGuideOptions { site?: string; /** Profile name to echo as `--config` in the paste-ready command. */ @@ -47,6 +54,11 @@ export function openApiPasteCommand(identity: Identity, options: OpenApiPasteOpt * before awaiting the opener, so a slow or hanging `open` / `xdg-open` never withholds * what the user needs to act on — the same ordering rule `login-console.ts` follows by * registering the callback before opening the browser. + * + * The wait is capped via `openInBrowser(url, { timeoutMs })`: on desktops where + * `xdg-open` stays attached to the browser, an uncapped await would keep the prompt + * away and the user could not paste the follow-up command. An opener killed at that + * cap is an unconfirmed outcome — never reported as a failure, never as a success. */ export async function runOpenApiGuide( deps: LoginDeps, @@ -75,15 +87,27 @@ export async function runOpenApiGuide( let browserOpened = false; if (!options.noBrowser) { try { - await openInBrowser(url); + await openInBrowser(url, { timeoutMs: OPEN_WAIT_CAP_MS }); browserOpened = true; } catch (error: unknown) { - deps.output.warning( - localizeGuide(deps, { - "en-US": `Could not open a browser automatically (${error instanceof Error ? error.message : String(error)}). Open the URL above manually.`, - "zh-CN": `无法自动打开浏览器(${error instanceof Error ? error.message : String(error)})。请手动打开上方地址。`, - }), - ); + if (isOpenPathTimeout(error)) { + deps.output.warning( + localizeGuide(deps, { + "en-US": + "Could not confirm the browser opened: the system open command did not return in time. Open the URL above manually if no tab appeared.", + "zh-CN": + "未能确认浏览器是否打开:系统打开命令超时未返回。若没有新标签页,请手动打开上方地址。", + }), + ); + } else { + const reason = error instanceof Error ? error.message : String(error); + deps.output.warning( + localizeGuide(deps, { + "en-US": `Could not open a browser automatically (${reason}). Open the URL above manually.`, + "zh-CN": `无法自动打开浏览器(${reason})。请手动打开上方地址。`, + }), + ); + } } } diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index a7677e616..20d2028a5 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -362,21 +362,32 @@ export default defineCommand({ return; } const resolvedBaseUrl = store.resolveBaseUrl(); - const target = resolveCLIAccessTokenTarget(settings, resolvedBaseUrl); + // `--console-site` is a command-own flag: create-cli routes only global and + // credential-domain flags into `sources`, so it never reaches `settings` for this + // command (auth: "none"). Reading `settings.consoleSite` alone silently ignored the + // flag — a new Profile asked for international saved domestic, and an international + // Profile asked for domestic saved international. Honour the flag exactly like the + // guide branch above already does, and reuse the same value for every hop: + // generateCLIAccessToken re-derives the target from `settings` internally. + const effectiveSettings = { + ...settings, + consoleSite: site as "domestic" | "international", + }; + const target = resolveCLIAccessTokenTarget(effectiveSettings, resolvedBaseUrl); ctx.output.progress({ "en-US": "Generating CLI access token...", "zh-CN": "正在生成 CLI access token...", }); const resp = await generateCLIAccessToken({ identity, - settings, + settings: effectiveSettings, debug: (record) => ctx.output.debug(record), baseUrl: resolvedBaseUrl, accessKeyId: flags.accessKeyId!, accessKeySecret: flags.accessKeySecret!, }); const accessToken = resp.cliAccessToken; - await validateConsoleAccessToken({ ...target, token: accessToken }, settings, { + await validateConsoleAccessToken({ ...target, token: accessToken }, effectiveSettings, { debug: (record) => ctx.output.debug(record), }); await store.login({ diff --git a/packages/commands/src/commands/shared/local-server.ts b/packages/commands/src/commands/shared/local-server.ts index f2c6fa0c1..911cd23cb 100644 --- a/packages/commands/src/commands/shared/local-server.ts +++ b/packages/commands/src/commands/shared/local-server.ts @@ -66,11 +66,35 @@ export function buildOpenInvocation(target: string, platform = process.platform) return { command: "xdg-open", args: [target] }; } +export interface OpenPathOptions { + /** + * Kill the opener after this many milliseconds. Left unset, the promise waits as + * long as the OS handler takes — the historical behaviour, and deliberately still + * the default: callers like `config ui` map a rejected opener onto an HTTP 400 or a + * "could not open" warning, so a blanket cap would turn "slow but already opened" + * into a false failure. Callers that must hand the terminal back pass `timeoutMs`. + */ + timeoutMs?: number; +} + +/** + * True when {@link openPath} killed the opener at its own cap, as opposed to the OS + * handler failing. Any caller that sets `timeoutMs` must branch on this, so an + * unconfirmed open is reported as "not confirmed" rather than "could not open". + */ +export function isOpenPathTimeout(error: unknown): boolean { + return error instanceof Error && (error as { killed?: boolean }).killed === true; +} + /** * Open a local file, directory, or URL with the OS default handler * (best-effort, cross-platform). + * + * When `timeoutMs` is set the child is killed at the cap. Killing is what releases + * Node's event loop: `child.unref()` alone does not, because `execFile` keeps ref'd + * stdout/stderr pipe handles, so an unref'd opener still delays the prompt. */ -export function openPath(target: string): Promise { +export function openPath(target: string, options: OpenPathOptions = {}): Promise { const invocation = buildOpenInvocation(target); return new Promise((resolve, reject) => { execFile( @@ -79,6 +103,9 @@ export function openPath(target: string): Promise { { windowsHide: true, windowsVerbatimArguments: invocation.windowsVerbatimArguments, + ...(options.timeoutMs === undefined + ? {} + : { timeout: options.timeoutMs, killSignal: "SIGTERM" }), }, (err) => { if (err) reject(err); @@ -89,6 +116,6 @@ export function openPath(target: string): Promise { } /** Open a URL in the user's default browser (best-effort, cross-platform). */ -export function openInBrowser(url: string): Promise { - return openPath(url); +export function openInBrowser(url: string, options?: OpenPathOptions): Promise { + return openPath(url, options); } diff --git a/packages/commands/tests/auth-login-openapi-site.test.ts b/packages/commands/tests/auth-login-openapi-site.test.ts new file mode 100644 index 000000000..594f23e2f --- /dev/null +++ b/packages/commands/tests/auth-login-openapi-site.test.ts @@ -0,0 +1,118 @@ +import { buildSettings, type AuthStore, type Identity, type LocalizedText } from "bailian-cli-core"; +import { expect, test, vi } from "vite-plus/test"; + +// 换票与控制台校验是这条链路仅有的两处网络出口。mock 掉它们,才能把断言集中在 +// 「用户传的 --console-site 最终落到了哪里」,而不是依赖真实 AK/SK。 +type ConsoleSite = "domestic" | "international"; +type TokenRequest = { settings: { consoleSite?: ConsoleSite }; baseUrl: string }; +type GatewayTarget = { region: string; site: ConsoleSite; token: string }; + +const generateCLIAccessToken = vi.hoisted(() => + vi.fn<(request: TokenRequest) => Promise<{ cliAccessToken: string }>>(async () => ({ + cliAccessToken: "cli-token-fake", + })), +); +const validateConsoleAccessToken = vi.hoisted(() => + vi.fn<(target: GatewayTarget, settings: unknown, diagnostics: unknown) => Promise>( + async () => undefined, + ), +); + +vi.mock("bailian-cli-core", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + generateCLIAccessToken: (request: TokenRequest) => generateCLIAccessToken(request), + validateConsoleAccessToken: (target: GatewayTarget, settings: unknown, diagnostics: unknown) => + validateConsoleAccessToken(target, settings, diagnostics), + }; +}); + +import login from "../src/commands/auth/login.ts"; + +const identity: Identity = { + binName: "bl", + version: "test", + npmPackage: "bailian-cli", + clientName: "bailian-cli-test", +}; + +interface Harness { + savedPatch: Record; + gatewayTarget: GatewayTarget | undefined; +} + +/** + * `--console-site` 是命令自有 flag:create-cli 只把全局 flag 与凭证域 flag 放进 + * sources,所以它永远进不了 `settings`。落盘链路必须自己尊重 `ctx.flags`, + * 否则会出现「新 Profile 传 international 存成 domestic」这类静默忽略。 + */ +async function runPersist( + flagSite: ConsoleSite | undefined, + settingsSite: ConsoleSite | undefined, +): Promise { + generateCLIAccessToken.mockClear(); + validateConsoleAccessToken.mockClear(); + const savedPatch: Record = {}; + + const store = { + path: "/tmp/unused/config.json", + resolveBaseUrl: () => "https://dashscope.aliyuncs.com/compatible-mode/v1", + stored: () => ({}), + async login(patch: Record) { + Object.assign(savedPatch, patch); + }, + } as unknown as AuthStore; + + const settings = { + ...buildSettings({ flags: {}, file: {}, env: {} }), + consoleSite: settingsSite, + }; + const flags = { + openApi: true, + accessKeyId: "LTAI-fake", + accessKeySecret: "secret-fake", + ...(flagSite === undefined ? {} : { consoleSite: flagSite }), + }; + + await login.run({ + identity, + settings, + flags, + authStore: store, + localize: (text: LocalizedText) => (typeof text === "string" ? text : text["en-US"]), + output: { + info: () => undefined, + warning: () => undefined, + progress: () => undefined, + result: () => undefined, + debug: () => undefined, + }, + } as never); + + return { savedPatch, gatewayTarget: validateConsoleAccessToken.mock.calls[0]?.[0] }; +} + +test("显式 --console-site international 落到新 Profile(settings 里什么都没有)", async () => { + const { savedPatch, gatewayTarget } = await runPersist("international", undefined); + expect(savedPatch.console_site).toBe("international"); + expect(gatewayTarget?.site).toBe("international"); +}); + +test("显式 --console-site domestic 覆盖 Profile 里已存的 international", async () => { + const { savedPatch, gatewayTarget } = await runPersist("domestic", "international"); + expect(savedPatch.console_site).toBe("domestic"); + expect(gatewayTarget?.site).toBe("domestic"); +}); + +test("不传 --console-site 时仍沿用 Profile 默认", async () => { + const { savedPatch, gatewayTarget } = await runPersist(undefined, "international"); + expect(savedPatch.console_site).toBe("international"); + expect(gatewayTarget?.site).toBe("international"); +}); + +test("换票请求也使用被覆盖后的站点(generateCLIAccessToken 内部会重算 target)", async () => { + await runPersist("domestic", "international"); + const request = generateCLIAccessToken.mock.calls[0]?.[0]; + expect(request?.settings.consoleSite).toBe("domestic"); +}); diff --git a/packages/commands/tests/local-server-open-path.test.ts b/packages/commands/tests/local-server-open-path.test.ts new file mode 100644 index 000000000..2e1a0b3d3 --- /dev/null +++ b/packages/commands/tests/local-server-open-path.test.ts @@ -0,0 +1,89 @@ +import { expect, test, vi } from "vite-plus/test"; + +const execFileMock = vi.hoisted(() => vi.fn()); + +vi.mock("node:child_process", () => ({ + execFile: (...args: unknown[]) => execFileMock(...args), +})); + +import { isOpenPathTimeout, openPath } from "../src/commands/shared/local-server.ts"; + +function lastOptions(): { timeout?: number; killSignal?: string } { + return execFileMock.mock.calls[0]?.[2] as { timeout?: number; killSignal?: string }; +} + +// 上限是 opt-in:共享调用方(config ui 的 /api/*/open、console 登录)把 reject 映射成 +// HTTP 400 或「无法打开默认浏览器」,默认设上限会把「已打开但慢」误报成失败。 +test("默认不设上限,保持既有语义", () => { + execFileMock.mockClear(); + execFileMock.mockImplementation(() => undefined); + void openPath("https://example.com"); + + const options = lastOptions(); + expect(options.timeout).toBeUndefined(); + expect(options.killSignal).toBeUndefined(); +}); + +test("显式传 timeoutMs 才设上限,并以 SIGTERM 杀掉以释放事件循环", () => { + execFileMock.mockClear(); + execFileMock.mockImplementation(() => undefined); + void openPath("https://example.com", { timeoutMs: 5_000 }); + + const options = lastOptions(); + expect(options.timeout).toBe(5_000); + expect(options.killSignal).toBe("SIGTERM"); +}); + +test("被 timeout 杀掉的打开器归类为超时,而不是失败", async () => { + execFileMock.mockClear(); + execFileMock.mockImplementation( + ( + _command: string, + _args: string[], + _options: unknown, + callback: (err: Error | null) => void, + ) => { + const killed = Object.assign(new Error("Command failed"), { + killed: true, + signal: "SIGTERM", + }); + callback(killed); + }, + ); + + const error = await openPath("https://example.com").catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(Error); + expect(isOpenPathTimeout(error)).toBe(true); +}); + +test("正常失败(ENOENT / 非零退出)不被误判为超时", async () => { + execFileMock.mockClear(); + execFileMock.mockImplementation( + ( + _command: string, + _args: string[], + _options: unknown, + callback: (err: Error | null) => void, + ) => { + callback(Object.assign(new Error("no display"), { killed: false })); + }, + ); + + const error = await openPath("https://example.com").catch((caught: unknown) => caught); + expect(isOpenPathTimeout(error)).toBe(false); +}); + +test("打开器成功返回时 promise 解决", async () => { + execFileMock.mockClear(); + execFileMock.mockImplementation( + ( + _command: string, + _args: string[], + _options: unknown, + callback: (err: Error | null) => void, + ) => { + callback(null); + }, + ); + await expect(openPath("https://example.com")).resolves.toBeUndefined(); +}); diff --git a/packages/commands/tests/login-openapi-guide.test.ts b/packages/commands/tests/login-openapi-guide.test.ts index 0200ce9bf..e1844c8b6 100644 --- a/packages/commands/tests/login-openapi-guide.test.ts +++ b/packages/commands/tests/login-openapi-guide.test.ts @@ -1,17 +1,20 @@ import { buildSettings, type AuthStore, type Identity, type LocalizedText } from "bailian-cli-core"; import { expect, test, vi } from "vite-plus/test"; -const openInBrowser = vi.hoisted(() => vi.fn<(url: string) => Promise>()); +const openInBrowser = vi.hoisted(() => + vi.fn<(url: string, options?: OpenPathOptions) => Promise>(), +); vi.mock("../src/commands/shared/local-server.ts", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - openInBrowser: (url: string) => openInBrowser(url), + openInBrowser: (url: string, options?: OpenPathOptions) => openInBrowser(url, options), }; }); import { openApiPasteCommand, runOpenApiGuide } from "../src/commands/auth/login-openapi-guide.ts"; +import type { OpenPathOptions } from "../src/commands/shared/local-server.ts"; import type { LoginDeps } from "../src/commands/auth/login-console.ts"; const identity = { binName: "bl" } as Identity; @@ -92,6 +95,8 @@ test("runOpenApiGuide marks browserOpened when open succeeds", async () => { expect(result.browserOpened).toBe(true); expect(openInBrowser).toHaveBeenCalledOnce(); + // 上限是引导自己选的,不是共享默认:其他调用方仍不设 timeout。 + expect(openInBrowser).toHaveBeenCalledWith(expect.any(String), { timeoutMs: 5_000 }); }); test("runOpenApiGuide prints the paste command before the opener resolves", async () => { @@ -117,6 +122,26 @@ test("runOpenApiGuide prints the paste command before the opener resolves", asyn expect((await pendingGuide).browserOpened).toBe(true); }); +test("runOpenApiGuide 在打开器被上限杀掉时报「未确认」而不是「失败」", async () => { + const warnings: string[] = []; + const infos: string[] = []; + openInBrowser.mockReset(); + openInBrowser.mockRejectedValue( + Object.assign(new Error("Command failed: open https://example.com"), { + killed: true, + signal: "SIGTERM", + }), + ); + + const result = await runOpenApiGuide(makeDeps({ infos, warnings }), { site: "domestic" }); + + expect(result.browserOpened).toBe(false); + expect(warnings.join("\n")).toMatch(/Could not confirm the browser opened/); + expect(warnings.join("\n")).not.toMatch(/Could not open a browser automatically/); + // 超时同样不能影响可操作输出:粘贴命令在等待之前就已打印。 + expect(infos.join("\n")).toMatch(/--access-key-id /); +}); + test("runOpenApiGuide with --no-browser skips openInBrowser", async () => { openInBrowser.mockReset();